Author: rhauch
Date: 2009-02-27 17:21:50 -0500 (Fri, 27 Feb 2009)
New Revision: 738
Added:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistry.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistry.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistry.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/AbstractNamespaceRegistryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistryTest.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/DnaLexicon.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSvLexicon.java
trunk/dna-jcr/src/test/resources/cars.xml
Removed:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistry.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistryTest.java
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/DnaLexicon.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContext.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/Graph.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/GraphImporter.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistry.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/LocationTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/AbstractValueComparatorsTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNameTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathOldTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathSegmentTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/InMemoryBinaryValueFactoryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/NameValueFactoryTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/PathValueFactoryTest.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrLexicon.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNamespaceRegistry.java
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/main/java/org/jboss/dna/jcr/JcrWorkspace.java
trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JackrabbitJcrTckTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNamespaceRegistryTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
Log:
DNA-286 Implement namespace management
This change provides a new implementation of the NamespaceRegistry interface of the JCR
API, along with refactoring the implementations of DNA's NamespaceRegistry. In
particular, a new GraphNamespaceRegistry class was added that stores the namespace
mappings in the graph content (under a location provided into the constructor). This
allowed the new JcrNamespaceRegistry to simply delegate to that and do the simple mapping
from DNA's interface to JCR's. (The refactoring also changed a number of test
cases that were directly instantiating a namespace registry.)
The other major change to the JCR implementation is the proper implementation of a
session-specific (non-shared and non-persistent) namespace registry, on top of the shared
(in a content-sense, not shared objects) and persistent registry that is in the
JcrWorkspace. This required changing how the JcrSession and JcrWorkspace objects are
created. The result is that now namespace mappings can be set on the session, and these
override those in the workspace (that would be used for all sessions that use that
repository's workspace).
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/DnaLexicon.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/DnaLexicon.java 2009-02-24 14:40:05
UTC (rev 737)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/DnaLexicon.java 2009-02-27 22:21:50
UTC (rev 738)
@@ -42,4 +42,5 @@
public static final Name CLASSPATH = new BasicName(Namespace.URI,
"classpath");
public static final Name PROJECTION_RULES = new BasicName(Namespace.URI,
"projectionRules");
public static final Name TIME_TO_EXPIRE = new BasicName(Namespace.URI,
"timeToExpire");
+ public static final Name NAMESPACE_URI = new BasicName(Namespace.URI,
"uri");
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContext.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContext.java 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContext.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -42,9 +42,10 @@
import org.jboss.dna.graph.property.Property;
import org.jboss.dna.graph.property.PropertyFactory;
import org.jboss.dna.graph.property.ValueFactories;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
import org.jboss.dna.graph.property.basic.BasicPropertyFactory;
+import org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry;
import org.jboss.dna.graph.property.basic.StandardValueFactories;
+import org.jboss.dna.graph.property.basic.ThreadSafeNamespaceRegistry;
/**
* An ExecutionContext is a representation of the environment or context in which a
component or operation is operating. Some
@@ -150,8 +151,8 @@
* {@link AccessController#getContext() current calling context}.
* @param accessControlContext the access control context, or null if a {@link
LoginContext} is provided or if the
* {@link AccessController#getContext() current calling context} should be
used
- * @param namespaceRegistry the namespace registry implementation, or null if a
{@link BasicNamespaceRegistry} instance should
- * be used
+ * @param namespaceRegistry the namespace registry implementation, or null if a
thread-safe version of
+ * {@link SimpleNamespaceRegistry} instance should be used
* @param valueFactories the {@link ValueFactories} implementation, or null if a
{@link StandardValueFactories} instance
* should be used
* @param propertyFactory the {@link PropertyFactory} implementation, or null if a
{@link BasicPropertyFactory} instance
@@ -175,7 +176,8 @@
} else {
this.subject = loginContext.getSubject();
}
- this.namespaceRegistry = namespaceRegistry == null ? new BasicNamespaceRegistry()
: namespaceRegistry;
+ this.namespaceRegistry = namespaceRegistry != null ? namespaceRegistry : new
ThreadSafeNamespaceRegistry(
+
new SimpleNamespaceRegistry());
this.valueFactories = valueFactories == null ? new
StandardValueFactories(this.namespaceRegistry) : valueFactories;
this.propertyFactory = propertyFactory == null ? new
BasicPropertyFactory(this.valueFactories) : propertyFactory;
this.classLoaderFactory = classLoaderFactory == null ? new
StandardClassLoaderFactory() : classLoaderFactory;
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/Graph.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/Graph.java 2009-02-24 14:40:05 UTC
(rev 737)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/Graph.java 2009-02-27 22:21:50 UTC
(rev 738)
@@ -511,7 +511,7 @@
public Move<Conjunction<Graph>> move( Property firstIdProperty,
Property... additionalIdProperties ) {
return new MoveAction<Conjunction<Graph>>(this.nextGraph,
this.requestQueue, Location.create(firstIdProperty,
-
additionalIdProperties));
+
additionalIdProperties));
}
/**
@@ -713,6 +713,134 @@
}
/**
+ * Begin the request to create a node located at the supplied path, and return an
interface used to either add properties for
+ * the new node, or complete/submit the request and return the location, node, or
graph.
+ * <p>
+ * If you have the {@link Location} of the parent (for the new node) from a previous
request, it is better and more efficient
+ * to use {@link #createUnder(Location)}. However, this method work just as well if
all you have is the {@link Path} to the
+ * parent or new node.
+ * </p>
+ *
+ * @param atPath the path to the node that is to be created.
+ * @return an object that may be used to start another request
+ */
+ public CreateAt<Graph> createAt( String atPath ) {
+ return createAt(createPath(atPath));
+ }
+
+ /**
+ * Begin the request to create a node located at the supplied path, and return an
interface used to either add properties for
+ * the new node, or complete/submit the request and return the location, node, or
graph.
+ * <p>
+ * If you have the {@link Location} of the parent (for the new node) from a previous
request, it is better and more efficient
+ * to use {@link #createUnder(Location)}. However, this method work just as well if
all you have is the {@link Path} to the
+ * parent or new node.
+ * </p>
+ *
+ * @param at the path to the node that is to be created.
+ * @return an object that may be used to start another request
+ */
+ public CreateAt<Graph> createAt( final Path at ) {
+ CheckArg.isNotNull(at, "at");
+ final Path parent = at.getParent();
+ final Name childName = at.getLastSegment().getName();
+ final String workspaceName = getCurrentWorkspaceName();
+ return new CreateAt<Graph>() {
+ private final List<Property> properties = new
LinkedList<Property>();
+
+ public CreateAt<Graph> and( UUID uuid ) {
+ PropertyFactory factory =
queue().getGraph().getContext().getPropertyFactory();
+ properties.add(factory.create(DnaLexicon.UUID, uuid));
+ return this;
+ }
+
+ public CreateAt<Graph> and( Property property ) {
+ properties.add(property);
+ return this;
+ }
+
+ public CreateAt<Graph> and( Iterable<Property> properties ) {
+ for (Property property : properties) {
+ this.properties.add(property);
+ }
+ return this;
+ }
+
+ public CreateAt<Graph> and( String name,
+ Object... values ) {
+ ExecutionContext context = queue().getGraph().getContext();
+ PropertyFactory factory = context.getPropertyFactory();
+ NameFactory nameFactory = context.getValueFactories().getNameFactory();
+ properties.add(factory.create(nameFactory.create(name), values));
+ return this;
+ }
+
+ public CreateAt<Graph> and( Name name,
+ Object... values ) {
+ ExecutionContext context = queue().getGraph().getContext();
+ PropertyFactory factory = context.getPropertyFactory();
+ properties.add(factory.create(name, values));
+ return this;
+ }
+
+ public CreateAt<Graph> and( Property property,
+ Property... additionalProperties ) {
+ properties.add(property);
+ for (Property additionalProperty : additionalProperties) {
+ properties.add(additionalProperty);
+ }
+ return this;
+ }
+
+ public CreateAt<Graph> with( UUID uuid ) {
+ return and(uuid);
+ }
+
+ public CreateAt<Graph> with( Property property ) {
+ return and(property);
+ }
+
+ public CreateAt<Graph> with( Iterable<Property> properties ) {
+ return and(properties);
+ }
+
+ public CreateAt<Graph> with( Property property,
+ Property... additionalProperties ) {
+ return and(property, additionalProperties);
+ }
+
+ public CreateAt<Graph> with( String name,
+ Object... values ) {
+ return and(name, values);
+ }
+
+ public CreateAt<Graph> with( Name name,
+ Object... values ) {
+ return and(name, values);
+ }
+
+ public Location getLocation() {
+ Location parentLoc = Location.create(parent);
+ CreateNodeRequest request = new CreateNodeRequest(parentLoc,
workspaceName, childName, this.properties);
+ queue().submit(request); // immediate
+ return request.getActualLocationOfNode();
+ }
+
+ public Node getNode() {
+ Location parentLoc = Location.create(parent);
+ CreateNodeRequest request = new CreateNodeRequest(parentLoc,
workspaceName, childName, this.properties);
+ queue().submit(request); // immediate
+ return getNodeAt(request.getActualLocationOfNode());
+ }
+
+ public Graph and() {
+ queue().submit(new CreateNodeRequest(Location.create(parent),
workspaceName, childName, this.properties));
+ return Graph.this;
+ }
+ };
+ }
+
+ /**
* Begin the request to create a node located at the supplied path. This request is
submitted to the repository immediately.
* <p>
* If you have the {@link Location} of the parent (for the new node) from a previous
request, it is better and more efficient
@@ -739,16 +867,13 @@
* parent or new node.
* </p>
*
- * @param atPath the path to the node that is to be created.
- * @param properties the properties for the new node
+ * @param at the path to the node that is to be created.
* @return an object that may be used to start another request
*/
- public Conjunction<Graph> create( String atPath,
- Property... properties ) {
- Path at = createPath(atPath);
+ public Conjunction<Graph> create( final Path at ) {
Path parent = at.getParent();
Name child = at.getLastSegment().getName();
- this.requestQueue.submit(new CreateNodeRequest(Location.create(parent),
getCurrentWorkspaceName(), child, properties));
+ this.requestQueue.submit(new CreateNodeRequest(Location.create(parent),
getCurrentWorkspaceName(), child));
return nextGraph;
}
@@ -760,14 +885,16 @@
* parent or new node.
* </p>
*
- * @param at the path to the node that is to be created.
+ * @param atPath the path to the node that is to be created.
+ * @param properties the properties for the new node
* @return an object that may be used to start another request
*/
- public Conjunction<Graph> create( Path at ) {
- CheckArg.isNotNull(at, "at");
+ public Conjunction<Graph> create( String atPath,
+ Property... properties ) {
+ Path at = createPath(atPath);
Path parent = at.getParent();
Name child = at.getLastSegment().getName();
- this.requestQueue.submit(new CreateNodeRequest(Location.create(parent),
getCurrentWorkspaceName(), child));
+ this.requestQueue.submit(new CreateNodeRequest(Location.create(parent),
getCurrentWorkspaceName(), child, properties));
return nextGraph;
}
@@ -1498,7 +1625,7 @@
public List<Location> startingAfter( Property
firstIdProperyOfPreviousSibling,
Property...
additionalIdPropertiesOfPreviousSibling ) {
return
startingAfter(Location.create(firstIdProperyOfPreviousSibling,
-
additionalIdPropertiesOfPreviousSibling));
+
additionalIdPropertiesOfPreviousSibling));
}
};
}
@@ -1965,7 +2092,7 @@
Property... additionalIdProperties ) {
assertNotExecuted();
return new MoveAction<BatchConjunction>(this.nextRequests,
this.requestQueue, Location.create(firstIdProperty,
-
additionalIdProperties));
+
additionalIdProperties));
}
/**
@@ -2107,7 +2234,7 @@
Property... additionalIdProperties ) {
assertNotExecuted();
return new CopyAction<BatchConjunction>(nextRequests,
this.requestQueue, Location.create(firstIdProperty,
-
additionalIdProperties));
+
additionalIdProperties));
}
/**
@@ -2322,7 +2449,7 @@
Path parent = at.getParent();
Name name = at.getLastSegment().getName();
return new CreateAction<Batch>(this, requestQueue,
Location.create(parent), getCurrentWorkspaceName(), name).with(firstProperty,
-
additionalProperties);
+
additionalProperties);
}
/**
@@ -2412,7 +2539,7 @@
Path parent = at.getParent();
Name name = at.getLastSegment().getName();
return new CreateAction<Batch>(this, requestQueue,
Location.create(parent), getCurrentWorkspaceName(), name).with(firstProperty,
-
additionalProperties);
+
additionalProperties);
}
/**
@@ -3406,9 +3533,9 @@
Next to( String desiredPath );
/**
- * Finish the request by specifying the Location.create where the node should be
copied/moved. Unlike {@link Into#into(Path)}
- * , which specifies the location of the parent and which assumes the new node
should have the same name as the original,
- * this method allows the caller to specify a new name for the new node.
+ * Finish the request by specifying the Location.create where the node should be
copied/moved. Unlike
+ * {@link Into#into(Path)} , which specifies the location of the parent and which
assumes the new node should have the
+ * same name as the original, this method allows the caller to specify a new name
for the new node.
*
* @param desiredPath the path for the new node
* @return the interface for additional requests or actions
@@ -3530,6 +3657,14 @@
Create<Next> with( Property property );
/**
+ * Specify property that should the new node should have. This is an alias for
{@link #and(Iterable)}.
+ *
+ * @param properties the properties that should be added
+ * @return this same interface so additional properties may be added
+ */
+ Create<Next> with( Iterable<Property> properties );
+
+ /**
* Specify a property that should the new node should have. This is an alias for
{@link #and(String, Object...)}.
*
* @param propertyName the name of the property
@@ -3576,6 +3711,15 @@
Create<Next> and( Property property );
/**
+ * Specify property that should the new node should have. This is equivalent to
calling {@link #and(Property)} for each of
+ * the properties in the supplied {@link Iterable}.
+ *
+ * @param properties the properties that should be added
+ * @return this same interface so additional properties may be added
+ */
+ Create<Next> and( Iterable<Property> properties );
+
+ /**
* Specify a property that should the new node should have.
*
* @param propertyName the name of the property
@@ -3607,6 +3751,137 @@
}
/**
+ * The interface for defining additional properties on a new node.
+ *
+ * @param <Next> The interface that is to be returned when this create request
is completed
+ * @author Randall Hauch
+ */
+ public interface CreateAt<Next> extends Conjunction<Next> {
+ /**
+ * Specify the UUID that should the new node should have. This is an alias for
{@link #and(UUID)}.
+ *
+ * @param uuid the UUID
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> with( UUID uuid );
+
+ /**
+ * Specify a property that should the new node should have. This is an alias for
{@link #and(Property)}.
+ *
+ * @param property the property
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> with( Property property );
+
+ /**
+ * Specify property that should the new node should have. This is an alias for
{@link #and(Iterable)}.
+ *
+ * @param properties the properties that should be added
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> with( Iterable<Property> properties );
+
+ /**
+ * Specify a property that should the new node should have. This is an alias for
{@link #and(String, Object...)}.
+ *
+ * @param propertyName the name of the property
+ * @param values the property values
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> with( String propertyName,
+ Object... values );
+
+ /**
+ * Specify a property that should the new node should have. This is an alias for
{@link #and(Name, Object...)}.
+ *
+ * @param propertyName the name of the property
+ * @param values the property values
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> with( Name propertyName,
+ Object... values );
+
+ /**
+ * Specify properties that should the new node should have. This is an alias for
{@link #and(Property, Property...)}.
+ *
+ * @param firstProperty the first property
+ * @param additionalProperties the additional property
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> with( Property firstProperty,
+ Property... additionalProperties );
+
+ /**
+ * Specify the UUID that should the new node should have.
+ *
+ * @param uuid the UUID
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> and( UUID uuid );
+
+ /**
+ * Specify a property that should the new node should have.
+ *
+ * @param property the property
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> and( Property property );
+
+ /**
+ * Specify property that should the new node should have. This is equivalent to
calling {@link #and(Property)} for each of
+ * the properties in the supplied {@link Iterable}.
+ *
+ * @param properties the properties that should be added
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> and( Iterable<Property> properties );
+
+ /**
+ * Specify a property that should the new node should have.
+ *
+ * @param propertyName the name of the property
+ * @param values the property values
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> and( String propertyName,
+ Object... values );
+
+ /**
+ * Specify a property that should the new node should have.
+ *
+ * @param propertyName the name of the property
+ * @param values the property values
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> and( Name propertyName,
+ Object... values );
+
+ /**
+ * Specify properties that should the new node should have.
+ *
+ * @param firstProperty the first property
+ * @param additionalProperties the additional property
+ * @return this same interface so additional properties may be added
+ */
+ CreateAt<Next> and( Property firstProperty,
+ Property... additionalProperties );
+
+ /**
+ * Complete this request, submit it, and return the actual location of the
created node.
+ *
+ * @return the actual location of the just-created node; never null
+ */
+ Location getLocation();
+
+ /**
+ * Complete this request, submit it, and return the actual node that was
created.
+ *
+ * @return the actual node that was just created; never null
+ */
+ Node getNode();
+ }
+
+ /**
* The interface for defining the node upon which a request operates.
*
* @param <Next> The interface that is to be returned when the request is
completed
@@ -5225,6 +5500,13 @@
return this;
}
+ public Create<T> and( Iterable<Property> properties ) {
+ for (Property property : properties) {
+ this.properties.add(property);
+ }
+ return this;
+ }
+
public Create<T> and( String name,
Object... values ) {
ExecutionContext context = queue().getGraph().getContext();
@@ -5259,6 +5541,10 @@
return and(property);
}
+ public Create<T> with( Iterable<Property> properties ) {
+ return and(properties);
+ }
+
public Create<T> with( Property property,
Property... additionalProperties ) {
return and(property, additionalProperties);
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/GraphImporter.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/GraphImporter.java 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/GraphImporter.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -112,14 +112,62 @@
CheckArg.isNotNull(uri, "uri");
CheckArg.isNotNull(location, "location");
CheckArg.isNotNull(location.getPath(), "location.getPath()");
+ InputStream stream = null;
+ try {
+ stream = uri.toURL().openStream();
+ return importXml(stream, location, skip);
+ } finally {
+ if (stream != null) stream.close();
+ }
+ }
+ /**
+ * Read the content from the supplied URI and import into the repository at the
supplied location. This method does <i>not</i>
+ * close the stream.
+ *
+ * @param stream the stream containing the content to be imported
+ * @param location the location in the {@link RepositorySource repository source}
where the content is to be written; may not
+ * be null
+ * @return the batch of requests for creating the graph content that represents the
imported content
+ * @throws IllegalArgumentException if the <code>stream</code> or
destination path are null
+ * @throws IOException if there is a problem reading the content
+ * @throws SAXException if there is a problem with the SAX Parser
+ * @throws RepositorySourceException if there is a problem while writing the content
to the {@link RepositorySource repository
+ * source}
+ */
+ public Graph.Batch importXml( InputStream stream,
+ Location location ) throws IOException, SAXException,
RepositorySourceException {
+ return importXml(stream, location, false);
+ }
+
+ /**
+ * Read the content from the supplied URI and import into the repository at the
supplied location. This method does <i>not</i>
+ * close the stream.
+ *
+ * @param stream the stream containing the content to be imported
+ * @param location the location in the {@link RepositorySource repository source}
where the content is to be written; may not
+ * be null
+ * @param skip true if the root element should be skipped, or false if a node should
be created for the root XML element
+ * @return the batch of requests for creating the graph content that represents the
imported content
+ * @throws IllegalArgumentException if the <code>stream</code> or
destination path are null
+ * @throws IOException if there is a problem reading the content
+ * @throws SAXException if there is a problem with the SAX Parser
+ * @throws RepositorySourceException if there is a problem while writing the content
to the {@link RepositorySource repository
+ * source}
+ */
+ public Graph.Batch importXml( InputStream stream,
+ Location location,
+ boolean skip ) throws IOException, SAXException,
RepositorySourceException {
+ CheckArg.isNotNull(stream, "uri");
+ CheckArg.isNotNull(location, "location");
+ CheckArg.isNotNull(location.getPath(), "location.getPath()");
+
// Create the destination for the XmlHandler ...
Graph.Batch batch = graph.batch();
XmlHandler.Destination destination = new CreateOnGraphInBatch(batch);
// Determine where the content is to be placed ...
Path parentPath = location.getPath();
- InputStream stream = null;
Name nameAttribute = JcrLexicon.NAME;
Name typeAttribute = JcrLexicon.PRIMARY_TYPE;
Name typeAttributeValue = null;
@@ -132,21 +180,54 @@
XmlHandler.AttributeScoping scoping =
XmlHandler.AttributeScoping.USE_DEFAULT_NAMESPACE;
XmlHandler handler = new XmlHandler(destination, skip, parentPath, decoder,
nameAttribute, typeAttribute,
typeAttributeValue, scoping);
- try {
- stream = uri.toURL().openStream();
- XMLReader reader = XMLReaderFactory.createXMLReader();
- reader.setContentHandler(handler);
- reader.setErrorHandler(handler);
- reader.parse(new InputSource(stream));
- } finally {
- if (stream != null) stream.close();
- }
+ XMLReader reader = XMLReaderFactory.createXMLReader();
+ reader.setContentHandler(handler);
+ reader.setErrorHandler(handler);
+ reader.parse(new InputSource(stream));
+ if (stream != null) stream.close();
return batch;
}
+ /**
+ * Return an {@link XmlHandler} that can be used to import content directly into the
supplied location. The operations
+ * resulting from the {@link XmlHandler} operations are batched until the {@link
XmlHandler#endDocument()} is called, at which
+ * point all enqueued operations are submitted to the graph.
+ *
+ * @param location the location in the {@link RepositorySource repository source}
where the content is to be written; may not
+ * be null
+ * @param skip true if the root element should be skipped, or false if a node should
be created for the root XML element
+ * @return the {@link XmlHandler} that can be used to import content
+ * @throws IllegalArgumentException if the <code>stream</code> or
destination path are null
+ */
+ public XmlHandler getHandlerForImportingXml( Location location,
+ boolean skip ) {
+ CheckArg.isNotNull(location, "location");
+ CheckArg.isNotNull(location.getPath(), "location.getPath()");
+
+ // Create the destination for the XmlHandler ...
+ Graph.Batch batch = graph.batch();
+ XmlHandler.Destination destination = new SubmitToGraphInBatch(batch);
+
+ // Determine where the content is to be placed ...
+ Path parentPath = location.getPath();
+ Name nameAttribute = JcrLexicon.NAME;
+ Name typeAttribute = JcrLexicon.PRIMARY_TYPE;
+ Name typeAttributeValue = null;
+ NamespaceRegistry reg = graph.getContext().getNamespaceRegistry();
+ if (reg.isRegisteredNamespaceUri(JcrNtLexicon.Namespace.URI)) {
+ typeAttributeValue = JcrNtLexicon.UNSTRUCTURED;
+ }
+
+ TextDecoder decoder = null;
+ XmlHandler.AttributeScoping scoping =
XmlHandler.AttributeScoping.USE_DEFAULT_NAMESPACE;
+ XmlHandler handler = new XmlHandler(destination, skip, parentPath, decoder,
nameAttribute, typeAttribute,
+ typeAttributeValue, scoping);
+ return handler;
+ }
+
@NotThreadSafe
- protected final static class CreateOnGraphInBatch implements Destination {
- private final Graph.Batch batch;
+ protected static class CreateOnGraphInBatch implements Destination {
+ protected final Graph.Batch batch;
protected CreateOnGraphInBatch( Graph.Batch batch ) {
assert batch != null;
@@ -181,4 +262,17 @@
}
}
+ @NotThreadSafe
+ protected final static class SubmitToGraphInBatch extends CreateOnGraphInBatch {
+ protected SubmitToGraphInBatch( Graph.Batch batch ) {
+ super(batch);
+ }
+
+ @Override
+ public void submit() {
+ super.submit();
+ batch.execute();
+ }
+ }
+
}
Deleted:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistry.java
===================================================================
---
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistry.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistry.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -1,275 +0,0 @@
-/*
- * JBoss DNA (
http://www.jboss.org/dna)
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * See the AUTHORS.txt file in the distribution for a full listing of
- * individual contributors.
- *
- * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
- * is licensed to you 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.
- *
- * JBoss DNA 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.graph.property.basic;
-
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import net.jcip.annotations.GuardedBy;
-import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.property.NamespaceRegistry;
-
-/**
- * @author Randall Hauch
- */
-@ThreadSafe
-public class BasicNamespaceRegistry implements NamespaceRegistry {
-
- public static final String DEFAULT_NAMESPACE_URI = "";
- public static final String DEFAULT_PREFIX_TEMPLATE = "ns##000";
- public static final String DEFAULT_PREFIX_NUMBER_FORMAT = "##000";
-
- private final ReadWriteLock registryLock = new ReentrantReadWriteLock();
- private final Map<String, String> namespacesByPrefix = new HashMap<String,
String>();
- private final Map<String, String> prefixesByNamespace = new HashMap<String,
String>();
- private String generatedPrefixTemplate = DEFAULT_PREFIX_TEMPLATE;
- private int nextGeneratedPrefixNumber = 1;
-
- /**
- *
- */
- public BasicNamespaceRegistry() {
- this(DEFAULT_NAMESPACE_URI);
- }
-
- /**
- * @param defaultNamespaceUri the namespace URI to use for the default prefix
- */
- public BasicNamespaceRegistry( final String defaultNamespaceUri ) {
- register("", defaultNamespaceUri);
- }
-
- /**
- * @return prefixTemplate
- */
- public String getGeneratedPrefixTemplate() {
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- return this.generatedPrefixTemplate;
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * @param prefixTemplate Sets prefixTemplate to the specified value.
- */
- public void setGeneratedPrefixTemplate( String prefixTemplate ) {
- if (prefixTemplate == null) prefixTemplate = DEFAULT_PREFIX_TEMPLATE;
- Lock lock = this.registryLock.writeLock();
- try {
- lock.lock();
- this.generatedPrefixTemplate = prefixTemplate;
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public String getNamespaceForPrefix( String prefix ) {
- CheckArg.isNotNull(prefix, "prefix");
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- return this.namespacesByPrefix.get(prefix);
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public String getPrefixForNamespaceUri( String namespaceUri,
- boolean generateIfMissing ) {
- CheckArg.isNotNull(namespaceUri, "namespaceUri");
- String prefix = null;
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- prefix = this.prefixesByNamespace.get(namespaceUri);
- } finally {
- lock.unlock();
- }
- if (prefix == null && generateIfMissing) {
- // Get a write lock ...
- lock = this.registryLock.writeLock();
- try {
- lock.lock();
- // Since we got a new lock, we need to check again ...
- prefix = this.prefixesByNamespace.get(namespaceUri);
- if (prefix == null) {
- // Now we can genereate a prefix and register it ...
- prefix = this.generatePrefix();
- this.register(prefix, namespaceUri);
- }
- return prefix;
- } finally {
- lock.unlock();
- }
- }
- return prefix;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isRegisteredNamespaceUri( String namespaceUri ) {
- CheckArg.isNotNull(namespaceUri, "namespaceUri");
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- return this.prefixesByNamespace.containsKey(namespaceUri);
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDefaultNamespaceUri() {
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- return this.namespacesByPrefix.get("");
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public String register( String prefix,
- String namespaceUri ) {
- CheckArg.isNotNull(namespaceUri, "namespaceUri");
- String previousNamespaceForPrefix = null;
- namespaceUri = namespaceUri.trim();
- Lock lock = this.registryLock.writeLock();
- try {
- lock.lock();
- if (prefix == null) prefix = generatePrefix();
- prefix = prefix.trim();
- prefix = prefix.replaceFirst("^:+", "");
- prefix = prefix.replaceFirst(":+$", "");
- previousNamespaceForPrefix = this.namespacesByPrefix.put(prefix,
namespaceUri);
- String previousPrefix = this.prefixesByNamespace.put(namespaceUri, prefix);
- if (previousPrefix != null && !previousPrefix.equals(prefix)) {
- this.namespacesByPrefix.remove(previousPrefix);
- }
- if (previousNamespaceForPrefix != null &&
!previousNamespaceForPrefix.equals(namespaceUri)) {
- this.prefixesByNamespace.remove(previousNamespaceForPrefix);
- }
- } finally {
- lock.unlock();
- }
- return previousNamespaceForPrefix;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.jboss.dna.graph.property.NamespaceRegistry#unregister(java.lang.String)
- */
- public boolean unregister( String namespaceUri ) {
- CheckArg.isNotNull(namespaceUri, "namespaceUri");
- namespaceUri = namespaceUri.trim();
- Lock lock = this.registryLock.writeLock();
- try {
- lock.lock();
- String prefix = this.prefixesByNamespace.remove(namespaceUri);
- if (prefix == null) return false;
- this.namespacesByPrefix.remove(prefix);
- } finally {
- lock.unlock();
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set<String> getRegisteredNamespaceUris() {
- Set<String> result = new HashSet<String>();
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- result.addAll(this.prefixesByNamespace.keySet());
- } finally {
- lock.unlock();
- }
- return Collections.unmodifiableSet(result);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see org.jboss.dna.graph.property.NamespaceRegistry#getNamespaces()
- */
- public Set<Namespace> getNamespaces() {
- Set<Namespace> result = new HashSet<Namespace>();
- Lock lock = this.registryLock.readLock();
- try {
- lock.lock();
- for (Map.Entry<String, String> entry :
this.namespacesByPrefix.entrySet()) {
- result.add(new BasicNamespace(entry.getKey(), entry.getValue()));
- }
- } finally {
- lock.unlock();
- }
- return Collections.unmodifiableSet(result);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- List<Namespace> namespaces = new
ArrayList<Namespace>(getNamespaces());
- Collections.sort(namespaces);
- return namespaces.toString();
- }
-
- @GuardedBy( "registryLock" )
- protected String generatePrefix() {
- DecimalFormat formatter = new DecimalFormat(this.generatedPrefixTemplate);
- return formatter.format(nextGeneratedPrefixNumber++);
- }
-
-}
Added:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistry.java
===================================================================
---
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistry.java
(rev 0)
+++
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistry.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,382 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * Unless otherwise indicated, all code in JBoss DNA is licensed
+ * to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import net.jcip.annotations.NotThreadSafe;
+import org.jboss.dna.common.util.CheckArg;
+import org.jboss.dna.graph.DnaLexicon;
+import org.jboss.dna.graph.Graph;
+import org.jboss.dna.graph.Location;
+import org.jboss.dna.graph.Node;
+import org.jboss.dna.graph.Subgraph;
+import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
+import org.jboss.dna.graph.property.Path;
+import org.jboss.dna.graph.property.PathFactory;
+import org.jboss.dna.graph.property.PathNotFoundException;
+import org.jboss.dna.graph.property.Property;
+import org.jboss.dna.graph.property.ValueFactory;
+
+/**
+ * A {@link NamespaceRegistry} implementation that stores the namespaces in a Graph as
individual nodes for each namespace, under
+ * a parent supplied by the constructor.
+ *
+ * @See {@link ThreadSafeNamespaceRegistry}
+ */
+@NotThreadSafe
+public class GraphNamespaceRegistry implements NamespaceRegistry {
+
+ public static final Name DEFAULT_URI_PROPERTY_NAME = DnaLexicon.NAMESPACE_URI;
+ public static final String GENERATED_PREFIX = "ns";
+
+ private SimpleNamespaceRegistry cache;
+ private final Graph store;
+ private final Path parentOfNamespaceNodes;
+ private final Name uriPropertyName;
+ private final List<Property> namespaceProperties;
+
+ public GraphNamespaceRegistry( Graph store,
+ Path parentOfNamespaceNodes,
+ Name uriPropertyName,
+ Property... additionalProperties ) {
+ this.cache = new SimpleNamespaceRegistry();
+ this.store = store;
+ this.parentOfNamespaceNodes = parentOfNamespaceNodes;
+ this.uriPropertyName = uriPropertyName != null ? uriPropertyName :
DEFAULT_URI_PROPERTY_NAME;
+ List<Property> properties = Collections.emptyList();
+ if (additionalProperties != null && additionalProperties.length != 0) {
+ properties = new ArrayList<Property>(additionalProperties.length);
+ Set<Name> propertyNames = new HashSet<Name>();
+ for (Property property : additionalProperties) {
+ if (!propertyNames.contains(property.getName()))
properties.add(property);
+ }
+ }
+ this.namespaceProperties = Collections.unmodifiableList(properties);
+ initializeCacheFromStore(cache);
+
+ // Load in the namespaces from the execution context used by the store ...
+ for (Namespace namespace :
store.getContext().getNamespaceRegistry().getNamespaces()) {
+ register(namespace.getPrefix(), namespace.getNamespaceUri());
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getNamespaceForPrefix( String prefix ) {
+ CheckArg.isNotNull(prefix, "prefix");
+ // Try the cache first ...
+ String uri = cache.getNamespaceForPrefix(prefix);
+ if (uri == null) {
+ // See if the store has it ...
+ uri = readUriFor(prefix);
+ if (uri != null) {
+ // update the cache ...
+ cache.register(prefix, uri);
+ }
+ }
+ return uri;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPrefixForNamespaceUri( String namespaceUri,
+ boolean generateIfMissing ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ // Try the cache first ...
+ String prefix = cache.getPrefixForNamespaceUri(namespaceUri, false);
+ if (prefix == null && generateIfMissing) {
+ prefix = readPrefixFor(namespaceUri, generateIfMissing);
+ if (prefix != null) {
+ cache.register(prefix, namespaceUri);
+ }
+ }
+ return prefix;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isRegisteredNamespaceUri( String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ if (cache.isRegisteredNamespaceUri(namespaceUri)) return true;
+ // Otherwise it was not found in the cache, so check the store ...
+ String prefix = readPrefixFor(namespaceUri, false);
+ if (prefix != null) {
+ cache.register(prefix, namespaceUri);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getDefaultNamespaceUri() {
+ return this.getNamespaceForPrefix("");
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String register( String prefix,
+ String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ namespaceUri = namespaceUri.trim();
+ // Register it in the cache first ...
+ String previousCachedUriForPrefix = this.cache.register(prefix, namespaceUri);
+ // And register it in the source ...
+ String previousPersistentUriForPrefix = doRegister(prefix, namespaceUri);
+ return previousCachedUriForPrefix != null ? previousPersistentUriForPrefix :
previousPersistentUriForPrefix;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.NamespaceRegistry#unregister(java.lang.String)
+ */
+ public boolean unregister( String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ namespaceUri = namespaceUri.trim();
+ // Remove it from the cache ...
+ boolean found = this.cache.unregister(namespaceUri);
+ // Then from the source ...
+ return doUnregister(namespaceUri) || found;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<String> getRegisteredNamespaceUris() {
+ // Just return what's in the cache ...
+ return cache.getRegisteredNamespaceUris();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.NamespaceRegistry#getNamespaces()
+ */
+ public Set<Namespace> getNamespaces() {
+ // Just return what's in the cache ...
+ return cache.getNamespaces();
+ }
+
+ public void refresh() {
+ SimpleNamespaceRegistry newCache = new SimpleNamespaceRegistry();
+ initializeCacheFromStore(newCache);
+ this.cache = newCache;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ List<Namespace> namespaces = new
ArrayList<Namespace>(getNamespaces());
+ Collections.sort(namespaces);
+ return namespaces.toString();
+ }
+
+ protected void initializeCacheFromStore( NamespaceRegistry cache ) {
+ // Read the store ...
+ try {
+ Subgraph nsGraph = store.getSubgraphOfDepth(2).at(parentOfNamespaceNodes);
+ ValueFactory<String> stringFactory =
store.getContext().getValueFactories().getStringFactory();
+ for (Location nsLocation : nsGraph.getRoot().getChildren()) {
+ Node ns = nsGraph.getNode(nsLocation);
+ // This node is a namespace ...
+ String uri =
stringFactory.create(ns.getProperty(uriPropertyName).getFirstValue());
+ if (uri != null) {
+ String prefix = getPrefixFor(nsLocation.getPath());
+ cache.register(prefix, uri);
+ }
+ }
+ } catch (PathNotFoundException e) {
+ // Nothing to read
+ }
+ }
+
+ protected String readUriFor( String prefix ) {
+ // Read the store ...
+ try {
+ PathFactory pathFactory =
store.getContext().getValueFactories().getPathFactory();
+ Path pathToNamespaceNode = pathFactory.create(parentOfNamespaceNodes,
prefix);
+ Property uri = store.getProperty(uriPropertyName).on(pathToNamespaceNode);
+ // Get the URI property value ...
+ ValueFactory<String> stringFactory =
store.getContext().getValueFactories().getStringFactory();
+ return stringFactory.create(uri.getFirstValue());
+ } catch (PathNotFoundException e) {
+ // Nothing to read
+ return null;
+ }
+ }
+
+ protected String getPrefixFor( Path path ) {
+ Path.Segment lastSegment = path.getLastSegment();
+ String localName = lastSegment.getName().getLocalName();
+ int index = lastSegment.getIndex();
+ if (index == 1) {
+ if (GENERATED_PREFIX.equals(localName)) return localName + "00" +
index;
+ return localName;
+ }
+ if (index < 10) {
+ return localName + "00" + index;
+ }
+ if (index < 100) {
+ return localName + "0" + index;
+ }
+ return localName + index;
+ }
+
+ protected String readPrefixFor( String namespaceUri,
+ boolean generateIfMissing ) {
+ // Read the store ...
+ try {
+ Subgraph nsGraph = store.getSubgraphOfDepth(2).at(parentOfNamespaceNodes);
+ ValueFactory<String> stringFactory =
store.getContext().getValueFactories().getStringFactory();
+ for (Location nsLocation : nsGraph.getRoot().getChildren()) {
+ Node ns = nsGraph.getNode(nsLocation);
+ String prefix = getPrefixFor(nsLocation.getPath());
+ String uri =
stringFactory.create(ns.getProperty(uriPropertyName).getFirstValue());
+ if (prefix != null && uri != null) {
+ if (uri.equals(namespaceUri)) return prefix;
+ }
+ }
+ if (generateIfMissing) {
+ // Generated prefixes are simply "ns" followed by the SNS index
...
+ PathFactory pathFactory =
store.getContext().getValueFactories().getPathFactory();
+ Path pathToNamespaceNode = pathFactory.create(parentOfNamespaceNodes,
GENERATED_PREFIX);
+ Location actualLocation = store.createAt(pathToNamespaceNode)
+ .with(namespaceProperties)
+ .and(uriPropertyName, namespaceUri)
+ .getLocation();
+
+ return getPrefixFor(actualLocation.getPath());
+ }
+
+ } catch (PathNotFoundException e) {
+ // Nothing to read
+ }
+ return null;
+ }
+
+ protected String doRegister( String prefix,
+ String uri ) {
+ assert prefix != null;
+ assert uri != null;
+ prefix = prefix.trim();
+ uri = uri.trim();
+
+ // Read the store ...
+ String previousUri = null;
+ ValueFactory<String> stringFactory =
store.getContext().getValueFactories().getStringFactory();
+ PathFactory pathFactory =
store.getContext().getValueFactories().getPathFactory();
+ Path pathToNamespaceNode = pathFactory.create(parentOfNamespaceNodes, prefix);
+ try {
+ Subgraph nsGraph = store.getSubgraphOfDepth(2).at(parentOfNamespaceNodes);
+ // Iterate over the existing mappings, looking for one that uses the URI ...
+ Location nsNodeWithPrefix = null;
+ boolean updateNode = true;
+ Set<Location> locationsToRemove = new HashSet<Location>();
+ for (Location nsLocation : nsGraph.getRoot().getChildren()) {
+ Node ns = nsGraph.getNode(nsLocation);
+ String actualPrefix = getPrefixFor(nsLocation.getPath());
+ String actualUri =
stringFactory.create(ns.getProperty(uriPropertyName).getFirstValue());
+ if (actualPrefix != null && actualUri != null) {
+ if (actualPrefix.equals(prefix)) {
+ nsNodeWithPrefix = nsLocation;
+ if (actualUri.equals(uri)) {
+ updateNode = false;
+ break;
+ }
+ previousUri = actualUri;
+ }
+ if (actualUri.equals(uri)) {
+ locationsToRemove.add(ns.getLocation());
+ }
+ }
+ }
+ Graph.Batch batch = store.batch();
+ // Remove any other nodes that have the same URI ...
+ for (Location namespaceToRemove : locationsToRemove) {
+ batch.delete(namespaceToRemove).and();
+ }
+ // Now update/create the namespace mapping ...
+ if (nsNodeWithPrefix == null) {
+ // We didn't find an existing node, so we have to create it ...
+
batch.create(pathToNamespaceNode).with(namespaceProperties).and(uriPropertyName,
uri).and();
+ } else {
+ if (updateNode) {
+ // There was already an existing node, so update it ...
+ batch.set(uriPropertyName).to(uri).on(pathToNamespaceNode).and();
+ }
+ }
+ // Execute all these changes ...
+ batch.execute();
+ } catch (PathNotFoundException e) {
+ // Nothing stored yet ...
+
store.createAt(pathToNamespaceNode).with(namespaceProperties).and(uriPropertyName,
uri).getLocation();
+ }
+ return previousUri;
+ }
+
+ protected boolean doUnregister( String uri ) {
+ // Read the store ...
+ ValueFactory<String> stringFactory =
store.getContext().getValueFactories().getStringFactory();
+ boolean result = false;
+ try {
+ Subgraph nsGraph = store.getSubgraphOfDepth(2).at(parentOfNamespaceNodes);
+ // Iterate over the existing mappings, looking for one that uses the prefix
and uri ...
+ Set<Location> locationsToRemove = new HashSet<Location>();
+ for (Location nsLocation : nsGraph.getRoot().getChildren()) {
+ Node ns = nsGraph.getNode(nsLocation);
+ String actualUri =
stringFactory.create(ns.getProperty(uriPropertyName).getFirstValue());
+ if (actualUri.equals(uri)) {
+ locationsToRemove.add(ns.getLocation());
+ result = true;
+ }
+ }
+ // Remove any other nodes that have the same URI ...
+ Graph.Batch batch = store.batch();
+ for (Location namespaceToRemove : locationsToRemove) {
+ batch.delete(namespaceToRemove).and();
+ }
+ // Execute all these changes ...
+ batch.execute();
+ } catch (PathNotFoundException e) {
+ // Nothing stored yet, so do nothing ...
+ }
+ return result;
+ }
+
+}
Property changes on:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistry.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistry.java
===================================================================
---
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistry.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistry.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -36,7 +36,7 @@
* @author Randall Hauch
*/
@ThreadSafe
-public class LocalNamespaceRegistry extends BasicNamespaceRegistry {
+public class LocalNamespaceRegistry extends SimpleNamespaceRegistry {
private final NamespaceRegistry delegate;
@@ -65,7 +65,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#getDefaultNamespaceUri()
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#getDefaultNamespaceUri()
*/
@Override
public String getDefaultNamespaceUri() {
@@ -77,7 +77,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#getNamespaceForPrefix(java.lang.String)
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#getNamespaceForPrefix(java.lang.String)
*/
@Override
public String getNamespaceForPrefix( String prefix ) {
@@ -89,7 +89,7 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#getNamespaces()
+ * @see org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#getNamespaces()
*/
@Override
public Set<Namespace> getNamespaces() {
@@ -116,7 +116,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#getPrefixForNamespaceUri(java.lang.String,
boolean)
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#getPrefixForNamespaceUri(java.lang.String,
boolean)
*/
@Override
public String getPrefixForNamespaceUri( String namespaceUri,
@@ -130,7 +130,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#getRegisteredNamespaceUris()
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#getRegisteredNamespaceUris()
*/
@Override
public Set<String> getRegisteredNamespaceUris() {
@@ -142,7 +142,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#isRegisteredNamespaceUri(java.lang.String)
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#isRegisteredNamespaceUri(java.lang.String)
*/
@Override
public boolean isRegisteredNamespaceUri( String namespaceUri ) {
@@ -152,7 +152,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#register(java.lang.String,
java.lang.String)
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#register(java.lang.String,
java.lang.String)
*/
@Override
public String register( String prefix,
@@ -167,7 +167,7 @@
/**
* {@inheritDoc}
*
- * @see
org.jboss.dna.graph.property.basic.BasicNamespaceRegistry#unregister(java.lang.String)
+ * @see
org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry#unregister(java.lang.String)
*/
@Override
public boolean unregister( String namespaceUri ) {
Added:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistry.java
===================================================================
---
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistry.java
(rev 0)
+++
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistry.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,200 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+import java.text.DecimalFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import net.jcip.annotations.NotThreadSafe;
+import org.jboss.dna.common.util.CheckArg;
+import org.jboss.dna.graph.property.NamespaceRegistry;
+
+/**
+ * A simple {@link NamespaceRegistry} implementation that is not thread-safe, but that
provides all the basic functionality.
+ *
+ * @author Randall Hauch
+ */
+@NotThreadSafe
+public class SimpleNamespaceRegistry implements NamespaceRegistry {
+
+ public static final String DEFAULT_NAMESPACE_URI = "";
+ public static final String DEFAULT_PREFIX_TEMPLATE = "ns##000";
+ public static final String DEFAULT_PREFIX_NUMBER_FORMAT = "##000";
+
+ private final Map<String, String> namespacesByPrefix = new HashMap<String,
String>();
+ private final Map<String, String> prefixesByNamespace = new HashMap<String,
String>();
+ private String generatedPrefixTemplate = DEFAULT_PREFIX_TEMPLATE;
+ private int nextGeneratedPrefixNumber = 1;
+
+ /**
+ *
+ */
+ public SimpleNamespaceRegistry() {
+ this(DEFAULT_NAMESPACE_URI);
+ }
+
+ /**
+ * @param defaultNamespaceUri the namespace URI to use for the default prefix
+ */
+ public SimpleNamespaceRegistry( final String defaultNamespaceUri ) {
+ register("", defaultNamespaceUri);
+ }
+
+ /**
+ * @return prefixTemplate
+ */
+ public String getGeneratedPrefixTemplate() {
+ return this.generatedPrefixTemplate;
+ }
+
+ /**
+ * @param prefixTemplate Sets prefixTemplate to the specified value.
+ */
+ public void setGeneratedPrefixTemplate( String prefixTemplate ) {
+ if (prefixTemplate == null) prefixTemplate = DEFAULT_PREFIX_TEMPLATE;
+ this.generatedPrefixTemplate = prefixTemplate;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getNamespaceForPrefix( String prefix ) {
+ CheckArg.isNotNull(prefix, "prefix");
+ return this.namespacesByPrefix.get(prefix);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPrefixForNamespaceUri( String namespaceUri,
+ boolean generateIfMissing ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ String prefix = null;
+ prefix = this.prefixesByNamespace.get(namespaceUri);
+ if (prefix == null && generateIfMissing) {
+ // Now we can genereate a prefix and register it ...
+ prefix = this.generatePrefix();
+ this.register(prefix, namespaceUri);
+ return prefix;
+ }
+ return prefix;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isRegisteredNamespaceUri( String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ return this.prefixesByNamespace.containsKey(namespaceUri);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getDefaultNamespaceUri() {
+ return this.namespacesByPrefix.get("");
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String register( String prefix,
+ String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ String previousNamespaceForPrefix = null;
+ namespaceUri = namespaceUri.trim();
+ if (prefix == null) prefix = generatePrefix();
+ prefix = prefix.trim();
+ prefix = prefix.replaceFirst("^:+", "");
+ prefix = prefix.replaceFirst(":+$", "");
+ previousNamespaceForPrefix = this.namespacesByPrefix.put(prefix, namespaceUri);
+ String previousPrefix = this.prefixesByNamespace.put(namespaceUri, prefix);
+ if (previousPrefix != null && !previousPrefix.equals(prefix)) {
+ this.namespacesByPrefix.remove(previousPrefix);
+ }
+ if (previousNamespaceForPrefix != null &&
!previousNamespaceForPrefix.equals(namespaceUri)) {
+ this.prefixesByNamespace.remove(previousNamespaceForPrefix);
+ }
+ return previousNamespaceForPrefix;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.NamespaceRegistry#unregister(java.lang.String)
+ */
+ public boolean unregister( String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ namespaceUri = namespaceUri.trim();
+ String prefix = this.prefixesByNamespace.remove(namespaceUri);
+ if (prefix == null) return false;
+ this.namespacesByPrefix.remove(prefix);
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<String> getRegisteredNamespaceUris() {
+ Set<String> result = new HashSet<String>();
+ result.addAll(this.prefixesByNamespace.keySet());
+ return Collections.unmodifiableSet(result);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.NamespaceRegistry#getNamespaces()
+ */
+ public Set<Namespace> getNamespaces() {
+ Set<Namespace> result = new HashSet<Namespace>();
+ for (Map.Entry<String, String> entry : this.namespacesByPrefix.entrySet())
{
+ result.add(new BasicNamespace(entry.getKey(), entry.getValue()));
+ }
+ return Collections.unmodifiableSet(result);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ List<Namespace> namespaces = new
ArrayList<Namespace>(getNamespaces());
+ Collections.sort(namespaces);
+ return namespaces.toString();
+ }
+
+ protected String generatePrefix() {
+ DecimalFormat formatter = new DecimalFormat(this.generatedPrefixTemplate);
+ return formatter.format(nextGeneratedPrefixNumber++);
+ }
+
+}
Property changes on:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistry.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistry.java
===================================================================
---
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistry.java
(rev 0)
+++
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistry.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,204 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import net.jcip.annotations.ThreadSafe;
+import org.jboss.dna.common.util.CheckArg;
+import org.jboss.dna.graph.property.NamespaceRegistry;
+
+/**
+ * A thread-safe {@link NamespaceRegistry} that may be used as a thread-safe wrapper
around another non-thread-safe
+ * implementation.
+ *
+ * @author Randall Hauch
+ */
+@ThreadSafe
+public class ThreadSafeNamespaceRegistry implements NamespaceRegistry {
+
+ private final ReadWriteLock registryLock = new ReentrantReadWriteLock();
+ private final NamespaceRegistry delegate;
+
+ /**
+ */
+ public ThreadSafeNamespaceRegistry() {
+ this(new SimpleNamespaceRegistry());
+ }
+
+ /**
+ * @param nonThreadSafeRegistry a {@link NamespaceRegistry} implementation that is
not thread safe and to which this instance
+ * will delegate; may not be null
+ */
+ public ThreadSafeNamespaceRegistry( NamespaceRegistry nonThreadSafeRegistry ) {
+ CheckArg.isNotNull(nonThreadSafeRegistry, "nonThreadSafeRegistry");
+ delegate = nonThreadSafeRegistry;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getNamespaceForPrefix( String prefix ) {
+ CheckArg.isNotNull(prefix, "prefix");
+ Lock lock = this.registryLock.readLock();
+ try {
+ lock.lock();
+ return this.delegate.getNamespaceForPrefix(prefix);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getPrefixForNamespaceUri( String namespaceUri,
+ boolean generateIfMissing ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ String prefix = null;
+ Lock lock = this.registryLock.readLock();
+ try {
+ lock.lock();
+ prefix = delegate.getPrefixForNamespaceUri(namespaceUri, false);
+ } finally {
+ lock.unlock();
+ }
+ if (prefix == null && generateIfMissing) {
+ // Get a write lock ...
+ lock = this.registryLock.writeLock();
+ try {
+ lock.lock();
+ prefix = delegate.getPrefixForNamespaceUri(namespaceUri, true);
+ return prefix;
+ } finally {
+ lock.unlock();
+ }
+ }
+ return prefix;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isRegisteredNamespaceUri( String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ Lock lock = this.registryLock.readLock();
+ try {
+ lock.lock();
+ return delegate.isRegisteredNamespaceUri(namespaceUri);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String getDefaultNamespaceUri() {
+ Lock lock = this.registryLock.readLock();
+ try {
+ lock.lock();
+ return delegate.getDefaultNamespaceUri();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public String register( String prefix,
+ String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ Lock lock = this.registryLock.writeLock();
+ try {
+ lock.lock();
+ return delegate.register(prefix, namespaceUri);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.NamespaceRegistry#unregister(java.lang.String)
+ */
+ public boolean unregister( String namespaceUri ) {
+ CheckArg.isNotNull(namespaceUri, "namespaceUri");
+ Lock lock = this.registryLock.writeLock();
+ try {
+ lock.lock();
+ return delegate.unregister(namespaceUri);
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public Set<String> getRegisteredNamespaceUris() {
+ Lock lock = this.registryLock.readLock();
+ try {
+ lock.lock();
+ return delegate.getRegisteredNamespaceUris();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.NamespaceRegistry#getNamespaces()
+ */
+ public Set<Namespace> getNamespaces() {
+ Lock lock = this.registryLock.readLock();
+ try {
+ lock.lock();
+ return delegate.getNamespaces();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ List<Namespace> namespaces = new
ArrayList<Namespace>(getNamespaces());
+ Collections.sort(namespaces);
+ return namespaces.toString();
+ }
+
+}
Property changes on:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistry.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphTest.java 2009-02-24 14:40:05
UTC (rev 737)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphTest.java 2009-02-27 22:21:50
UTC (rev 738)
@@ -424,6 +424,62 @@
}
@Test
+ public void shouldCreateNodeAndReturnGraph() {
+ graph.create(validPath).and().getNodeAt(validPath);
+ assertThat(numberOfExecutions, is(2));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()),
"c");
+ assertNextRequestReadNode(Location.create(validPath));
+ assertNoMoreRequests();
+ }
+
+ @Test
+ public void shouldCreateNodeAtPathWithPropertiesAndReturnLocation() {
+ Location actual =
graph.createAt(validPath).with(validIdProperty1).getLocation();
+ assertThat(actual, is(notNullValue()));
+ assertThat(numberOfExecutions, is(1));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()), "c",
validIdProperty1);
+ assertNoMoreRequests();
+
+ actual =
graph.createAt(validPath).with(validIdProperty1).and(validIdProperty2).getLocation();
+ assertThat(actual, is(notNullValue()));
+ assertThat(numberOfExecutions, is(1));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()), "c",
validIdProperty1, validIdProperty2);
+ assertNoMoreRequests();
+ }
+
+ @Test
+ public void shouldCreateNodeAtPathWithPropertiesAndReturnNode() {
+ Node node = graph.createAt(validPath).with(validIdProperty1).getNode();
+ assertThat(node, is(notNullValue()));
+ assertThat(numberOfExecutions, is(2));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()), "c",
validIdProperty1);
+ assertNextRequestReadNode(Location.create(validPath));
+ assertNoMoreRequests();
+
+ node =
graph.createAt(validPath).with(validIdProperty1).and(validIdProperty2).getNode();
+ assertThat(node, is(notNullValue()));
+ assertThat(numberOfExecutions, is(2));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()), "c",
validIdProperty1, validIdProperty2);
+ assertNextRequestReadNode(Location.create(validPath));
+ assertNoMoreRequests();
+ }
+
+ @Test
+ public void shouldCreateNodeAtPathWithPropertiesAndReturnGraph() {
+ graph.createAt(validPath).with(validIdProperty1).and().getNodeAt(validPath);
+ assertThat(numberOfExecutions, is(2));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()), "c",
validIdProperty1);
+ assertNextRequestReadNode(Location.create(validPath));
+ assertNoMoreRequests();
+
+
graph.createAt(validPath).with(validIdProperty1).and(validIdProperty2).and().getNodeAt(validPath);
+ assertThat(numberOfExecutions, is(2));
+ assertNextRequestIsCreate(Location.create(validPath.getParent()), "c",
validIdProperty1, validIdProperty2);
+ assertNextRequestReadNode(Location.create(validPath));
+ assertNoMoreRequests();
+ }
+
+ @Test
public void shouldCreateNodesWithBatch() {
graph.batch().create(validPath,
validIdProperty1).and().remove("prop").on(validPathString).execute();
graph.batch().move(validPath).and(validPath).into(validPathString).and().create(validPath).execute();
@@ -596,8 +652,8 @@
assertNextRequestUpdateProperties(Location.create(validPath),
createProperty("propName", validPath));
graph.set("propName").on(validPath).to(validPath.getLastSegment().getName());
- assertNextRequestUpdateProperties(Location.create(validPath),
createProperty("propName",
-
validPath.getLastSegment().getName()));
+ assertNextRequestUpdateProperties(Location.create(validPath),
createProperty("propName", validPath.getLastSegment()
+
.getName()));
Date now = new Date();
graph.set("propName").on(validPath).to(now);
assertNextRequestUpdateProperties(Location.create(validPath),
createProperty("propName", now));
@@ -720,8 +776,16 @@
assertNextRequestIsMove(Location.create(validUuid), Location.create(validPath));
assertNoMoreRequests();
- graph.batch().move(validPath).into(validIdProperty1,
validIdProperty2).and().move(validPathString).into(validIdProperty1,
-
validIdProperty2).and().move(validUuid).into(validPath).execute();
+ graph.batch()
+ .move(validPath)
+ .into(validIdProperty1, validIdProperty2)
+ .and()
+ .move(validPathString)
+ .into(validIdProperty1, validIdProperty2)
+ .and()
+ .move(validUuid)
+ .into(validPath)
+ .execute();
assertThat(numberOfExecutions, is(1));
extractRequestsFromComposite();
assertNextRequestIsMove(Location.create(validPath),
Location.create(validIdProperty1, validIdProperty2));
@@ -747,8 +811,16 @@
assertNextRequestIsCopy(Location.create(validUuid), Location.create(validPath));
assertNoMoreRequests();
- graph.batch().copy(validPath).into(validIdProperty1,
validIdProperty2).and().copy(validPathString).into(validIdProperty1,
-
validIdProperty2).and().copy(validUuid).into(validPath).execute();
+ graph.batch()
+ .copy(validPath)
+ .into(validIdProperty1, validIdProperty2)
+ .and()
+ .copy(validPathString)
+ .into(validIdProperty1, validIdProperty2)
+ .and()
+ .copy(validUuid)
+ .into(validPath)
+ .execute();
assertThat(numberOfExecutions, is(1));
extractRequestsFromComposite();
assertNextRequestIsCopy(Location.create(validPath),
Location.create(validIdProperty1, validIdProperty2));
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/LocationTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/LocationTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/LocationTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -26,210 +26,230 @@
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
-
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-
import org.jboss.dna.common.text.NoOpEncoder;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.PathFactory;
import org.jboss.dna.graph.property.Property;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
import org.jboss.dna.graph.property.basic.BasicSingleValueProperty;
import org.jboss.dna.graph.property.basic.NameValueFactory;
import org.jboss.dna.graph.property.basic.PathValueFactory;
+import org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry;
import org.jboss.dna.graph.property.basic.StringValueFactory;
import org.junit.BeforeClass;
import org.junit.Test;
-
/**
* Tests <code>Location</code> class and factory constructors.
*/
public class LocationTest {
- private static final NoOpEncoder NO_OP_ENCODER = new NoOpEncoder();
- private static final StringValueFactory STRING_VALUE_FACTORY = new
StringValueFactory(NO_OP_ENCODER, NO_OP_ENCODER);
- private static final NameValueFactory NAME_VALUE_FACTORY = new NameValueFactory(new
BasicNamespaceRegistry("http://www.jboss.org/dna/1.0"), NO_OP_ENCODER,
STRING_VALUE_FACTORY);
-
- private PathFactory pathFactory = new PathValueFactory(NO_OP_ENCODER,
- STRING_VALUE_FACTORY, NAME_VALUE_FACTORY);
-
- private static UUID uuid = UUID.randomUUID();
-
- private Path pathA = pathFactory.create("/A");
- private Path pathABC = pathFactory.create("/A/B/C");
+ private static final NoOpEncoder NO_OP_ENCODER = new NoOpEncoder();
+ private static final StringValueFactory STRING_VALUE_FACTORY = new
StringValueFactory(NO_OP_ENCODER, NO_OP_ENCODER);
+ private static final NameValueFactory NAME_VALUE_FACTORY = new NameValueFactory(
+ new
SimpleNamespaceRegistry(
+
"http://www.jboss.org/dna/1.0"),
+
NO_OP_ENCODER, STRING_VALUE_FACTORY);
- private static Property propA = new
BasicSingleValueProperty(NAME_VALUE_FACTORY.create("A"), "Value A");
- private static Property propB = new
BasicSingleValueProperty(NAME_VALUE_FACTORY.create("B"), "Value B");
- private static Property propU = new BasicSingleValueProperty(DnaLexicon.UUID, uuid);
-
- private static List<Property> propListAB;
- private static List<Property> propListABU;
-
-
+ private PathFactory pathFactory = new PathValueFactory(NO_OP_ENCODER,
STRING_VALUE_FACTORY, NAME_VALUE_FACTORY);
+
+ private static UUID uuid = UUID.randomUUID();
+
+ private Path pathA = pathFactory.create("/A");
+ private Path pathABC = pathFactory.create("/A/B/C");
+
+ private static Property propA = new
BasicSingleValueProperty(NAME_VALUE_FACTORY.create("A"), "Value A");
+ private static Property propB = new
BasicSingleValueProperty(NAME_VALUE_FACTORY.create("B"), "Value B");
+ private static Property propU = new BasicSingleValueProperty(DnaLexicon.UUID, uuid);
+
+ private static List<Property> propListAB;
+ private static List<Property> propListABU;
+
@BeforeClass
- public static void beforeAny() {
- propListAB = new ArrayList<Property>();
- propListAB.add(propA);
- propListAB.add(propB);
+ public static void beforeAny() {
+ propListAB = new ArrayList<Property>();
+ propListAB.add(propA);
+ propListAB.add(propB);
- propListABU = new ArrayList<Property>();
- propListABU.add(propA);
- propListABU.add(propB);
- propListABU.add(propU);
+ propListABU = new ArrayList<Property>();
+ propListABU.add(propA);
+ propListABU.add(propB);
+ propListABU.add(propU);
}
-
+
@Test
public void locationsWithSamePathsAreEqual() {
- Location locationA1 = Location.create(pathA);
- Location locationA2 = Location.create(pathA);
-
- assertThat("Locations created with identical paths must be equal",
locationA1, is(locationA2));
-
- Location locationABC1 = Location.create(pathABC);
- Location locationABC2 = Location.create(pathABC);
-
- assertThat("Locations created with identical non-trivial paths must be
equal", locationABC1, is(locationABC2));
+ Location locationA1 = Location.create(pathA);
+ Location locationA2 = Location.create(pathA);
+
+ assertThat("Locations created with identical paths must be equal",
locationA1, is(locationA2));
+
+ Location locationABC1 = Location.create(pathABC);
+ Location locationABC2 = Location.create(pathABC);
+
+ assertThat("Locations created with identical non-trivial paths must be
equal", locationABC1, is(locationABC2));
}
@Test
public void locationsWithSamePathsAreSame() {
- Location locationA1 = Location.create(pathA);
- Location locationA2 = Location.create(pathA);
-
- assertThat("isSame must return true for locations created with identical
paths", locationA1.isSame(locationA2), is(true));
-
- Location locationABC1 = Location.create(pathABC);
- Location locationABC2 = Location.create(pathABC);
-
- assertThat("isSame must return true for locations created with identical,
non-trivial paths", locationABC1.isSame(locationABC2), is(true));
+ Location locationA1 = Location.create(pathA);
+ Location locationA2 = Location.create(pathA);
+
+ assertThat("isSame must return true for locations created with identical
paths", locationA1.isSame(locationA2), is(true));
+
+ Location locationABC1 = Location.create(pathABC);
+ Location locationABC2 = Location.create(pathABC);
+
+ assertThat("isSame must return true for locations created with identical,
non-trivial paths",
+ locationABC1.isSame(locationABC2),
+ is(true));
}
@Test
public void locationsWithSamePathsAndSamePropertyAreNotEqual() {
- Location locationA1 = Location.create(pathA, propA);
- Location locationA2 = Location.create(pathA, propA);
-
- assertThat("Locations created with identical paths and different property must
be equal", locationA1, is(locationA2));
- }
+ Location locationA1 = Location.create(pathA, propA);
+ Location locationA2 = Location.create(pathA, propA);
+ assertThat("Locations created with identical paths and different property
must be equal", locationA1, is(locationA2));
+ }
+
@Test
public void locationsWithSamePathsAndSamePropertyAreNotSame() {
- Location locationA1 = Location.create(pathA, propA);
- Location locationA2 = Location.create(pathA, propA);
-
- assertThat("isSame must return true for locations created with identical paths
and property", locationA1.isSame(locationA2), is(true));
- }
-
+ Location locationA1 = Location.create(pathA, propA);
+ Location locationA2 = Location.create(pathA, propA);
+
+ assertThat("isSame must return true for locations created with identical
paths and property",
+ locationA1.isSame(locationA2),
+ is(true));
+ }
+
@Test
public void locationsWithSamePathsAndDifferentPropertyAreNotEqual() {
- Location locationA1 = Location.create(pathA, propA);
- Location locationA2 = Location.create(pathA, propB);
-
- assertThat("Locations created with identical paths and different property must
not be equal", locationA1, not(locationA2));
- }
+ Location locationA1 = Location.create(pathA, propA);
+ Location locationA2 = Location.create(pathA, propB);
+ assertThat("Locations created with identical paths and different property
must not be equal", locationA1, not(locationA2));
+ }
+
@Test
public void locationsWithSamePathsAndDifferentPropertyAreNotSame() {
- Location locationA1 = Location.create(pathA, propA);
- Location locationA2 = Location.create(pathA, propB);
-
- assertThat("isSame must not return true for locations created with identical
paths and property", locationA1.isSame(locationA2), is(false));
- }
-
+ Location locationA1 = Location.create(pathA, propA);
+ Location locationA2 = Location.create(pathA, propB);
+
+ assertThat("isSame must not return true for locations created with identical
paths and property",
+ locationA1.isSame(locationA2),
+ is(false));
+ }
+
@Test
public void locationsWithDifferentPathsAndSamePropertyAreNotEqual() {
- Location locationA1 = Location.create(pathA, propA);
- Location locationA2 = Location.create(pathABC, propA);
-
- assertThat("Locations created with different paths and the same property must
not be equal", locationA1, not(locationA2));
- }
+ Location locationA1 = Location.create(pathA, propA);
+ Location locationA2 = Location.create(pathABC, propA);
+ assertThat("Locations created with different paths and the same property
must not be equal", locationA1, not(locationA2));
+ }
+
@Test
public void locationsWithDifferentPathsAndSamePropertyAreNotSame() {
- Location locationA1 = Location.create(pathA, propA);
- Location locationA2 = Location.create(pathABC, propA);
-
- assertThat("isSame must not return true for locations created with different
paths and the same property", locationA1.isSame(locationA2), is(false));
- }
+ Location locationA1 = Location.create(pathA, propA);
+ Location locationA2 = Location.create(pathABC, propA);
+ assertThat("isSame must not return true for locations created with different
paths and the same property",
+ locationA1.isSame(locationA2),
+ is(false));
+ }
+
@Test
public void locationsWithSamePathsAndSamePropertiesAreNotEqual() {
- Location locationA1 = Location.create(pathA, propListAB);
- Location locationA2 = Location.create(pathA, propListAB);
-
- assertThat("Locations created with identical paths and different properties
must be equal", locationA1, is(locationA2));
- }
+ Location locationA1 = Location.create(pathA, propListAB);
+ Location locationA2 = Location.create(pathA, propListAB);
+ assertThat("Locations created with identical paths and different properties
must be equal", locationA1, is(locationA2));
+ }
+
@Test
public void locationsWithSamePathsAndSamePropertiesAreNotSame() {
- Location locationA1 = Location.create(pathA, propListAB);
- Location locationA2 = Location.create(pathA, propListAB);
-
- assertThat("isSame must return true for locations created with identical paths
and properties", locationA1.isSame(locationA2), is(true));
- }
-
+ Location locationA1 = Location.create(pathA, propListAB);
+ Location locationA2 = Location.create(pathA, propListAB);
+
+ assertThat("isSame must return true for locations created with identical
paths and properties",
+ locationA1.isSame(locationA2),
+ is(true));
+ }
+
@Test
public void locationsWithSamePathsAndDifferentPropertiesAreNotEqual() {
- Location locationA1 = Location.create(pathA, propListAB);
- Location locationA2 = Location.create(pathA, propListABU);
-
- assertThat("Locations created with identical paths and different properties
must not be equal", locationA1, not(locationA2));
- }
+ Location locationA1 = Location.create(pathA, propListAB);
+ Location locationA2 = Location.create(pathA, propListABU);
+ assertThat("Locations created with identical paths and different properties
must not be equal",
+ locationA1,
+ not(locationA2));
+ }
+
@Test
public void locationsWithSamePathsAndDifferentPropertiesAreNotSame() {
- Location locationA1 = Location.create(pathA, propListAB);
- Location locationA2 = Location.create(pathA, propListABU);
-
- assertThat("isSame must not return true for locations created with identical
paths and different properties", locationA1.isSame(locationA2), is(false));
- }
-
+ Location locationA1 = Location.create(pathA, propListAB);
+ Location locationA2 = Location.create(pathA, propListABU);
+
+ assertThat("isSame must not return true for locations created with identical
paths and different properties",
+ locationA1.isSame(locationA2),
+ is(false));
+ }
+
@Test
public void locationsWithDifferentPathsAndSamePropertiesAreNotEqual() {
- Location locationA1 = Location.create(pathA, propListAB);
- Location locationA2 = Location.create(pathABC, propListAB);
-
- assertThat("Locations created with identical paths and different properties
must not be equal", locationA1, not(locationA2));
- }
+ Location locationA1 = Location.create(pathA, propListAB);
+ Location locationA2 = Location.create(pathABC, propListAB);
+ assertThat("Locations created with identical paths and different properties
must not be equal",
+ locationA1,
+ not(locationA2));
+ }
+
@Test
public void locationsWithDifferentPathsAndSamePropertiesAreNotSame() {
- Location locationA1 = Location.create(pathA, propListAB);
- Location locationA2 = Location.create(pathABC, propListAB);
-
- assertThat("isSame must not return true for locations created with different
paths and the same properties", locationA1.isSame(locationA2), is(false));
- }
-
+ Location locationA1 = Location.create(pathA, propListAB);
+ Location locationA2 = Location.create(pathABC, propListAB);
+
+ assertThat("isSame must not return true for locations created with different
paths and the same properties",
+ locationA1.isSame(locationA2),
+ is(false));
+ }
+
@Test
public void testTransitivityOfWithOperationForPathAndUUID() {
- Location locationA1 = Location.create(pathA);
- locationA1 = locationA1.with(uuid);
-
- Location locationU1 = Location.create(uuid);
- locationU1 = locationU1.with(pathA);
-
- assertThat("With() operation must be transitive for equals",
locationA1.equals(locationU1), is(true));
- assertThat("With() operation must be transitive for isSame",
locationA1.isSame(locationU1), is(true));
- assertThat("With() operation must be transitive for getString",
locationA1.getString().equals(locationU1.getString()), is(true));
- assertThat("With() operation must be transitive for hashCode",
locationA1.hashCode() == locationU1.hashCode(), is(true));
+ Location locationA1 = Location.create(pathA);
+ locationA1 = locationA1.with(uuid);
+
+ Location locationU1 = Location.create(uuid);
+ locationU1 = locationU1.with(pathA);
+
+ assertThat("With() operation must be transitive for equals",
locationA1.equals(locationU1), is(true));
+ assertThat("With() operation must be transitive for isSame",
locationA1.isSame(locationU1), is(true));
+ assertThat("With() operation must be transitive for getString",
+ locationA1.getString().equals(locationU1.getString()),
+ is(true));
+ assertThat("With() operation must be transitive for hashCode",
locationA1.hashCode() == locationU1.hashCode(), is(true));
}
-
+
@Test
public void testTransitivityOfWithOperationForPathAndProperty() {
- Location locationA1 = Location.create(pathA);
- locationA1 = locationA1.with(propB);
-
- Location locationU1 = Location.create(propB);
- locationU1 = locationU1.with(pathA);
-
- assertThat("With() operation must be transitive for equals",
locationA1.equals(locationU1), is(true));
- assertThat("With() operation must be transitive for isSame",
locationA1.isSame(locationU1), is(true));
- assertThat("With() operation must be transitive for getString",
locationA1.getString().equals(locationU1.getString()), is(true));
- assertThat("With() operation must be transitive for hashCode",
locationA1.hashCode() == locationU1.hashCode(), is(true));
- }
+ Location locationA1 = Location.create(pathA);
+ locationA1 = locationA1.with(propB);
+ Location locationU1 = Location.create(propB);
+ locationU1 = locationU1.with(pathA);
+
+ assertThat("With() operation must be transitive for equals",
locationA1.equals(locationU1), is(true));
+ assertThat("With() operation must be transitive for isSame",
locationA1.isSame(locationU1), is(true));
+ assertThat("With() operation must be transitive for getString",
+ locationA1.getString().equals(locationU1.getString()),
+ is(true));
+ assertThat("With() operation must be transitive for hashCode",
locationA1.hashCode() == locationU1.hashCode(), is(true));
+ }
+
}
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/AbstractValueComparatorsTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/AbstractValueComparatorsTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/AbstractValueComparatorsTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -32,8 +32,7 @@
import java.util.Comparator;
import java.util.List;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.graph.property.ValueFactories;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
+import org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry;
import org.jboss.dna.graph.property.basic.StandardValueFactories;
import org.junit.Test;
@@ -43,13 +42,14 @@
*/
public abstract class AbstractValueComparatorsTest<T> {
- public static final BasicNamespaceRegistry NAMESPACE_REGISTRY = new
BasicNamespaceRegistry();
+ public static final NamespaceRegistry NAMESPACE_REGISTRY = new
SimpleNamespaceRegistry();
public static final ValueFactories VALUE_FACTORIES = new
StandardValueFactories(NAMESPACE_REGISTRY);
protected final Comparator<T> comparator;
protected final T[] validNonNullValues;
- protected AbstractValueComparatorsTest( Comparator<T> comparator, T...
validNonNullValues ) {
+ protected AbstractValueComparatorsTest( Comparator<T> comparator,
+ T... validNonNullValues ) {
CheckArg.isNotNull(comparator, "comparator");
CheckArg.isNotEmpty(validNonNullValues, "validNonNullValues");
this.comparator = comparator;
@@ -125,7 +125,8 @@
}
}
- protected void assertValuesCompareUsing( T value1, T value2 ) {
+ protected void assertValuesCompareUsing( T value1,
+ T value2 ) {
int value1ToValue2 = comparator.compare(value1, value2);
int value2ToValue1 = comparator.compare(value2, value1);
if (value1ToValue2 == 0) {
Added:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/AbstractNamespaceRegistryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/AbstractNamespaceRegistryTest.java
(rev 0)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/AbstractNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,170 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+import static org.hamcrest.core.Is.is;
+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.jboss.dna.graph.property.NamespaceRegistry;
+import org.junit.Before;
+import org.junit.Test;
+
+public abstract class AbstractNamespaceRegistryTest<NamespaceRegistryType extends
NamespaceRegistry> {
+
+ protected String validNamespaceUri1;
+ protected String validNamespaceUri2;
+ protected String validNamespaceUri3;
+ protected String validPrefix1;
+ protected String validPrefix2;
+ protected NamespaceRegistryType namespaceRegistry;
+
+ @Before
+ public void setUp() {
+ validNamespaceUri1 = "http://example.com/foo";
+ validNamespaceUri2 = "http://acme.com/something";
+ validNamespaceUri3 = "http://www.redhat.com";
+ validPrefix1 = "foo";
+ validPrefix2 = "acme";
+ namespaceRegistry = createNamespaceRegistry();
+ }
+
+ protected abstract NamespaceRegistryType createNamespaceRegistry();
+
+ @Test
+ public void shouldReturnNullForNamespaceUriIfPrefixIsNotRegistered() {
+ assertThat(namespaceRegistry.getNamespaceForPrefix("notfound"),
is(nullValue()));
+ // now register some namespaces ...
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getNamespaceForPrefix("notfound"),
is(nullValue()));
+ }
+
+ @Test
+ public void shouldReturnNamespaceUriForPrefixThatIsRegistered() {
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix1),
is(validNamespaceUri1));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix2),
is(validNamespaceUri2));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNullPrefixParameterWhenGettingNamespaceUri() {
+ namespaceRegistry.getNamespaceForPrefix(null);
+ }
+
+ @Test
+ public void shouldReturnNullForPrefixIfNamespaceUriIsNotRegistered() {
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false),
is(nullValue()));
+ // now register some namespaces ...
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false),
is(nullValue()));
+ }
+
+ @Test
+ public void shouldReturnPrefixForNamespaceUriThatIsRegistered() {
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, false),
is(validPrefix1));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, false),
is(validPrefix2));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNullNamespaceUriParameterWhenGettingPrefix() {
+ namespaceRegistry.getPrefixForNamespaceUri(null, false);
+ }
+
+ @Test
+ public void shouldAlwaysHaveDefaultNamespaceRegistered() {
+ assertThat(namespaceRegistry.getDefaultNamespaceUri(), is(notNullValue()));
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getDefaultNamespaceUri(), is(notNullValue()));
+ }
+
+ @Test
+ public void
shouldReturnNonNullDefaultNamespaceUriWhenThereAreNamespacesRegisteredIncludineOneWithZeroLengthPrefix()
{
+ 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
+ public void shouldNotFindRegisteredNamespaceIfNamespaceNotRegistered() {
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1),
is(false));
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri2),
is(false));
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri3),
is(false));
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1),
is(true));
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri2),
is(true));
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri3),
is(false));
+ }
+
+ @Test
+ public void shouldFindRegisteredNamespace() {
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1),
is(true));
+ 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));
+
+ NamespaceRegistry newRegistry = new SimpleNamespaceRegistry();
+ 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));
+
+ }
+
+}
Property changes on:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/AbstractNamespaceRegistryTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNameTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNameTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNameTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -30,6 +30,7 @@
import org.jboss.dna.common.text.TextEncoder;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.junit.Before;
import org.junit.Test;
@@ -40,7 +41,7 @@
*/
public class BasicNameTest {
- private BasicNamespaceRegistry namespaceRegistry;
+ private NamespaceRegistry namespaceRegistry;
private Name name;
private String validNamespaceUri;
private String validLocalName;
@@ -55,7 +56,7 @@
this.validLocalName = "localPart";
this.name = new BasicName(validNamespaceUri, validLocalName);
this.encoder = Path.URL_ENCODER;
- this.namespaceRegistry = new BasicNamespaceRegistry();
+ this.namespaceRegistry = new SimpleNamespaceRegistry();
this.namespaceRegistry.register(validNamespacePrefix, validNamespaceUri);
this.delimiterEncoder = new TextEncoder() {
public String encode( String text ) {
Deleted:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistryTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -1,186 +0,0 @@
-/*
- * JBoss DNA (
http://www.jboss.org/dna)
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
- * See the AUTHORS.txt file in the distribution for a full listing of
- * individual contributors.
- *
- * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
- * is licensed to you 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.
- *
- * JBoss DNA 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.graph.property.basic;
-
-import static org.hamcrest.core.Is.is;
-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.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author Randall Hauch
- */
-public class BasicNamespaceRegistryTest {
-
- private String validNamespaceUri1;
- private String validNamespaceUri2;
- private String validNamespaceUri3;
- private String validPrefix1;
- private String validPrefix2;
- private BasicNamespaceRegistry namespaceRegistry;
-
- @Before
- public void setUp() {
- namespaceRegistry = new BasicNamespaceRegistry();
- validNamespaceUri1 = "http://www.jboss.org/dna/2";
- validNamespaceUri2 = "http://acme.com/something";
- validNamespaceUri3 = "http://www.redhat.com";
- validPrefix1 = "dna";
- validPrefix2 = "acme";
- }
-
- @Test
- public void shouldReturnNullForNamespaceUriIfPrefixIsNotRegistered() {
- assertThat(namespaceRegistry.getNamespaceForPrefix("notfound"),
is(nullValue()));
- // now register some namespaces ...
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.getNamespaceForPrefix("notfound"),
is(nullValue()));
- }
-
- @Test
- public void shouldReturnNamespaceUriForPrefixThatIsRegistered() {
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix1),
is(validNamespaceUri1));
- assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix2),
is(validNamespaceUri2));
- }
-
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNullPrefixParameterWhenGettingNamespaceUri() {
- namespaceRegistry.getNamespaceForPrefix(null);
- }
-
- @Test
- public void shouldReturnNullForPrefixIfNamespaceUriIsNotRegistered() {
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false),
is(nullValue()));
- // now register some namespaces ...
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false),
is(nullValue()));
- }
-
- @Test
- public void shouldGeneratePrefixIfNamespaceUriIsNotRegistered() {
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false),
is(nullValue()));
- // Now get the generated prefix ...
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, true),
is("ns001"));
- // Change the template ...
- namespaceRegistry.setGeneratedPrefixTemplate("xyz0000abc");
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, true),
is("xyz0002abc"));
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, true),
is("xyz0002abc"));
- // Change the template again ...
- namespaceRegistry.setGeneratedPrefixTemplate("xyz####abc");
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, true),
is("xyz3abc"));
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, true),
is("xyz3abc"));
- }
-
- @Test
- public void shouldReturnPrefixForNamespaceUriThatIsRegistered() {
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, false),
is(validPrefix1));
- assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, false),
is(validPrefix2));
- }
-
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNullNamespaceUriParameterWhenGettingPrefix() {
- namespaceRegistry.getPrefixForNamespaceUri(null, false);
- }
-
- @Test
- public void shouldAlwaysHaveDefaultNamespaceRegistered() {
- assertThat(namespaceRegistry.getDefaultNamespaceUri(), is(notNullValue()));
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.getDefaultNamespaceUri(), is(notNullValue()));
- }
-
- @Test
- public void
shouldReturnNonNullDefaultNamespaceUriWhenThereAreNamespacesRegisteredIncludineOneWithZeroLengthPrefix()
{
- 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
- public void shouldNotFindRegisteredNamespaceIfNamespaceNotRegistered() {
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1),
is(false));
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri2),
is(false));
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri3),
is(false));
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1),
is(true));
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri2),
is(true));
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri3),
is(false));
- }
-
- @Test
- public void shouldFindRegisteredNamespace() {
- namespaceRegistry.register(validPrefix1, validNamespaceUri1);
- namespaceRegistry.register(validPrefix2, validNamespaceUri2);
- assertThat(namespaceRegistry.isRegisteredNamespaceUri(validNamespaceUri1),
is(true));
- 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/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathOldTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathOldTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathOldTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -38,6 +38,7 @@
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.property.InvalidPathException;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.ValueFormatException;
import org.junit.Before;
@@ -52,7 +53,7 @@
public static final TextEncoder NO_OP_ENCODER = Path.NO_OP_ENCODER;
public static final Path ROOT = RootPath.INSTANCE;
- private BasicNamespaceRegistry namespaceRegistry;
+ private NamespaceRegistry namespaceRegistry;
private String validNamespaceUri;
private Path path;
private Path path2;
@@ -75,7 +76,7 @@
validSegmentsList.add(segment);
}
path = new BasicPath(validSegmentsList, true);
- namespaceRegistry = new BasicNamespaceRegistry();
+ namespaceRegistry = new SimpleNamespaceRegistry();
namespaceRegistry.register(validNamespacePrefix, validNamespaceUri);
StringValueFactory stringValueFactory = new
StringValueFactory(Path.DEFAULT_DECODER, Path.DEFAULT_ENCODER);
NameValueFactory nameValueFactory = new NameValueFactory(namespaceRegistry,
Path.DEFAULT_DECODER, stringValueFactory);
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathSegmentTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathSegmentTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathSegmentTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -30,14 +30,9 @@
import org.jboss.dna.common.text.TextEncoder;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.ValueFactory;
-import org.jboss.dna.graph.property.basic.BasicName;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
-import org.jboss.dna.graph.property.basic.BasicPathSegment;
-import org.jboss.dna.graph.property.basic.NameValueFactory;
-import org.jboss.dna.graph.property.basic.PathValueFactory;
-import org.jboss.dna.graph.property.basic.StringValueFactory;
import org.junit.Before;
import org.junit.Test;
@@ -48,7 +43,7 @@
public static final TextEncoder NO_OP_ENCODER = Path.NO_OP_ENCODER;
- private BasicNamespaceRegistry registry;
+ private NamespaceRegistry registry;
private ValueFactory<String> stringValueFactory;
private NameValueFactory nameFactory;
private PathValueFactory factory;
@@ -58,7 +53,7 @@
@Before
public void beforeEach() {
- this.registry = new BasicNamespaceRegistry();
+ this.registry = new SimpleNamespaceRegistry();
this.registry.register(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
this.stringValueFactory = new StringValueFactory(Path.DEFAULT_DECODER,
Path.DEFAULT_ENCODER);
this.nameFactory = new NameValueFactory(registry, Path.DEFAULT_DECODER,
stringValueFactory);
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicPathTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -37,6 +37,7 @@
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.property.InvalidPathException;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.ValueFormatException;
import org.junit.Before;
@@ -51,7 +52,7 @@
public static final TextEncoder NO_OP_ENCODER = Path.NO_OP_ENCODER;
public static final Path ROOT = RootPath.INSTANCE;
- private BasicNamespaceRegistry namespaceRegistry;
+ private NamespaceRegistry namespaceRegistry;
private String validNamespaceUri;
private Path path2;
private Path.Segment[] validSegments;
@@ -74,7 +75,7 @@
validSegmentsList.add(segment);
}
super.path = new BasicPath(validSegmentsList, true);
- namespaceRegistry = new BasicNamespaceRegistry();
+ namespaceRegistry = new SimpleNamespaceRegistry();
namespaceRegistry.register(validNamespacePrefix, validNamespaceUri);
StringValueFactory stringValueFactory = new
StringValueFactory(Path.DEFAULT_DECODER, Path.DEFAULT_ENCODER);
NameValueFactory nameValueFactory = new NameValueFactory(namespaceRegistry,
Path.DEFAULT_DECODER, stringValueFactory);
Added:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistryTest.java
(rev 0)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,141 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+import java.util.Set;
+import org.jboss.dna.graph.ExecutionContext;
+import org.jboss.dna.graph.Graph;
+import org.jboss.dna.graph.connector.inmemory.InMemoryRepositorySource;
+import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NameFactory;
+import org.jboss.dna.graph.property.NamespaceRegistry;
+import org.jboss.dna.graph.property.Path;
+import org.jboss.dna.graph.property.Property;
+import org.jboss.dna.graph.property.PropertyFactory;
+import org.junit.Test;
+
+/**
+ * @author Randall Hauch
+ */
+public class GraphNamespaceRegistryTest extends
AbstractNamespaceRegistryTest<GraphNamespaceRegistry> {
+
+ protected ExecutionContext context;
+ protected InMemoryRepositorySource source;
+ protected Graph graph;
+ private Path pathToParentOfNamespaceNodes;
+ private Name uriPropertyName;
+ private Property[] additionalNamespaceProperties;
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.property.basic.AbstractNamespaceRegistryTest#setUp()
+ */
+ @Override
+ public void setUp() {
+ super.setUp();
+
+ // Set up the context and register any namespaces that we'll be using to
manage the namespaces ...
+ context = new ExecutionContext();
+ NameFactory nameFactory = context.getValueFactories().getNameFactory();
+ PropertyFactory propertyFactory = context.getPropertyFactory();
+ context.getNamespaceRegistry().register("nsx",
"http://www.example.com/namespaces");
+ context.getNamespaceRegistry().register("other",
"http://www.example.com/other");
+ uriPropertyName =
context.getValueFactories().getNameFactory().create("nsx:uri");
+ additionalNamespaceProperties = new Property[] {
+ propertyFactory.create(nameFactory.create("nsx:something"),
"Some value"),
+ propertyFactory.create(nameFactory.create("nsx:something2"),
"Some value2"),
+ propertyFactory.create(nameFactory.create("other:something2"),
"Some other value2")};
+
+ // Set up the repository that we'll be using ...
+ source = new InMemoryRepositorySource();
+ source.setName("namespace repository");
+ graph = Graph.create(source, context);
+
+ // Create the path to the where the namespaces will be managed ...
+ pathToParentOfNamespaceNodes =
graph.create("/a").and().create("/a/b").and().createAt("/a/b/c").getLocation().getPath();
+
+ // Now set up the graph-based namespace registry ...
+ namespaceRegistry = new GraphNamespaceRegistry(graph,
pathToParentOfNamespaceNodes, uriPropertyName,
+ additionalNamespaceProperties);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see
org.jboss.dna.graph.property.basic.AbstractNamespaceRegistryTest#createNamespaceRegistry()
+ */
+ @Override
+ protected GraphNamespaceRegistry createNamespaceRegistry() {
+ return null;
+ }
+
+ @Test
+ public void shouldInitializeFromPersistedContent() {
+ // Add some namespaces ...
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix1),
is(validNamespaceUri1));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix2),
is(validNamespaceUri2));
+
+ // Now set up the graph-based namespace registry ...
+ GraphNamespaceRegistry registry2 = new GraphNamespaceRegistry(graph,
pathToParentOfNamespaceNodes, uriPropertyName,
+
additionalNamespaceProperties);
+ // All namespaces should match ...
+ Set<NamespaceRegistry.Namespace> all = namespaceRegistry.getNamespaces();
+ Set<NamespaceRegistry.Namespace> all2 = registry2.getNamespaces();
+ assertThat(all, is(all2));
+ assertThat(registry2.getNamespaceForPrefix(validPrefix1),
is(validNamespaceUri1));
+ assertThat(registry2.getNamespaceForPrefix(validPrefix2),
is(validNamespaceUri2));
+
+ registry2.refresh();
+ all2 = registry2.getNamespaces();
+ assertThat(all, is(all2));
+ assertThat(registry2.getNamespaceForPrefix(validPrefix1),
is(validNamespaceUri1));
+ assertThat(registry2.getNamespaceForPrefix(validPrefix2),
is(validNamespaceUri2));
+ }
+
+ @Test
+ public void shouldRefreshFromPersistedContent() {
+ // Add some namespaces ...
+ namespaceRegistry.register(validPrefix1, validNamespaceUri1);
+ namespaceRegistry.register(validPrefix2, validNamespaceUri2);
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix1),
is(validNamespaceUri1));
+ assertThat(namespaceRegistry.getNamespaceForPrefix(validPrefix2),
is(validNamespaceUri2));
+
+ // Get the namespaces, refresh, then get all the namespaces again
+ Set<NamespaceRegistry.Namespace> allBefore =
namespaceRegistry.getNamespaces();
+ namespaceRegistry.refresh();
+ Set<NamespaceRegistry.Namespace> allAfter =
namespaceRegistry.getNamespaces();
+
+ assertThat(allBefore, is(allAfter));
+ for (NamespaceRegistry.Namespace namespace : allBefore) {
+ assertThat(namespaceRegistry.getNamespaceForPrefix(namespace.getPrefix()),
is(namespace.getNamespaceUri()));
+
assertThat(namespaceRegistry.getPrefixForNamespaceUri(namespace.getNamespaceUri(), false),
is(namespace.getPrefix()));
+ }
+ }
+
+}
Property changes on:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/GraphNamespaceRegistryTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/InMemoryBinaryValueFactoryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/InMemoryBinaryValueFactoryTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/InMemoryBinaryValueFactoryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -23,8 +23,8 @@
*/
package org.jboss.dna.graph.property.basic;
-import static org.jboss.dna.graph.property.basic.BinaryContains.hasContent;
import static org.hamcrest.core.Is.is;
+import static org.jboss.dna.graph.property.basic.BinaryContains.hasContent;
import static org.junit.Assert.assertThat;
import java.io.ByteArrayInputStream;
import java.io.StringReader;
@@ -40,15 +40,9 @@
import org.jboss.dna.common.text.TextEncoder;
import org.jboss.dna.graph.property.Binary;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.Reference;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
-import org.jboss.dna.graph.property.basic.InMemoryBinaryValueFactory;
-import org.jboss.dna.graph.property.basic.JodaDateTime;
-import org.jboss.dna.graph.property.basic.NameValueFactory;
-import org.jboss.dna.graph.property.basic.PathValueFactory;
-import org.jboss.dna.graph.property.basic.StringValueFactory;
-import org.jboss.dna.graph.property.basic.UuidReference;
import org.junit.Before;
import org.junit.Test;
@@ -60,7 +54,7 @@
private InMemoryBinaryValueFactory factory;
private StringValueFactory stringFactory;
private NameValueFactory nameFactory;
- private BasicNamespaceRegistry namespaceRegistry;
+ private NamespaceRegistry namespaceRegistry;
private PathValueFactory pathFactory;
private TextEncoder encoder;
@@ -72,7 +66,7 @@
encoder = Path.URL_ENCODER;
stringFactory = new StringValueFactory(Path.URL_DECODER, encoder);
factory = new InMemoryBinaryValueFactory(Path.URL_DECODER, stringFactory);
- namespaceRegistry = new BasicNamespaceRegistry();
+ namespaceRegistry = new SimpleNamespaceRegistry();
namespaceRegistry.register("jboss", "http://www.jboss.org");
namespaceRegistry.register("dna",
"http://www.jboss.org/dna");
nameFactory = new NameValueFactory(namespaceRegistry, Path.URL_DECODER,
stringFactory);
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistryTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/LocalNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -28,8 +28,6 @@
import java.util.HashMap;
import java.util.Map;
import org.jboss.dna.graph.property.NamespaceRegistry;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
-import org.jboss.dna.graph.property.basic.LocalNamespaceRegistry;
import org.junit.Before;
import org.junit.Test;
@@ -44,7 +42,7 @@
@Before
public void beforeEach() {
- delegate = new BasicNamespaceRegistry();
+ delegate = new SimpleNamespaceRegistry();
local = new LocalNamespaceRegistry(delegate);
uri = "http://www.example.com";
}
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/NameValueFactoryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/NameValueFactoryTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/NameValueFactoryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -34,9 +34,6 @@
import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.ValueFactory;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
-import org.jboss.dna.graph.property.basic.NameValueFactory;
-import org.jboss.dna.graph.property.basic.StringValueFactory;
import org.junit.Before;
import org.junit.Test;
@@ -57,7 +54,7 @@
@Before
public void beforeEach() {
- this.registry = new BasicNamespaceRegistry();
+ this.registry = new SimpleNamespaceRegistry();
this.registry.register("dna",
"http://www.jboss.org/dna/namespace");
this.encoder = Path.DEFAULT_ENCODER;
this.decoder = Path.DEFAULT_DECODER;
Modified:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/PathValueFactoryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/PathValueFactoryTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/PathValueFactoryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -23,8 +23,8 @@
*/
package org.jboss.dna.graph.property.basic;
-import static org.jboss.dna.graph.property.basic.IsPathContaining.hasSegments;
import static org.hamcrest.core.Is.is;
+import static org.jboss.dna.graph.property.basic.IsPathContaining.hasSegments;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Iterator;
@@ -33,11 +33,6 @@
import org.jboss.dna.graph.property.Name;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.ValueFactory;
-import org.jboss.dna.graph.property.basic.BasicNamespaceRegistry;
-import org.jboss.dna.graph.property.basic.BasicPathSegment;
-import org.jboss.dna.graph.property.basic.NameValueFactory;
-import org.jboss.dna.graph.property.basic.PathValueFactory;
-import org.jboss.dna.graph.property.basic.StringValueFactory;
import org.junit.Before;
import org.junit.Test;
@@ -48,7 +43,7 @@
public static final TextEncoder NO_OP_ENCODER = Path.NO_OP_ENCODER;
- private BasicNamespaceRegistry registry;
+ private SimpleNamespaceRegistry registry;
private ValueFactory<String> stringValueFactory;
private NameValueFactory nameFactory;
private PathValueFactory factory;
@@ -57,7 +52,7 @@
@Before
public void beforeEach() {
- this.registry = new BasicNamespaceRegistry();
+ this.registry = new SimpleNamespaceRegistry();
this.registry.register("dna",
"http://www.jboss.org/dna/namespace");
this.stringValueFactory = new StringValueFactory(Path.DEFAULT_DECODER,
Path.DEFAULT_ENCODER);
this.nameFactory = new NameValueFactory(registry, Path.DEFAULT_DECODER,
stringValueFactory);
Copied:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistryTest.java
(from rev 723,
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/BasicNamespaceRegistryTest.java)
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistryTest.java
(rev 0)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,61 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.nullValue;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+/**
+ * @author Randall Hauch
+ */
+public class SimpleNamespaceRegistryTest extends
AbstractNamespaceRegistryTest<SimpleNamespaceRegistry> {
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see
org.jboss.dna.graph.property.basic.AbstractNamespaceRegistryTest#createNamespaceRegistry()
+ */
+ @Override
+ protected SimpleNamespaceRegistry createNamespaceRegistry() {
+ return new SimpleNamespaceRegistry();
+ }
+
+ @Test
+ public void shouldGeneratePrefixIfNamespaceUriIsNotRegistered() {
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, false),
is(nullValue()));
+ // Now get the generated prefix ...
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri3, true),
is("ns001"));
+ // Change the template ...
+ namespaceRegistry.setGeneratedPrefixTemplate("xyz0000abc");
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, true),
is("xyz0002abc"));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri2, true),
is("xyz0002abc"));
+ // Change the template again ...
+ namespaceRegistry.setGeneratedPrefixTemplate("xyz####abc");
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, true),
is("xyz3abc"));
+ assertThat(namespaceRegistry.getPrefixForNamespaceUri(validNamespaceUri1, true),
is("xyz3abc"));
+ }
+
+}
Property changes on:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/SimpleNamespaceRegistryTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistryTest.java
===================================================================
---
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistryTest.java
(rev 0)
+++
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -0,0 +1,42 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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.graph.property.basic;
+
+
+/**
+ * @author Randall Hauch
+ */
+public class ThreadSafeNamespaceRegistryTest extends
AbstractNamespaceRegistryTest<ThreadSafeNamespaceRegistry> {
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see
org.jboss.dna.graph.property.basic.AbstractNamespaceRegistryTest#createNamespaceRegistry()
+ */
+ @Override
+ protected ThreadSafeNamespaceRegistry createNamespaceRegistry() {
+ return new ThreadSafeNamespaceRegistry(new SimpleNamespaceRegistry());
+ }
+
+}
Property changes on:
trunk/dna-graph/src/test/java/org/jboss/dna/graph/property/basic/ThreadSafeNamespaceRegistryTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/DnaLexicon.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/DnaLexicon.java
(rev 0)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/DnaLexicon.java 2009-02-27 22:21:50 UTC
(rev 738)
@@ -0,0 +1,37 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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 org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.basic.BasicName;
+
+/**
+ * @author Randall Hauch
+ */
+public class DnaLexicon extends org.jboss.dna.graph.DnaLexicon {
+
+ public static final Name NAMESPACES = new BasicName(Namespace.URI,
"namespaces");
+ public static final Name NAMESPACE = new BasicName(Namespace.URI,
"namespace");
+
+}
Property changes on: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/DnaLexicon.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java 2009-02-24 14:40:05 UTC
(rev 737)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java 2009-02-27 22:21:50 UTC
(rev 738)
@@ -1,57 +1,78 @@
-/*
- * JBoss DNA (
http://www.jboss.org/dna)
- * See the COPYRIGHT.txt file distributed with this work for information
- * regarding copyright ownership. Some portions may be licensed
- * to Red Hat, Inc. under one or more contributor license agreements.
-* See the AUTHORS.txt file in the distribution for a full listing of
-* individual contributors.
- *
- * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
- * is licensed to you 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.
- *
- * JBoss DNA 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 org.jboss.dna.common.i18n.I18n;
-
-/**
- * @author John Verhaeg
- * @author Randall Hauch
- */
-public final class JcrI18n {
-
- public static I18n cannotConvertValue;
- public static I18n credentialsMustProvideJaasMethod;
- public static I18n credentialsMustReturnAccessControlContext;
- public static I18n credentialsMustReturnLoginContext;
- public static I18n defaultWorkspaceName;
- public static I18n inputStreamConsumed;
- public static I18n nonInputStreamConsumed;
- public static I18n pathNotFound;
- public static I18n permissionDenied;
- public static I18n repositoryMustBeConfigured;
- public static I18n sourceInUse;
-
- public static I18n REP_NAME_DESC;
- public static I18n REP_VENDOR_DESC;
- public static I18n SPEC_NAME_DESC;
-
- static {
- try {
- I18n.initialize(JcrI18n.class);
- } catch (final Exception err) {
- System.err.println(err);
- }
- }
-}
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+* See the AUTHORS.txt file in the distribution for a full listing of
+* individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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 org.jboss.dna.common.i18n.I18n;
+
+/**
+ * @author John Verhaeg
+ * @author Randall Hauch
+ */
+public final class JcrI18n {
+
+ public static I18n cannotConvertValue;
+ public static I18n credentialsMustProvideJaasMethod;
+ public static I18n credentialsMustReturnAccessControlContext;
+ public static I18n credentialsMustReturnLoginContext;
+ public static I18n defaultWorkspaceName;
+ public static I18n inputStreamConsumed;
+ public static I18n nonInputStreamConsumed;
+ public static I18n pathNotFound;
+ public static I18n permissionDenied;
+ public static I18n repositoryMustBeConfigured;
+ public static I18n sourceInUse;
+
+ public static I18n noNamespaceWithPrefix;
+ public static I18n noNamespaceWithUri;
+ public static I18n unableToChangeTheDefaultNamespace;
+ public static I18n unableToRegisterReservedNamespacePrefix;
+ public static I18n unableToRegisterReservedNamespaceUri;
+ public static I18n unableToRegisterNamespaceUsingXmlPrefix;
+ public static I18n unableToRegisterNamespaceWithInvalidPrefix;
+ public static I18n errorRegisteringPersistentNamespace;
+ public static I18n unableToUnregisterReservedNamespacePrefix;
+ public static I18n unableToUnregisterReservedNamespaceUri;
+ public static I18n unableToUnregisterPrefixForNamespaceThatIsNotRegistered;
+
+ public static I18n errorWhileInitializingTheNamespaceRegistry;
+ public static I18n invalidPathParameter;
+
+ public static I18n REP_NAME_DESC;
+ public static I18n REP_VENDOR_DESC;
+ public static I18n SPEC_NAME_DESC;
+
+ // New implementation
+ public static I18n errorObtainingWorkspaceNames;
+ public static I18n errorObtainingDefaultWorkspaceName;
+ public static I18n workspaceNameIsInvalid;
+ public static I18n errorVerifyingWorkspaceName;
+
+ static {
+ try {
+ I18n.initialize(JcrI18n.class);
+ } catch (final Exception err) {
+ System.err.println(err);
+ }
+ }
+}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrLexicon.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrLexicon.java 2009-02-24 14:40:05 UTC
(rev 737)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrLexicon.java 2009-02-27 22:21:50 UTC
(rev 738)
@@ -23,10 +23,14 @@
*/
package org.jboss.dna.jcr;
+import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.basic.BasicName;
/**
* @author Randall Hauch
*/
class JcrLexicon extends org.jboss.dna.graph.JcrLexicon {
+ public static final Name SYSTEM = new BasicName(Namespace.URI, "system");
+
}
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 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNamespaceRegistry.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -23,34 +23,99 @@
*/
package org.jboss.dna.jcr;
-import java.util.Iterator;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
import java.util.Set;
+import javax.jcr.AccessDeniedException;
import javax.jcr.NamespaceException;
-import javax.jcr.NamespaceRegistry;
import javax.jcr.RepositoryException;
-import javax.jcr.UnsupportedRepositoryOperationException;
+import javax.xml.XMLConstants;
+import net.jcip.annotations.ThreadSafe;
+import org.jboss.dna.common.util.CheckArg;
+import org.jboss.dna.common.xml.XmlCharacters;
+import org.jboss.dna.graph.JcrLexicon;
+import org.jboss.dna.graph.JcrMixLexicon;
+import org.jboss.dna.graph.JcrNtLexicon;
+import org.jboss.dna.graph.property.NamespaceRegistry;
+import org.jboss.dna.graph.property.NamespaceRegistry.Namespace;
+import org.jboss.dna.graph.property.basic.SimpleNamespaceRegistry;
+import org.jboss.dna.graph.property.basic.ThreadSafeNamespaceRegistry;
/**
- * @author John Verhaeg
- * @author Randall Hauch
+ * A thread-safe JCR {@link javax.jcr.NamespaceRegistry} implementation that has the
standard JCR namespaces pre-registered and
+ * enforces the JCR semantics for {@link #registerNamespace(String, String) registering}
and {@link #unregisterNamespace(String)
+ * unregistering} namespaces.
*/
-final class JcrNamespaceRegistry implements NamespaceRegistry {
+@ThreadSafe
+class JcrNamespaceRegistry implements javax.jcr.NamespaceRegistry {
- private org.jboss.dna.graph.property.NamespaceRegistry dnaNamespaceRegistry;
+ static final String DEFAULT_NAMESPACE_PREFIX = "";
+ static final String DEFAULT_NAMESPACE_URI = "";
- JcrNamespaceRegistry( org.jboss.dna.graph.property.NamespaceRegistry
dnaNamespaceRegistry ) {
- this.dnaNamespaceRegistry = dnaNamespaceRegistry;
+ static final String XML_NAMESPACE_PREFIX = XMLConstants.XML_NS_PREFIX;
+ static final String XML_NAMESPACE_URI = XMLConstants.XML_NS_URI;
+ static final String XMLNS_NAMESPACE_PREFIX = XMLConstants.XMLNS_ATTRIBUTE;
+ static final String XMLNS_NAMESPACE_URI = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
+
+ static final Set<String> STANDARD_BUILT_IN_PREFIXES;
+ static final Set<String> STANDARD_BUILT_IN_URIS;
+ static final Map<String, String> STANDARD_BUILT_IN_NAMESPACES_BY_PREFIX;
+ static final Map<String, String> STANDARD_BUILT_IN_PREFIXES_BY_NAMESPACE;
+
+ static {
+ // Set up the standard namespaces ...
+ Map<String, String> namespaces = new HashMap<String, String>();
+ namespaces.put(DEFAULT_NAMESPACE_PREFIX, DEFAULT_NAMESPACE_URI);
+ namespaces.put(JcrLexicon.Namespace.PREFIX, JcrLexicon.Namespace.URI);
+ namespaces.put(JcrNtLexicon.Namespace.PREFIX, JcrNtLexicon.Namespace.URI);
+ namespaces.put(JcrMixLexicon.Namespace.PREFIX, JcrMixLexicon.Namespace.URI);
+ namespaces.put(JcrSvLexicon.Namespace.PREFIX, JcrSvLexicon.Namespace.URI);
+ namespaces.put(XML_NAMESPACE_PREFIX, XML_NAMESPACE_URI);
+ namespaces.put(XMLNS_NAMESPACE_PREFIX, XMLNS_NAMESPACE_URI);
+ namespaces.put(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
+ // Set up the reverse map for the standard namespaces ...
+ Map<String, String> prefixes = new HashMap<String, String>();
+ for (Map.Entry<String, String> entry : namespaces.entrySet()) {
+ String uri = entry.getValue();
+ String prefix = entry.getKey();
+ prefixes.put(uri, prefix);
+ }
+ // Now set up the unmodifiable static collections ...
+ STANDARD_BUILT_IN_NAMESPACES_BY_PREFIX =
Collections.unmodifiableMap(namespaces);
+ STANDARD_BUILT_IN_PREFIXES_BY_NAMESPACE = Collections.unmodifiableMap(prefixes);
+ STANDARD_BUILT_IN_PREFIXES = Collections.unmodifiableSet(namespaces.keySet());
+ STANDARD_BUILT_IN_URIS = Collections.unmodifiableSet(new
HashSet<String>(namespaces.values()));
}
+ private final NamespaceRegistry registry;
+
+ JcrNamespaceRegistry() {
+ this(new ThreadSafeNamespaceRegistry(new SimpleNamespaceRegistry())); //
thread-safe implementation
+ }
+
+ JcrNamespaceRegistry( NamespaceRegistry dnaRegistry ) {
+ this.registry = dnaRegistry;
+ // Add the built-ins, ensuring we overwrite any badly-initialized values ...
+ for (Map.Entry<String, String> builtIn :
STANDARD_BUILT_IN_NAMESPACES_BY_PREFIX.entrySet()) {
+ this.registry.register(builtIn.getKey(), builtIn.getValue());
+ }
+ }
+
/**
* {@inheritDoc}
*
* @see javax.jcr.NamespaceRegistry#getPrefix(java.lang.String)
*/
public String getPrefix( String uri ) throws NamespaceException, RepositoryException
{
- String prefix = dnaNamespaceRegistry.getPrefixForNamespaceUri(uri, false);
+ // Check the standard ones first, ensuring that invalid changes to the persistent
storage don't matter ...
+ String prefix = STANDARD_BUILT_IN_PREFIXES_BY_NAMESPACE.get(uri);
+ if (prefix != null) return prefix;
+ // Now check the underlying registry ...
+ prefix = registry.getPrefixForNamespaceUri(uri, false);
if (prefix == null) {
- throw new NamespaceException();
+ throw new NamespaceException(JcrI18n.noNamespaceWithUri.text(uri));
}
return prefix;
}
@@ -61,11 +126,11 @@
* @see javax.jcr.NamespaceRegistry#getPrefixes()
*/
public String[] getPrefixes() {
- 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);
+ Set<Namespace> namespaces = registry.getNamespaces();
+ String[] prefixes = new String[namespaces.size()];
+ int i = 0;
+ for (Namespace namespace : namespaces) {
+ prefixes[i++] = namespace.getPrefix();
}
return prefixes;
}
@@ -75,10 +140,14 @@
*
* @see javax.jcr.NamespaceRegistry#getURI(java.lang.String)
*/
- public String getURI( String prefix ) throws NamespaceException {
- String uri = dnaNamespaceRegistry.getNamespaceForPrefix(prefix);
+ public String getURI( String prefix ) throws NamespaceException, RepositoryException
{
+ // Check the standard ones first, ensuring that invalid changes to the persistent
storage don't matter ...
+ String uri = STANDARD_BUILT_IN_NAMESPACES_BY_PREFIX.get(prefix);
+ if (uri != null) return uri;
+ // Now check the underlying registry ...
+ uri = registry.getNamespaceForPrefix(prefix);
if (uri == null) {
- throw new NamespaceException();
+ throw new NamespaceException(JcrI18n.noNamespaceWithPrefix.text(prefix));
}
return uri;
}
@@ -89,22 +158,90 @@
* @see javax.jcr.NamespaceRegistry#getURIs()
*/
public String[] getURIs() {
- Set<String> uris = dnaNamespaceRegistry.getRegisteredNamespaceUris();
- return uris.toArray(new String[uris.size()]);
+ Set<Namespace> namespaces = registry.getNamespaces();
+ String[] uris = new String[namespaces.size()];
+ int i = 0;
+ for (Namespace namespace : namespaces) {
+ uris[i++] = namespace.getNamespaceUri();
+ }
+ return uris;
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.NamespaceRegistry#registerNamespace(java.lang.String,
java.lang.String)
*/
- public void registerNamespace( String prefix,
- String uri ) throws
UnsupportedRepositoryOperationException {
- throw new UnsupportedRepositoryOperationException();
+ public synchronized void registerNamespace( String prefix,
+ String uri ) throws NamespaceException,
RepositoryException {
+ CheckArg.isNotNull(prefix, "prefix");
+ CheckArg.isNotNull(uri, "uri");
+ // Check the zero-length prefix and zero-length URI ...
+ if (DEFAULT_NAMESPACE_PREFIX.equals(prefix) || DEFAULT_NAMESPACE_URI.equals(uri))
{
+ throw new
NamespaceException(JcrI18n.unableToChangeTheDefaultNamespace.text());
+ }
+ // Check whether the prefix or URI are reserved (case-sensitive) ...
+ if (STANDARD_BUILT_IN_PREFIXES.contains(prefix)) {
+ throw new
NamespaceException(JcrI18n.unableToRegisterReservedNamespacePrefix.text(prefix, uri));
+ }
+ if (STANDARD_BUILT_IN_URIS.contains(uri)) {
+ throw new
NamespaceException(JcrI18n.unableToRegisterReservedNamespaceUri.text(prefix, uri));
+ }
+ // Check whether the prefix begins with 'xml' (in any case) ...
+ if (prefix.toLowerCase().startsWith(XML_NAMESPACE_PREFIX)) {
+ throw new
NamespaceException(JcrI18n.unableToRegisterNamespaceUsingXmlPrefix.text(prefix, uri));
+ }
+
+ // The prefix must be a valid XML Namespace prefix (i.e., a valid NCName) ...
+ if (!XmlCharacters.isValidName(prefix)) {
+ throw new
NamespaceException(JcrI18n.unableToRegisterNamespaceWithInvalidPrefix.text(prefix, uri));
+ }
+
+ // Now we're sure the prefix and URI are valid and okay for a custom mapping
...
+ try {
+ registry.register(prefix, uri);
+ } catch (RuntimeException e) {
+ throw new RepositoryException(e.getMessage(), e.getCause());
+ }
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.NamespaceRegistry#unregisterNamespace(java.lang.String)
*/
- public void unregisterNamespace( String prefix ) throws
UnsupportedRepositoryOperationException {
- throw new UnsupportedRepositoryOperationException();
+ public synchronized void unregisterNamespace( String prefix )
+ throws NamespaceException, AccessDeniedException, RepositoryException {
+ CheckArg.isNotNull(prefix, "prefix");
+ // Look to see whether the prefix is registered ...
+ String uri = registry.getNamespaceForPrefix(prefix);
+ // It is an error to unregister a namespace that is not registered ...
+ if (uri == null) {
+ throw new
NamespaceException(JcrI18n.unableToUnregisterPrefixForNamespaceThatIsNotRegistered.text(prefix));
+ }
+ // Unregistering a built-in prefix or URI is invalid ...
+ if (STANDARD_BUILT_IN_PREFIXES.contains(prefix)) {
+ throw new
NamespaceException(JcrI18n.unableToUnregisterReservedNamespacePrefix.text(prefix, uri));
+ }
+ if (STANDARD_BUILT_IN_URIS.contains(uri)) {
+ throw new
NamespaceException(JcrI18n.unableToUnregisterReservedNamespaceUri.text(prefix, uri));
+ }
+
+ // Now we're sure the prefix is valid and is actually used in a mapping ...
+ try {
+ registry.unregister(uri);
+ } catch (RuntimeException e) {
+ throw new RepositoryException(e.getMessage(), e.getCause());
+ }
}
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString() {
+ return registry.toString();
+ }
}
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 2009-02-24 14:40:05
UTC (rev 737)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java 2009-02-27 22:21:50
UTC (rev 738)
@@ -28,10 +28,9 @@
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import java.util.UUID;
+import java.util.Set;
import javax.jcr.Credentials;
-import javax.jcr.LoginException;
-import javax.jcr.Node;
+import javax.jcr.NoSuchWorkspaceException;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
@@ -42,8 +41,8 @@
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Graph;
import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
-import com.google.common.base.ReferenceType;
-import com.google.common.collect.ReferenceMap;
+import org.jboss.dna.graph.connector.RepositorySourceException;
+import org.jboss.dna.graph.request.InvalidWorkspaceException;
/**
* Creates JCR {@link Session sessions} to an underlying repository (which may be a
federated repository).
@@ -72,6 +71,7 @@
@ThreadSafe
public class JcrRepository implements Repository {
+ private final String sourceName;
private final Map<String, String> descriptors;
private final ExecutionContext executionContext;
private final RepositoryConnectionFactory connectionFactory;
@@ -82,12 +82,14 @@
*
* @param executionContext An execution context.
* @param connectionFactory A repository connection factory.
+ * @param repositorySourceName the name of the repository source (in the connection
factory) that should be used
* @throws IllegalArgumentException If
<code>executionContextFactory</code> or
<code>connectionFactory</code> is
* <code>null</code>.
*/
public JcrRepository( ExecutionContext executionContext,
- RepositoryConnectionFactory connectionFactory ) {
- this(null, executionContext, connectionFactory);
+ RepositoryConnectionFactory connectionFactory,
+ String repositorySourceName ) {
+ this(null, executionContext, connectionFactory, repositorySourceName);
}
/**
@@ -95,18 +97,22 @@
* establish {@link Session sessions} to the underlying repository source upon {@link
#login() login}.
*
* @param descriptors The {@link #getDescriptorKeys() descriptors} for this
repository; may be <code>null</code>.
- * @param executionContext An execution context.
- * @param connectionFactory A repository connection factory.
+ * @param executionContext the execution context in which this repository is to
operate
+ * @param connectionFactory the factory for repository connections
+ * @param repositorySourceName the name of the repository source (in the connection
factory) that should be used
* @throws IllegalArgumentException If
<code>executionContextFactory</code> or
<code>connectionFactory</code> is
* <code>null</code>.
*/
public JcrRepository( Map<String, String> descriptors,
ExecutionContext executionContext,
- RepositoryConnectionFactory connectionFactory ) {
+ RepositoryConnectionFactory connectionFactory,
+ String repositorySourceName ) {
CheckArg.isNotNull(executionContext, "executionContext");
CheckArg.isNotNull(connectionFactory, "connectionFactory");
+ CheckArg.isNotNull(repositorySourceName, "repositorySourceName");
this.executionContext = executionContext;
this.connectionFactory = connectionFactory;
+ this.sourceName = repositorySourceName;
Map<String, String> modifiableDescriptors;
if (descriptors == null) {
modifiableDescriptors = new HashMap<String, String>();
@@ -134,7 +140,7 @@
modifiableDescriptors.put(Repository.REP_VENDOR_URL_DESC,
"http://www.jboss.org/dna");
}
if (!modifiableDescriptors.containsKey(Repository.REP_VERSION_DESC)) {
- modifiableDescriptors.put(Repository.REP_VERSION_DESC, "0.2");
+ modifiableDescriptors.put(Repository.REP_VERSION_DESC, "0.4");
}
modifiableDescriptors.put(Repository.SPEC_NAME_DESC,
JcrI18n.SPEC_NAME_DESC.text());
modifiableDescriptors.put(Repository.SPEC_VERSION_DESC, "1.0");
@@ -142,6 +148,25 @@
}
/**
+ * Get the name of the repository source that this repository is using.
+ *
+ * @return the name of the RepositorySource
+ * @see #getConnectionFactory()
+ */
+ String getRepositorySourceName() {
+ return sourceName;
+ }
+
+ /**
+ * Get the connection factory that this repository is using.
+ *
+ * @return the connection factory; never null
+ */
+ RepositoryConnectionFactory getConnectionFactory() {
+ return this.connectionFactory;
+ }
+
+ /**
* {@inheritDoc}
*
* @throws IllegalArgumentException if <code>key</code> is
<code>null</code>.
@@ -206,6 +231,7 @@
public synchronized Session login( Credentials credentials,
String workspaceName ) throws RepositoryException
{
// Ensure credentials are either null or provide a JAAS method
+ Map<String, Object> sessionAttributes = new HashMap<String,
Object>();
ExecutionContext execContext;
if (credentials == null) {
execContext = executionContext;
@@ -246,21 +272,44 @@
} catch (Exception error) {
throw new RepositoryException(error);
}
+ if (credentials instanceof SimpleCredentials) {
+ SimpleCredentials simple = (SimpleCredentials)credentials;
+ for (String attributeName : simple.getAttributeNames()) {
+ Object attributeValue = simple.getAttribute(attributeName);
+ sessionAttributes.put(attributeName, attributeValue);
+ }
+ }
}
- // Authenticate if possible
- assert execContext != null;
- LoginContext loginContext = execContext.getLoginContext();
- if (loginContext != null) {
+
+ // Ensure valid workspace name
+ Graph graph = Graph.create(sourceName, connectionFactory, executionContext);
+ if (workspaceName == null) {
try {
- loginContext.login();
- } catch (javax.security.auth.login.LoginException error) {
- throw new LoginException(error);
+ // Get the correct workspace name given the desired workspace name (which
may be null) ...
+ workspaceName = graph.getCurrentWorkspace().getName();
+ } catch (RepositorySourceException e) {
+ throw new
RepositoryException(JcrI18n.errorObtainingDefaultWorkspaceName.text(sourceName,
e.getMessage()), e);
}
+ } else {
+ try {
+ // Verify that the workspace exists (or can be created) ...
+ Set<String> workspaces = graph.getWorkspaces();
+ if (!workspaces.contains(workspaceName)) {
+ // Try to create it ...
+ graph.createWorkspace().namedSomethingLike(workspaceName).getName();
+ }
+ workspaceName = graph.getCurrentWorkspace().getName();
+ } catch (InvalidWorkspaceException e) {
+ throw new
NoSuchWorkspaceException(JcrI18n.workspaceNameIsInvalid.text(sourceName, workspaceName),
e);
+ } catch (RepositorySourceException e) {
+ String msg = JcrI18n.errorVerifyingWorkspaceName.text(sourceName,
workspaceName, e.getMessage());
+ throw new NoSuchWorkspaceException(msg, e);
+ }
}
- // Ensure valid workspace name
- if (workspaceName == null) workspaceName = JcrI18n.defaultWorkspaceName.text();
- // Create session
- Graph graph = Graph.create(workspaceName, connectionFactory, execContext);
- return new JcrSession(this, workspaceName, graph, new ReferenceMap<UUID,
Node>(ReferenceType.STRONG, ReferenceType.SOFT));
+
+ // Create the workspace, which will create its own session ...
+ sessionAttributes = Collections.unmodifiableMap(sessionAttributes);
+ JcrWorkspace workspace = new JcrWorkspace(this, workspaceName, execContext,
sessionAttributes);
+ return workspace.getSession();
}
}
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 2009-02-24 14:40:05 UTC
(rev 737)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2009-02-27 22:21:50 UTC
(rev 738)
@@ -28,11 +28,14 @@
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Calendar;
+import java.util.Collections;
import java.util.HashSet;
+import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Credentials;
import javax.jcr.Item;
+import javax.jcr.NamespaceException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
@@ -40,6 +43,7 @@
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
@@ -48,14 +52,15 @@
import javax.security.auth.login.LoginException;
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Graph;
import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.NamespaceRegistry;
import org.jboss.dna.graph.property.Path;
import org.jboss.dna.graph.property.UuidFactory;
import org.jboss.dna.graph.property.ValueFactories;
+import org.jboss.dna.graph.property.basic.LocalNamespaceRegistry;
import org.xml.sax.ContentHandler;
import com.google.common.base.ReferenceType;
import com.google.common.collect.ReferenceMap;
@@ -67,32 +72,76 @@
@NotThreadSafe
class JcrSession implements Session {
- private final Repository repository;
+ private static final String[] NO_ATTRIBUTES_NAMES = new String[] {};
+
+ /**
+ * The repository that created this session.
+ */
+ private final JcrRepository repository;
+
+ /**
+ * The workspace that corresponds to this session.
+ */
+ private final JcrWorkspace workspace;
+
+ /**
+ * A JCR namespace registry that is specific to this session, with any
locally-defined namespaces defined in this session.
+ * This is backed by the workspace's namespace registry.
+ */
+ private final JcrNamespaceRegistry sessionRegistry;
+
+ /**
+ * The execution context for this session, which uses the {@link #sessionRegistry
session's namespace registry}
+ */
+ private final ExecutionContext executionContext;
+
+ /**
+ * The graph representing this session, which uses the {@link #graph session's
graph}.
+ */
private final Graph graph;
- private final ExecutionContext executionContext;
+
+ /**
+ * The session-specific attributes that came from the {@link SimpleCredentials}'
{@link SimpleCredentials#getAttributeNames()}
+ */
+ private final Map<String, Object> sessionAttributes;
+
private final ReferenceMap<UUID, Node> nodesByUuid;
private final ReferenceMap<String, Node> nodesByJcrUuid;
private boolean isLive;
- private Workspace workspace;
private JcrRootNode rootNode;
- JcrSession( Repository repository,
- String workspaceName,
- Graph graph,
- ReferenceMap<UUID, Node> nodesByUuid ) throws RepositoryException
{
+ JcrSession( JcrRepository repository,
+ JcrWorkspace workspace,
+ ExecutionContext workspaceContext,
+ Map<String, Object> sessionAttributes ) {
assert repository != null;
- assert graph != null;
- assert workspaceName != null;
- assert nodesByUuid != null;
+ assert workspace != null;
+ assert sessionAttributes != null;
+ assert workspaceContext != null;
this.repository = repository;
- this.graph = graph;
- this.executionContext = graph.getContext();
- assert this.executionContext != null;
- this.nodesByUuid = nodesByUuid;
+ this.sessionAttributes = sessionAttributes;
+ this.workspace = workspace;
+
+ // Create an execution context for this session, which should use the local
namespace registry ...
+ NamespaceRegistry local = new
LocalNamespaceRegistry(workspaceContext.getNamespaceRegistry());
+ this.executionContext = workspaceContext.with(local);
+ this.sessionRegistry = new JcrNamespaceRegistry(local);
+
+ // Set up the graph to use for this session (which uses the session's
namespace registry and context) ...
+ this.graph = Graph.create(this.repository.getRepositorySourceName(),
+ this.repository.getConnectionFactory(),
+ this.executionContext);
+
+ this.nodesByUuid = new ReferenceMap<UUID, Node>(ReferenceType.STRONG,
ReferenceType.SOFT);
this.nodesByJcrUuid = new ReferenceMap<String, Node>(ReferenceType.STRONG,
ReferenceType.SOFT);
this.isLive = true;
- // Following must be initialized after session's state is initialized
- this.workspace = new JcrWorkspace(this, workspaceName);
+
+ assert this.repository != null;
+ assert this.sessionAttributes != null;
+ assert this.workspace != null;
+ assert this.executionContext != null;
+ assert this.sessionRegistry != null;
+ assert this.graph != null;
}
ExecutionContext getExecutionContext() {
@@ -100,8 +149,94 @@
}
/**
+ * Return an unmodifiable map of nodes given then UUID.
+ *
+ * @return nodesByUuid
+ */
+ Map<UUID, Node> getNodesByUuid() {
+ return Collections.unmodifiableMap(nodesByUuid);
+ }
+
+ /**
* {@inheritDoc}
*
+ * @see javax.jcr.Session#getWorkspace()
+ */
+ public Workspace getWorkspace() {
+ return this.workspace;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Session#getRepository()
+ */
+ public Repository getRepository() {
+ return this.repository;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return <code>null</code>
+ * @see javax.jcr.Session#getAttribute(java.lang.String)
+ */
+ public Object getAttribute( String name ) {
+ return sessionAttributes.get(name);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return An empty array
+ * @see javax.jcr.Session#getAttributeNames()
+ */
+ public String[] getAttributeNames() {
+ Set<String> names = sessionAttributes.keySet();
+ if (names.isEmpty()) return NO_ATTRIBUTES_NAMES;
+ return names.toArray(new String[names.size()]);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Session#getNamespacePrefix(java.lang.String)
+ */
+ public String getNamespacePrefix( String uri ) throws RepositoryException {
+ return sessionRegistry.getPrefix(uri);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Session#getNamespacePrefixes()
+ */
+ public String[] getNamespacePrefixes() {
+ return sessionRegistry.getPrefixes();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Session#getNamespaceURI(java.lang.String)
+ */
+ public String getNamespaceURI( String prefix ) throws RepositoryException {
+ return sessionRegistry.getURI(prefix);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Session#setNamespacePrefix(java.lang.String, java.lang.String)
+ */
+ public void setNamespacePrefix( String newPrefix,
+ String existingUri ) throws NamespaceException,
RepositoryException {
+ sessionRegistry.registerNamespace(newPrefix, existingUri);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @throws UnsupportedOperationException always
* @see javax.jcr.Session#addLockToken(java.lang.String)
*/
@@ -179,26 +314,6 @@
/**
* {@inheritDoc}
*
- * @return <code>null</code>
- * @see javax.jcr.Session#getAttribute(java.lang.String)
- */
- public Object getAttribute( String name ) {
- return null;
- }
-
- /**
- * {@inheritDoc}
- *
- * @return An empty array
- * @see javax.jcr.Session#getAttributeNames()
- */
- public String[] getAttributeNames() {
- return StringUtil.EMPTY_STRING_ARRAY;
- }
-
- /**
- * {@inheritDoc}
- *
* @throws UnsupportedOperationException always
* @see javax.jcr.Session#getImportContentHandler(java.lang.String, int)
*/
@@ -255,33 +370,6 @@
throw new UnsupportedOperationException();
}
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.Session#getNamespacePrefix(java.lang.String)
- */
- public String getNamespacePrefix( String uri ) throws RepositoryException {
- return workspace.getNamespaceRegistry().getPrefix(uri);
- }
-
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.Session#getNamespacePrefixes()
- */
- public String[] getNamespacePrefixes() throws RepositoryException {
- return workspace.getNamespaceRegistry().getPrefixes();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.Session#getNamespaceURI(java.lang.String)
- */
- public String getNamespaceURI( String prefix ) throws RepositoryException {
- return workspace.getNamespaceRegistry().getURI(prefix);
- }
-
private Node getNode( Path path ) throws RepositoryException {
// Get node from source
org.jboss.dna.graph.Node graphNode = graph.getNodeAt(path);
@@ -322,15 +410,6 @@
/**
* {@inheritDoc}
*
- * @see javax.jcr.Session#getRepository()
- */
- public Repository getRepository() {
- return this.repository;
- }
-
- /**
- * {@inheritDoc}
- *
* @see javax.jcr.Session#getRootNode()
*/
public Node getRootNode() {
@@ -407,15 +486,6 @@
/**
* {@inheritDoc}
*
- * @see javax.jcr.Session#getWorkspace()
- */
- public Workspace getWorkspace() {
- return this.workspace;
- }
-
- /**
- * {@inheritDoc}
- *
* @return false
* @see javax.jcr.Session#hasPendingChanges()
*/
@@ -428,8 +498,11 @@
*
* @see javax.jcr.Session#impersonate(javax.jcr.Credentials)
*/
+ @SuppressWarnings( "unused" )
public Session impersonate( Credentials credentials ) throws RepositoryException {
- return repository.login(credentials);
+ // this is not right:
+ // return repository.login(credentials);
+ throw new UnsupportedOperationException();
}
/**
@@ -521,7 +594,8 @@
if (uuid == null && DnaLexicon.UUID.equals(name)) uuid =
uuidFactory.create(dnaProp.getValues()).next();
else if (jcrUuidName.equals(name)) dnaUuidProp = dnaProp;
else if (jcrMixinTypesName.equals(name)) {
- org.jboss.dna.graph.property.ValueFactory<String> stringFactory
= executionContext.getValueFactories().getStringFactory();
+ org.jboss.dna.graph.property.ValueFactory<String> stringFactory
= executionContext.getValueFactories()
+
.getStringFactory();
for (String mixin : stringFactory.create(dnaProp)) {
if ("mix:referenceable".equals(mixin)) referenceable =
true;
}
@@ -573,15 +647,4 @@
public void save() {
throw new UnsupportedOperationException();
}
-
- /**
- * {@inheritDoc}
- *
- * @throws UnsupportedOperationException always
- * @see javax.jcr.Session#setNamespacePrefix(java.lang.String, java.lang.String)
- */
- public void setNamespacePrefix( String newPrefix,
- String existingUri ) {
- throw new UnsupportedOperationException();
- }
}
Added: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSvLexicon.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSvLexicon.java
(rev 0)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSvLexicon.java 2009-02-27 22:21:50
UTC (rev 738)
@@ -0,0 +1,37 @@
+/*
+ * JBoss DNA (
http://www.jboss.org/dna)
+ * See the COPYRIGHT.txt file distributed with this work for information
+ * regarding copyright ownership. Some portions may be licensed
+ * to Red Hat, Inc. under one or more contributor license agreements.
+ * See the AUTHORS.txt file in the distribution for a full listing of
+ * individual contributors.
+ *
+ * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ * is licensed to you 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.
+ *
+ * JBoss DNA 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;
+
+
+/**
+ * @author Randall Hauch
+ */
+public class JcrSvLexicon {
+
+ public static class Namespace {
+ public static final String URI = "http://www.jcp.org/jcr/sv/1.0";
+ public static final String PREFIX = "sv";
+ }
+
+}
Property changes on: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSvLexicon.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
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 2009-02-24 14:40:05
UTC (rev 737)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrWorkspace.java 2009-02-27 22:21:50
UTC (rev 738)
@@ -23,15 +23,41 @@
*/
package org.jboss.dna.jcr;
+import java.io.IOException;
import java.io.InputStream;
+import java.util.Map;
+import java.util.Set;
+import javax.jcr.AccessDeniedException;
+import javax.jcr.InvalidSerializedDataException;
+import javax.jcr.ItemExistsException;
import javax.jcr.NamespaceRegistry;
+import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
+import javax.jcr.lock.LockException;
+import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.observation.ObservationManager;
import javax.jcr.query.QueryManager;
import javax.jcr.version.Version;
+import javax.jcr.version.VersionException;
+import org.jboss.dna.common.util.CheckArg;
+import org.jboss.dna.graph.ExecutionContext;
+import org.jboss.dna.graph.Graph;
+import org.jboss.dna.graph.GraphImporter;
+import org.jboss.dna.graph.Location;
+import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
+import org.jboss.dna.graph.connector.RepositorySource;
+import org.jboss.dna.graph.connector.RepositorySourceException;
+import org.jboss.dna.graph.property.Name;
+import org.jboss.dna.graph.property.Path;
+import org.jboss.dna.graph.property.PathFactory;
+import org.jboss.dna.graph.property.Property;
+import org.jboss.dna.graph.property.PropertyFactory;
+import org.jboss.dna.graph.property.ValueFormatException;
+import org.jboss.dna.graph.property.basic.GraphNamespaceRegistry;
+import org.jboss.dna.graph.property.basic.ThreadSafeNamespaceRegistry;
import org.xml.sax.ContentHandler;
/**
@@ -40,158 +66,261 @@
*/
final class JcrWorkspace implements Workspace {
+ /**
+ * The name of this workspace. This name is used as the name of the source when
+ * {@link RepositoryConnectionFactory#createConnection(String) creating connections}
to the underlying
+ * {@link RepositorySource} that stores the content for this workspace.
+ */
private final String name;
- private final JcrSession session;
- private final NamespaceRegistry namespaceRegistry;
/**
- * @param session the session that owns this workspace; may not be null
- * @param name the name of the workspace; may not be null
- * @throws RepositoryException
+ * The context in which this workspace is executing/operating. This context already
has been authenticated.
*/
- JcrWorkspace( JcrSession session,
- String name ) throws RepositoryException {
- assert session != null;
- 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;
- // for (String accessibleName : getAccessibleWorkspaceNames()) {
- // if (name.equalsIgnoreCase(accessibleName)) {
- // matchedName = name;
- // break;
- // }
- // }
- // if (matchedName == null) {
- // throw new LoginException();
- // }
+ private final ExecutionContext context;
+
+ /**
+ * The reference to the {@link JcrRepository} instance that owns this {@link
Workspace} instance. Very few methods on this
+ * repository object are used; mainly {@link JcrRepository#getConnectionFactory()}
and
+ * {@link JcrRepository#getRepositorySourceName()}.
+ */
+ private final JcrRepository repository;
+
+ /**
+ * The graph used by this workspace to access persistent content. This graph is not
thread-safe, but since this workspace is
+ * not thread-safe, it is okay for any method in this workspace to use the same
graph. It is also okay for other objects that
+ * have the same thread context as this workspace (e.g., the session, namespace
registry, etc.) to also reuse this same graph
+ * instance (though it's not very expensive at all for each to have their own
instance, too).
+ */
+ private final Graph graph;
+
+ /**
+ * Reference to the namespace registry for this workspace. Per the JCR specification,
this registry instance is persistent
+ * (unlike the namespace-related methods in the {@link Session}, like {@link
Session#getNamespacePrefix(String)},
+ * {@link Session#setNamespacePrefix(String, String)}, etc.).
+ */
+ private final JcrNamespaceRegistry workspaceRegistry;
+
+ /**
+ * The {@link Session} instance that this corresponds with this workspace.
+ */
+ private final JcrSession session;
+
+ JcrWorkspace( JcrRepository repository,
+ String workspaceName,
+ ExecutionContext context,
+ Map<String, Object> sessionAttributes ) {
+ assert workspaceName != null;
+ assert context != null;
+ assert repository != null;
+ this.name = workspaceName;
+ this.repository = repository;
+
+ // Set up the execution context for this workspace, which should use the
namespace registry that persists
+ // the namespaces in the graph ...
+ Graph namespaceGraph = Graph.create(this.repository.getRepositorySourceName(),
+ this.repository.getConnectionFactory(),
+ context);
+ Name uriProperty = DnaLexicon.NAMESPACE_URI;
+ PathFactory pathFactory = context.getValueFactories().getPathFactory();
+ Path root = pathFactory.createRootPath();
+ Path namespacesPath = context.getValueFactories().getPathFactory().create(root,
JcrLexicon.SYSTEM, DnaLexicon.NAMESPACES);
+ PropertyFactory propertyFactory = context.getPropertyFactory();
+ Property namespaceType = propertyFactory.create(JcrLexicon.PRIMARY_TYPE,
DnaLexicon.NAMESPACE);
+ org.jboss.dna.graph.property.NamespaceRegistry persistentRegistry = new
GraphNamespaceRegistry(namespaceGraph,
+
namespacesPath,
+
uriProperty, namespaceType);
+ persistentRegistry = new ThreadSafeNamespaceRegistry(persistentRegistry);
+ this.context = context.with(persistentRegistry);
+
+ // Set up and initialize the persistent (and thread-safe) JCR namespace registry
...
+ this.workspaceRegistry = new JcrNamespaceRegistry(persistentRegistry);
+
+ // Now create a graph with this new execution context ...
+ this.graph = Graph.create(this.repository.getRepositorySourceName(),
this.repository.getConnectionFactory(), this.context);
+ this.graph.useWorkspace(workspaceName);
+
+ // Set up the session for this workspace ...
+ this.session = new JcrSession(this.repository, this, this.context,
sessionAttributes);
}
+ String getSourceName() {
+ return this.repository.getRepositorySourceName();
+ }
+
/**
* {@inheritDoc}
- *
- * @see javax.jcr.Workspace#clone(java.lang.String, java.lang.String,
java.lang.String, boolean)
*/
- public void clone( String srcWorkspace,
- String srcAbsPath,
- String destAbsPath,
- boolean removeExisting ) {
- throw new UnsupportedOperationException();
+ public String getName() {
+ return name;
}
/**
* {@inheritDoc}
*/
- public void copy( String srcAbsPath,
- String destAbsPath ) {
- throw new UnsupportedOperationException();
+ public Session getSession() {
+ return this.session;
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#getNamespaceRegistry()
*/
- public void copy( String srcWorkspace,
- String srcAbsPath,
- String destAbsPath ) {
- throw new UnsupportedOperationException();
+ public NamespaceRegistry getNamespaceRegistry() {
+ return workspaceRegistry;
}
/**
* {@inheritDoc}
*/
- public String[] getAccessibleWorkspaceNames() {
- // try {
- // Node node = session.getRootNode().getNode("dna:jcr");
- // if (node != null) {
- // Property property = node.getProperty("dna:workspaceNames");
- // if (property != null) {
- // Value[] values = property.getValues();
- // if (values.length > 0) {
- // String[] names = new String[values.length];
- // for (int ndx = values.length; --ndx >= 0;) {
- // names[ndx] = values[ndx].getString();
- // }
- // return names;
- // }
- // }
- // }
- // } catch (PathNotFoundException meansOnlyDefaultWorkspaceNameAvailable) {
- // // TODO: Check permissions and, if writable, create node & property and,
if allowed, set to include this source's name
- // }
- // // Repository is read-only, so just return this source's name
- // return new String[]
{session.getDnaRepository().getSource(session.getSubject()).getName()};
- throw new UnsupportedOperationException();
+ public String[] getAccessibleWorkspaceNames() throws RepositoryException {
+ try {
+ Set<String> workspaces = graph.getWorkspaces();
+ return workspaces.toArray(new String[workspaces.size()]);
+ } catch (RepositorySourceException e) {
+ throw new
RepositoryException(JcrI18n.errorObtainingWorkspaceNames.text(getSourceName(),
e.getMessage()), e);
+ }
}
/**
* {@inheritDoc}
*/
- public ContentHandler getImportContentHandler( String parentAbsPath,
- int uuidBehavior ) {
+ public NodeTypeManager getNodeTypeManager() {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
- public String getName() {
- return name;
+ public ObservationManager getObservationManager() {
+ throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
- *
- * @see javax.jcr.Workspace#getNamespaceRegistry()
*/
- public NamespaceRegistry getNamespaceRegistry() {
- return namespaceRegistry;
+ public QueryManager getQueryManager() {
+ throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#clone(java.lang.String, java.lang.String,
java.lang.String, boolean)
*/
- public NodeTypeManager getNodeTypeManager() {
+ public void clone( String srcWorkspace,
+ String srcAbsPath,
+ String destAbsPath,
+ boolean removeExisting ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#copy(java.lang.String, java.lang.String)
*/
- public ObservationManager getObservationManager() {
- throw new UnsupportedOperationException();
+ public void copy( String srcAbsPath,
+ String destAbsPath )
+ throws ConstraintViolationException, VersionException, AccessDeniedException,
PathNotFoundException, ItemExistsException,
+ LockException, RepositoryException {
+ CheckArg.isNotEmpty(srcAbsPath, "srcAbsPath");
+ CheckArg.isNotEmpty(destAbsPath, "destAbsPath");
+
+ // Create the paths ...
+ PathFactory factory = context.getValueFactories().getPathFactory();
+ Path srcPath = null;
+ Path destPath = null;
+ try {
+ srcPath = factory.create(srcAbsPath);
+ } catch (ValueFormatException e) {
+ throw new RepositoryException(JcrI18n.invalidPathParameter.text(srcAbsPath,
"srcAbsPath"), e);
+ }
+ try {
+ destPath = factory.create(destAbsPath);
+ } catch (ValueFormatException e) {
+ throw new RepositoryException(JcrI18n.invalidPathParameter.text(destAbsPath,
"destAbsPath"), e);
+ }
+
+ // Perform the copy operation, but use the "to" form (not the
"into", which takes the parent) ...
+ graph.copy(srcPath).to(destPath);
}
/**
* {@inheritDoc}
*/
- public QueryManager getQueryManager() {
+ public void copy( String srcWorkspace,
+ String srcAbsPath,
+ String destAbsPath ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#getImportContentHandler(java.lang.String, int)
*/
- public Session getSession() {
- return this.session;
+ @SuppressWarnings( "unused" )
+ public ContentHandler getImportContentHandler( String parentAbsPath,
+ int uuidBehavior )
+ throws PathNotFoundException, ConstraintViolationException, VersionException,
LockException, AccessDeniedException,
+ RepositoryException {
+ CheckArg.isNotEmpty(parentAbsPath, "parentAbsPath");
+ // Create a graph importer, which can return the content handler that can be used
by the caller
+ // to call the handler's event methods to create content...
+ GraphImporter importer = new GraphImporter(graph);
+ Path parentPath =
context.getValueFactories().getPathFactory().create(parentAbsPath);
+ return importer.getHandlerForImportingXml(Location.create(parentPath), false);
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#importXML(java.lang.String, java.io.InputStream, int)
*/
+ @SuppressWarnings( "unused" )
public void importXML( String parentAbsPath,
InputStream in,
- int uuidBehavior ) {
+ int uuidBehavior )
+ throws IOException, PathNotFoundException, ItemExistsException,
ConstraintViolationException,
+ InvalidSerializedDataException, LockException, AccessDeniedException,
RepositoryException {
+ // try {
+ // graph.importXmlFrom(in).into(parentAbsPath);
+ // } catch (org.jboss.dna.graph.property.PathNotFoundException e) {
+ // throw new PathNotFoundException(e.getMessage(), e);
+ // } catch (SAXException err) {
+ // }
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
+ *
+ * @see javax.jcr.Workspace#move(java.lang.String, java.lang.String)
*/
+ @SuppressWarnings( "unused" )
public void move( String srcAbsPath,
- String destAbsPath ) {
+ String destAbsPath ) throws PathNotFoundException,
RepositoryException {
+ CheckArg.isNotEmpty(srcAbsPath, "srcAbsPath");
+ CheckArg.isNotEmpty(destAbsPath, "destAbsPath");
+
+ // Create the paths ...
+ PathFactory factory = context.getValueFactories().getPathFactory();
+ Path srcPath = null;
+ Path destPath = null;
+ try {
+ srcPath = factory.create(srcAbsPath);
+ } catch (ValueFormatException e) {
+ throw new RepositoryException(JcrI18n.invalidPathParameter.text(srcAbsPath,
"srcAbsPath"), e);
+ }
+ try {
+ destPath = factory.create(destAbsPath);
+ } catch (ValueFormatException e) {
+ throw new RepositoryException(JcrI18n.invalidPathParameter.text(destAbsPath,
"destAbsPath"), e);
+ }
+
+ // Perform the copy operation, but use the "to" form (not the
"into", which takes the parent) ...
+ // graph.move(srcPath).to(destPath);
throw new UnsupportedOperationException();
}
Modified: trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties
===================================================================
--- trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties 2009-02-27
22:21:50 UTC (rev 738)
@@ -33,6 +33,26 @@
repositoryMustBeConfigured = DNA repositories must be configured with either a repository
source factory or a repository source.
sourceInUse = All sessions must end before a new repository source can be set.
+noNamespaceWithPrefix = There is no namespace with prefix "{0}"
+noNamespaceWithUri = There is no namespace with URI "{0}"
+unableToChangeTheDefaultNamespace = The default namespace is reserved and cannot be
changed
+unableToRegisterReservedNamespacePrefix = Unable to register the namespace
"{1}" with prefix "{0}" because this prefix is reserved
+unableToRegisterReservedNamespaceUri = Unable to register the namespace "{1}"
with prefix "{0}" because this URI is reserved
+unableToRegisterNamespaceUsingXmlPrefix = Unable to register the namespace
"{1}" with prefix "{0}" because prefixes starting with 'xml'
(in any case) are reserved
+unableToRegisterNamespaceWithInvalidPrefix = Unable to register the namespace
"{1}" with prefix "{0}" because the prefix must be a valid XML NCName
+errorRegisteringPersistentNamespace = Error registering the persisted namespace
"{1}" with prefix "{0}"
+unableToUnregisterReservedNamespacePrefix = Unable to unregister the namespace
"{1}" with prefix "{0}" because this prefix is reserved
+unableToUnregisterReservedNamespaceUri = Unable to unregister the namespace
"{1}" with prefix "{0}" because this URI is reserved
+unableToUnregisterPrefixForNamespaceThatIsNotRegistered = The namespace with prefix
"{0}" is not registered and cannot be unregistered
+
+errorWhileInitializingTheNamespaceRegistry = Error while initializing the namespace
registry for workspace "{0}"
+invalidPathParameter = The "{1}" parameter value "{0}" was not a
valid path
+
REP_NAME_DESC = DNA Repository
REP_VENDOR_DESC = JBoss - A division of Red Hat Middleware LLC
-SPEC_NAME_DESC = Content Repository for Java Technology API
\ No newline at end of file
+SPEC_NAME_DESC = Content Repository for Java Technology API
+
+errorObtainingWorkspaceNames = Error while obtaining the workspace names for the
"{0}" repository: {1}
+errorObtainingDefaultWorkspaceName = Error while obtaining the default workspace names
for the "{0}" repository: {1}
+workspaceNameIsInvalid = "{1}" is not a valid workspace name for the
"{0}" repository
+errorVerifyingWorkspaceName = Error validating the workspace name "{1}" for the
"{0}" repository: {2}
\ No newline at end of file
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JackrabbitJcrTckTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JackrabbitJcrTckTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JackrabbitJcrTckTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -161,8 +161,12 @@
// Wrap a connection to the in-memory (DNA) repository in a (JCR) repository
connection = source.getConnection();
repository = new JcrRepository(Collections.<String, String>emptyMap(),
executionContext.create(accessControlContext),
- connectionFactory);
+ connectionFactory, source.getName());
+ // Make sure the path to the namespaces exists ...
+ Graph graph = Graph.create(source.getName(), connectionFactory,
executionContext);
+
graph.create("/jcr:system").and().create("/jcr:system/dna:namespaces");
+
// Set up some sample nodes in the graph to match the expected test
configuration
try {
@@ -173,7 +177,6 @@
executionContext.getNamespaceRegistry().register("sv",
"http://www.jcp.org/jcr/sv/1.0");
Path destinationPath =
executionContext.getValueFactories().getPathFactory().create("/");
- Graph graph = Graph.create(source.getName(), connectionFactory,
executionContext);
GraphImporter importer = new GraphImporter(graph);
URI xmlContent = new
File("src/test/resources/repositoryJackrabbitTck.xml").toURI();
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 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNamespaceRegistryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -23,15 +23,13 @@
*/
package org.jboss.dna.jcr;
-import static org.hamcrest.collection.IsArrayContaining.hasItemInArray;
import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsNull.notNullValue;
+import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
import javax.jcr.NamespaceException;
-import javax.jcr.UnsupportedRepositoryOperationException;
import org.jboss.dna.graph.ExecutionContext;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
/**
@@ -39,83 +37,276 @@
*/
public class JcrNamespaceRegistryTest {
- static ExecutionContext executionContext;
+ private ExecutionContext executionContext;
private JcrNamespaceRegistry registry;
- @BeforeClass
- public static void beforeClass() throws Exception {
- executionContext = TestUtil.getExecutionContext();
- }
-
@Before
public void before() {
+ executionContext = new ExecutionContext();
registry = new JcrNamespaceRegistry(executionContext.getNamespaceRegistry());
}
+ protected void assertThatNamespaceIsRegistered( String prefix,
+ String uri ) throws Exception {
+ assertThat(registry.getURI(prefix), is(uri));
+ assertThat(registry.getPrefix(uri), is(prefix));
+
+ boolean foundPrefix = false;
+ for (String existingPrefix : registry.getPrefixes()) {
+ if (existingPrefix.equals(prefix)) foundPrefix = true;
+ }
+ assertThat(foundPrefix, is(true));
+
+ boolean foundUri = false;
+ for (String existingUri : registry.getURIs()) {
+ if (existingUri.equals(uri)) foundUri = true;
+ }
+ assertThat(foundUri, is(true));
+ }
+
+ protected void assertThatNamespacePrefixIsNotRegistered( String prefix ) throws
Exception {
+ try {
+ registry.getURI(prefix);
+ fail("Should not have found namespace mapping with prefix \""
+ prefix + "\"");
+ } catch (NamespaceException e) {
+ // good
+ }
+ for (String existingPrefix : registry.getPrefixes()) {
+ assertThat(existingPrefix, is(not(prefix)));
+ }
+ }
+
+ protected void assertThatNamespaceUriIsNotRegistered( String uri ) throws Exception
{
+ try {
+ registry.getPrefix(uri);
+ fail("Should not have found namespace mapping with URI \"" +
uri + "\"");
+ } catch (NamespaceException e) {
+ // good
+ }
+ for (String existingUri : registry.getURIs()) {
+ assertThat(existingUri, is(not(uri)));
+ }
+ }
+
@Test
- public void shouldProvidePrefixes() {
- String[] prefixes = registry.getPrefixes();
- assertThat(prefixes, notNullValue());
- assertThat(prefixes, hasItemInArray(""));
- assertThat(prefixes, hasItemInArray("dna"));
- assertThat(prefixes, hasItemInArray("jcr"));
- assertThat(prefixes, hasItemInArray("mix"));
- assertThat(prefixes, hasItemInArray("nt"));
- // assertThat(prefixes, hasItemInArray("xml"));
+ public void shouldBeInitializedWithNamespacesDefinedByTheJcrSpecification() throws
Exception {
+ // Don't use the constants, since this needs to check that the actual values
are correct
+ assertThatNamespaceIsRegistered("jcr",
"http://www.jcp.org/jcr/1.0");
+ assertThatNamespaceIsRegistered("nt",
"http://www.jcp.org/jcr/nt/1.0");
+ assertThatNamespaceIsRegistered("mix",
"http://www.jcp.org/jcr/mix/1.0");
+ assertThatNamespaceIsRegistered("xml",
"http://www.w3.org/XML/1998/namespace");
+ assertThatNamespaceIsRegistered("", "");
}
@Test
- public void shouldProvideUris() {
- String[] uris = registry.getURIs();
- assertThat(uris, notNullValue());
- 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"));
+ public void shouldBeInitializedWithNamespacesDefinedByTheJcrApiJavaDoc() throws
Exception {
+ // Don't use the constants, since this needs to check that the actual values
are correct
+ assertThatNamespaceIsRegistered("sv",
"http://www.jcp.org/jcr/sv/1.0");
+ assertThatNamespaceIsRegistered("xmlns",
"http://www.w3.org/2000/xmlns/");
}
- @Test( expected = UnsupportedRepositoryOperationException.class )
- public void shouldNotAllowRegisterNamespace() throws Exception {
- registry.registerNamespace(null, null);
+ @Test
+ public void shouldBeInitializedWithNamespacesSpecificToDna() throws Exception {
+ // Don't use the constants, since this needs to check that the actual values
are correct
+ assertThatNamespaceIsRegistered("dna",
"http://www.jboss.org/dna/1.0");
}
- @Test( expected = UnsupportedRepositoryOperationException.class )
- public void shouldNotAllowUnregisterNamespace() throws Exception {
- registry.unregisterNamespace(null);
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowRegisteringNullPrefix() throws Exception {
+ registry.registerNamespace("foo", null);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNullPrefix() throws Exception {
- registry.getURI(null);
+ public void shouldNotAllowRegisteringNullUri() throws Exception {
+ registry.registerNamespace(null, "http://example.com");
}
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringPrefixThatStartsWithLowercaseXml() throws
Exception {
+ registry.registerNamespace("xmlw", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringPrefixThatStartsWithUppercaseXml() throws
Exception {
+ registry.registerNamespace("XMLw", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringPrefixThatStartsWithMixedcaseXml() throws
Exception {
+ registry.registerNamespace("XmLw", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringEmptyPrefix() throws Exception {
+ registry.registerNamespace("",
"http://www.jcp.org/jcr/1.0");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringEmptyUri() throws Exception {
+ registry.registerNamespace("foo", "");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingJcrPrefix() throws Exception {
+ registry.registerNamespace("jcr", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingNtPrefix() throws Exception {
+ registry.registerNamespace("nt", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingMixPrefix() throws Exception {
+ registry.registerNamespace("mix", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingSvPrefix() throws Exception {
+ registry.registerNamespace("sv", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingXmlPrefix() throws Exception {
+ registry.registerNamespace("xml", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingDnaPrefix() throws Exception {
+ registry.registerNamespace("dna", "http://example.com");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingJcrUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.jcp.org/jcr/1.0");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingNtUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.jcp.org/jcr/nt/1.0");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingMixUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.jcp.org/jcr/mix/1.0");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingSvUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.jcp.org/jcr/sv/1.0");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingXmlUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.w3.org/XML/1998/namespace");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingXmlnsUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.w3.org/2000/xmlns/");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringUsingDnaUri() throws Exception {
+ registry.registerNamespace("foo",
"http://www.jboss.org/dna/1.0");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowRegisteringPrefixThatIsNotValidXmlNCName() throws Exception
{
+ registry.registerNamespace("1foot&in<door",
"http://example.com");
+ }
+
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNullUri() throws Exception {
- registry.getPrefix(null);
+ public void shouldNotAllowUnregisteringNullPrefix() throws Exception {
+ registry.unregisterNamespace(null);
}
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringBlankPrefix() throws Exception {
+ registry.unregisterNamespace("");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringJcrPrefix() throws Exception {
+ registry.unregisterNamespace("jcr");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringNtPrefix() throws Exception {
+ registry.unregisterNamespace("nt");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringMixPrefix() throws Exception {
+ registry.unregisterNamespace("mix");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringSvPrefix() throws Exception {
+ registry.unregisterNamespace("sv");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringXmlPrefix() throws Exception {
+ registry.unregisterNamespace("xml");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringDnaPrefix() throws Exception {
+ registry.unregisterNamespace("dna");
+ }
+
+ @Test( expected = NamespaceException.class )
+ public void shouldNotAllowUnregisteringPrefixThatIsNotUsed() throws Exception {
+ String prefix = "bar";
+ assertThatNamespacePrefixIsNotRegistered(prefix);
+ registry.unregisterNamespace(prefix);
+ }
+
@Test
- public void shouldProvideUriForRegisteredPrefix() throws Exception {
- assertThat(registry.getPrefix(""), is(""));
-
assertThat(registry.getPrefix("http://www.jboss.org/dna/1.0"),
is("dna"));
-
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"));
+ public void shouldRegisterNewPrefixWithNewUri() throws Exception {
+ String prefix = "foo";
+ String uri = "http://example.com";
+ assertThatNamespacePrefixIsNotRegistered(prefix);
+ assertThatNamespaceUriIsNotRegistered(uri);
+ registry.registerNamespace(prefix, uri);
+ assertThatNamespaceIsRegistered(prefix, uri);
}
@Test
- public void shouldProvidePrefixForRegisteredUri() throws Exception {
- assertThat(registry.getURI(""), is(""));
- assertThat(registry.getURI("dna"),
is("http://www.jboss.org/dna/1.0"));
- 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"));
+ public void
shouldRegisterRemoveExistingMappingWhenUsingNewPrefixWithPreviouslyUsedUri() throws
Exception {
+ String prefix1 = "foo1";
+ String prefix2 = "foo2";
+ String uri = "http://example.com";
+ assertThatNamespacePrefixIsNotRegistered(prefix1);
+ assertThatNamespacePrefixIsNotRegistered(prefix2);
+ assertThatNamespaceUriIsNotRegistered(uri);
+ // Register the URI with the first prefix.
+ registry.registerNamespace(prefix1, uri);
+ assertThatNamespaceIsRegistered(prefix1, uri);
+ // Register the same URI with a different prefix. This should remove the mapping
with 'prefix1'
+ registry.registerNamespace(prefix2, uri);
+ assertThatNamespaceIsRegistered(prefix2, uri);
+ assertThatNamespacePrefixIsNotRegistered(prefix1);
}
+ @Test
+ public void
shouldRegisterOverwriteExistingMappingWhenUsingPreviouslyUsedPrefixWithNewUri() throws
Exception {
+ String prefix = "foo1";
+ String uri1 = "http://example.com";
+ String uri2 = "http://acme.com";
+ assertThatNamespacePrefixIsNotRegistered(prefix);
+ assertThatNamespaceUriIsNotRegistered(uri1);
+ assertThatNamespaceUriIsNotRegistered(uri2);
+ // Register the first URI with the prefix.
+ registry.registerNamespace(prefix, uri1);
+ assertThatNamespaceIsRegistered(prefix, uri1);
+ // Register the second URI with the same prefix. 'uri1' should no longer
be used
+ registry.registerNamespace(prefix, uri2);
+ assertThatNamespaceIsRegistered(prefix, uri2);
+ assertThatNamespaceUriIsNotRegistered(uri1);
+ }
+
@Test( expected = NamespaceException.class )
public void shouldNotAllowUnregisteredPrefix() throws Exception {
registry.getURI("bogus");
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 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -27,7 +27,6 @@
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.stub;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.util.HashMap;
@@ -38,8 +37,11 @@
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import org.jboss.dna.graph.ExecutionContext;
+import org.jboss.dna.graph.Graph;
import org.jboss.dna.graph.connector.RepositoryConnection;
import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
+import org.jboss.dna.graph.connector.RepositorySourceException;
+import org.jboss.dna.graph.connector.inmemory.InMemoryRepositorySource;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -51,18 +53,15 @@
*/
public class JcrRepositoryTest {
- private Repository repository;
- @Mock
+ private String sourceName;
+ private ExecutionContext context;
+ private JcrRepository repository;
+ private InMemoryRepositorySource source;
private Map<String, String> descriptors;
- @Mock
private RepositoryConnectionFactory connectionFactory;
+ protected AccessControlContext accessControlContext = AccessController.getContext();
@Mock
- private ExecutionContext executionContext;
- @Mock
LoginContext loginContext;
- @Mock
- private RepositoryConnection connection;
- AccessControlContext accessControlContext = AccessController.getContext();
private Credentials credentials = new Credentials() {
private static final long serialVersionUID = 1L;
@@ -76,27 +75,58 @@
@Before
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
- stub(executionContext.create(accessControlContext)).toReturn(executionContext);
-
stub(connectionFactory.createConnection(JcrI18n.defaultWorkspaceName.text())).toReturn(connection);
- repository = new JcrRepository(descriptors, executionContext,
connectionFactory);
+ sourceName = "repository";
+
+ // Set up the source ...
+ source = new InMemoryRepositorySource();
+ source.setName(sourceName);
+
+ // Set up the execution context ...
+ context = new ExecutionContext();
+
+ // Stub out the connection factory ...
+ connectionFactory = new RepositoryConnectionFactory() {
+ /**
+ * {@inheritDoc}
+ *
+ * @see
org.jboss.dna.graph.connector.RepositoryConnectionFactory#createConnection(java.lang.String)
+ */
+ @SuppressWarnings( "synthetic-access" )
+ public RepositoryConnection createConnection( String sourceName ) throws
RepositorySourceException {
+ return sourceName.equals(sourceName) ? source.getConnection() : null;
+ }
+ };
+
+ // Make sure the path to the namespaces exists ...
+ Graph graph = Graph.create(source, context);
+
graph.create("/jcr:system").and().create("/jcr:system/dna:namespaces");
+
+ // Set up the repository ...
+ descriptors = new HashMap<String, String>();
+ repository = new JcrRepository(descriptors, context, connectionFactory,
sourceName);
}
@Test
- public void shouldAllowNoDescriptors() {
- new JcrRepository(descriptors, executionContext, connectionFactory);
+ public void shouldAllowNullDescriptors() {
+ new JcrRepository(null, context, connectionFactory, sourceName);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNoExecutionContextFactory() throws Exception {
- new JcrRepository(null, connectionFactory);
+ public void shouldNotAllowNullExecutionContext() throws Exception {
+ new JcrRepository(descriptors, null, connectionFactory, sourceName);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNoConnectionFactories() throws Exception {
- new JcrRepository(executionContext, null);
+ public void shouldNotAllowNullConnectionFactories() throws Exception {
+ new JcrRepository(descriptors, context, null, sourceName);
}
@Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNullSourceName() throws Exception {
+ new JcrRepository(descriptors, context, connectionFactory, null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
public void shouldNotAllowNoDescriptorKey() {
repository.getDescriptor(null);
}
@@ -118,7 +148,7 @@
@Test
public void shouldProvideBuiltInDescriptorsWhenNotSuppliedDescriptors() {
- Repository repository = new JcrRepository(descriptors, executionContext,
connectionFactory);
+ Repository repository = new JcrRepository(descriptors, context,
connectionFactory, sourceName);
testDescriptorKeys(repository);
testDescriptorValues(repository);
}
@@ -127,7 +157,7 @@
public void shouldProvideUserSuppliedDescriptors() {
Map<String, String> descriptors = new HashMap<String, String>();
descriptors.put("property", "value");
- Repository repository = new JcrRepository(descriptors, executionContext,
connectionFactory);
+ Repository repository = new JcrRepository(descriptors, context,
connectionFactory, sourceName);
testDescriptorKeys(repository);
testDescriptorValues(repository);
assertThat(repository.getDescriptor("property"),
is("value"));
@@ -148,7 +178,6 @@
@Test
public void shouldAllowLoginWithProperCredentials() throws Exception {
repository.login(credentials);
- stub(executionContext.create(loginContext)).toReturn(executionContext);
repository.login(new Credentials() {
private static final long serialVersionUID = 1L;
@@ -235,7 +264,7 @@
assertThat(repository.getDescriptor(Repository.REP_NAME_DESC),
is(JcrI18n.REP_NAME_DESC.text()));
assertThat(repository.getDescriptor(Repository.REP_VENDOR_DESC),
is(JcrI18n.REP_VENDOR_DESC.text()));
assertThat(repository.getDescriptor(Repository.REP_VENDOR_URL_DESC),
is("http://www.jboss.org/dna"));
- assertThat(repository.getDescriptor(Repository.REP_VERSION_DESC),
is("0.2"));
+ assertThat(repository.getDescriptor(Repository.REP_VERSION_DESC),
is("0.4"));
assertThat(repository.getDescriptor(Repository.SPEC_NAME_DESC),
is(JcrI18n.SPEC_NAME_DESC.text()));
assertThat(repository.getDescriptor(Repository.SPEC_VERSION_DESC),
is("1.0"));
}
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 2009-02-24 14:40:05
UTC (rev 737)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2009-02-27 22:21:50
UTC (rev 738)
@@ -29,12 +29,15 @@
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.stub;
import java.io.InputStream;
import java.security.AccessControlException;
import java.security.Principal;
import java.util.Calendar;
import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
import java.util.UUID;
import javax.jcr.Item;
import javax.jcr.NamespaceException;
@@ -48,57 +51,82 @@
import javax.security.auth.login.LoginContext;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Graph;
+import org.jboss.dna.graph.connector.RepositoryConnection;
import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
+import org.jboss.dna.graph.connector.RepositorySourceException;
import org.jboss.dna.graph.connector.inmemory.InMemoryRepositorySource;
import org.junit.After;
-import org.junit.AfterClass;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
-import com.google.common.base.ReferenceType;
-import com.google.common.collect.ReferenceMap;
+import org.mockito.MockitoAnnotations.Mock;
/**
* @author jverhaeg
*/
public class JcrSessionTest {
- static final String REPOSITORY_NAME = "Test repository";
- static final String WORKSPACE_NAME = JcrI18n.defaultWorkspaceName.text();
+ private String workspaceName;
+ private ExecutionContext context;
+ private InMemoryRepositorySource source;
+ private JcrWorkspace workspace;
+ private JcrSession session;
+ private Graph graph;
+ private RepositoryConnectionFactory connectionFactory;
+ private Map<String, Object> sessionAttributes;
+ @Mock
+ private JcrRepository repository;
- static ExecutionContext executionContext;
- static InMemoryRepositorySource repositorySource;
- static Graph graph;
- static RepositoryConnectionFactory connectionFactory;
- static Repository repository;
+ @Before
+ public void beforeEach() throws Exception {
+ workspaceName = "workspace1";
+ final String repositorySourceName = "repository";
- @BeforeClass
- public static void beforeClass() throws Exception {
- executionContext = TestUtil.getExecutionContext();
- repositorySource = new InMemoryRepositorySource();
- repositorySource.setName(REPOSITORY_NAME);
- graph = Graph.create(repositorySource, executionContext);
+ // Set up the source ...
+ source = new InMemoryRepositorySource();
+ source.setName(workspaceName);
+ source.setDefaultWorkspaceName(workspaceName);
+
+ // Set up the execution context ...
+ context = new ExecutionContext();
+
+ // Set up the initial content ...
+ graph = Graph.create(source, context);
graph.create("/a").and().create("/a/b").and().create("/a/b/c");
graph.set("booleanProperty").on("/a/b").to(true);
graph.set("stringProperty").on("/a/b/c").to("value");
- connectionFactory = TestUtil.createJackRabbitConnectionFactory(repositorySource,
executionContext);
- repository = new JcrRepository(executionContext, connectionFactory);
- }
- @AfterClass
- public static void afterClass() {
- }
+ // Make sure the path to the namespaces exists ...
+
graph.create("/jcr:system").and().create("/jcr:system/dna:namespaces");
- private Session session;
- private ReferenceMap<UUID, Node> nodesByUuid;
+ // Stub out the connection factory ...
+ connectionFactory = new RepositoryConnectionFactory() {
+ /**
+ * {@inheritDoc}
+ *
+ * @see
org.jboss.dna.graph.connector.RepositoryConnectionFactory#createConnection(java.lang.String)
+ */
+ @SuppressWarnings( "synthetic-access" )
+ public RepositoryConnection createConnection( String sourceName ) throws
RepositorySourceException {
+ return repositorySourceName.equals(sourceName) ? source.getConnection() :
null;
+ }
+ };
- @Before
- public void before() throws Exception {
+ // Stub out the repository, since we only need a few methods ...
MockitoAnnotations.initMocks(this);
- nodesByUuid = new ReferenceMap<UUID, Node>(ReferenceType.STRONG,
ReferenceType.SOFT);
- session = repository.login();
+ stub(repository.getRepositorySourceName()).toReturn(repositorySourceName);
+ stub(repository.getConnectionFactory()).toReturn(connectionFactory);
+
+ // Set up the session attributes ...
+ sessionAttributes = new HashMap<String, Object>();
+ sessionAttributes.put("attribute1", "value1");
+
+ // Now create the workspace ...
+ workspace = new JcrWorkspace(repository, workspaceName, context,
sessionAttributes);
+
+ // Create the session and log in ...
+ session = (JcrSession)workspace.getSession();
}
@After
@@ -109,26 +137,23 @@
}
@Test( expected = AssertionError.class )
- public void shouldNotAllowNoRepository() throws Exception {
- Graph graph = Graph.create(WORKSPACE_NAME, connectionFactory, executionContext);
- new JcrSession(null, WORKSPACE_NAME, graph, nodesByUuid);
+ public void shouldNotAllowNullRepository() throws Exception {
+ new JcrSession(null, workspace, context, sessionAttributes);
}
@Test( expected = AssertionError.class )
- public void shouldNotAllowNoWorkspaceName() throws Exception {
- Graph graph = Graph.create(WORKSPACE_NAME, connectionFactory, executionContext);
- new JcrSession(repository, null, graph, nodesByUuid);
+ public void shouldNotAllowNullWorkspace() throws Exception {
+ new JcrSession(repository, null, context, sessionAttributes);
}
@Test( expected = AssertionError.class )
- public void shouldNotAllowNoGraph() throws Exception {
- new JcrSession(repository, WORKSPACE_NAME, null, nodesByUuid);
+ public void shouldNotAllowNullExecutionContext() throws Exception {
+ new JcrSession(repository, workspace, null, sessionAttributes);
}
@Test( expected = AssertionError.class )
- public void shouldNotAllowNoUuid2NodeMap() throws Exception {
- Graph graph = Graph.create(WORKSPACE_NAME, connectionFactory, executionContext);
- new JcrSession(repository, WORKSPACE_NAME, graph, null);
+ public void shouldNotAllowNullSessionAttributesMap() throws Exception {
+ new JcrSession(repository, workspace, context, null);
}
@Test( expected = UnsupportedOperationException.class )
@@ -167,12 +192,46 @@
}
@Test
- public void shouldProvideNoAttributes() throws Exception {
+ public void shouldReturnNullValueForNullAttributeName() throws Exception {
assertThat(session.getAttribute(null), nullValue());
}
@Test
+ public void shouldReturnNullValueForEmptyOrBlankAttributeName() throws Exception {
+ assertThat(session.getAttribute(""), nullValue());
+ assertThat(session.getAttribute(" "), nullValue());
+ }
+
+ @Test
+ public void shouldReturnNullValueForNonExistantAttributeName() throws Exception {
+ assertThat(session.getAttribute("something else entirely"),
nullValue());
+ }
+
+ @Test
+ public void shouldReturnPropertyAttributeValueGivenNameOfExistingAttribute() throws
Exception {
+ assertThat(session.getAttribute("attribute1"),
is((Object)"value1"));
+ }
+
+ @Test
+ public void shouldProvideAttributeNames() throws Exception {
+ String[] names = session.getAttributeNames();
+ assertThat(names, notNullValue());
+ assertThat(names.length, is(1));
+ assertThat(names[0], is("attribute1"));
+ }
+
+ @Test
public void shouldProvideEmptyAttributeNames() throws Exception {
+ // Set up the session attributes ...
+ sessionAttributes = new HashMap<String, Object>();
+
+ // Now create the workspace ...
+ workspace = new JcrWorkspace(repository, workspaceName, context,
sessionAttributes);
+
+ // Create the session and log in ...
+ session = (JcrSession)workspace.getSession();
+
+ // Get get the attribute names (there should be none) ...
String[] names = session.getAttributeNames();
assertThat(names, notNullValue());
assertThat(names.length, is(0));
@@ -180,7 +239,7 @@
@Test
public void shouldProvideAccessToRepository() throws Exception {
- assertThat(session.getRepository(), is(repository));
+ assertThat(session.getRepository(), is((Repository)repository));
}
@Test
@@ -210,12 +269,9 @@
Principal principal = Mockito.mock(Principal.class);
stub(principal.getName()).toReturn("name");
Subject subject = new Subject(false, Collections.singleton(principal),
Collections.EMPTY_SET, Collections.EMPTY_SET);
- ExecutionContext executionContext = Mockito.mock(ExecutionContext.class);
- stub(executionContext.getSubject()).toReturn(subject);
-
stub(executionContext.getLoginContext()).toReturn(Mockito.mock(LoginContext.class));
- Graph graph = Mockito.mock(Graph.class);
- stub(graph.getContext()).toReturn(executionContext);
- Session session = new JcrSession(repository, WORKSPACE_NAME, graph,
nodesByUuid);
+ LoginContext loginContext = mock(LoginContext.class);
+ stub(loginContext.getSubject()).toReturn(subject);
+ Session session = new JcrSession(repository, workspace,
context.create(loginContext), sessionAttributes);
try {
assertThat(session.getUserID(), is("name"));
} finally {
@@ -225,9 +281,7 @@
@Test
public void shouldProvideRootNode() throws Exception {
- ReferenceMap<UUID, Node> nodesByUuid = new ReferenceMap<UUID,
Node>(ReferenceType.STRONG, ReferenceType.SOFT);
- Graph graph = Graph.create(WORKSPACE_NAME, connectionFactory, executionContext);
- Session session = new JcrSession(repository, WORKSPACE_NAME, graph,
nodesByUuid);
+ Map<UUID, Node> nodesByUuid = session.getNodesByUuid();
assertThat(nodesByUuid.isEmpty(), is(true));
Node root = session.getRootNode();
assertThat(root, notNullValue());
@@ -267,7 +321,7 @@
assertThat(session.hasPendingChanges(), is(false));
}
- @Test
+ @Test( expected = UnsupportedOperationException.class )
public void shouldAllowImpersonation() throws Exception {
assertThat(session.impersonate(null), notNullValue());
}
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java 2009-02-24
14:40:05 UTC (rev 737)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrWorkspaceTest.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -26,61 +26,79 @@
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 static org.mockito.Mockito.stub;
+import java.util.HashMap;
+import java.util.Map;
+import javax.jcr.NamespaceRegistry;
+import org.jboss.dna.graph.ExecutionContext;
+import org.jboss.dna.graph.Graph;
+import org.jboss.dna.graph.JcrLexicon;
+import org.jboss.dna.graph.connector.RepositoryConnection;
+import org.jboss.dna.graph.connector.RepositoryConnectionFactory;
+import org.jboss.dna.graph.connector.RepositorySourceException;
import org.jboss.dna.graph.connector.inmemory.InMemoryRepositorySource;
-import org.junit.After;
-import org.junit.AfterClass;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoAnnotations.Mock;
/**
* @author jverhaeg
*/
public class JcrWorkspaceTest {
- @BeforeClass
- public static void beforeClass() throws Exception {
- JcrSessionTest.executionContext = TestUtil.getExecutionContext();
- InMemoryRepositorySource source = new InMemoryRepositorySource();
- source.setName(JcrSessionTest.REPOSITORY_NAME);
- JcrSessionTest.repositorySource = source;
- JcrSessionTest.connectionFactory =
TestUtil.createJackRabbitConnectionFactory(JcrSessionTest.repositorySource,
-
JcrSessionTest.executionContext);
- JcrSessionTest.repository = new JcrRepository(JcrSessionTest.executionContext,
JcrSessionTest.connectionFactory);
- }
+ private String workspaceName;
+ private ExecutionContext context;
+ private InMemoryRepositorySource source;
+ private JcrWorkspace workspace;
+ private RepositoryConnectionFactory connectionFactory;
+ private Map<String, Object> sessionAttributes;
+ @Mock
+ private JcrRepository repository;
- @AfterClass
- public static void afterClass() {
- }
+ @Before
+ public void beforeEach() throws Exception {
+ final String repositorySourceName = "repository";
+ workspaceName = "workspace1";
- private Session session;
- private Workspace workspace;
+ // Set up the source ...
+ source = new InMemoryRepositorySource();
+ source.setName(repositorySourceName);
+ source.setDefaultWorkspaceName(workspaceName);
- @Before
- public void before() throws Exception {
- MockitoAnnotations.initMocks(this);
- session = JcrSessionTest.repository.login();
- workspace = session.getWorkspace();
- }
+ // Set up the execution context ...
+ context = new ExecutionContext();
- @After
- public void after() throws Exception {
- if (session.isLive()) {
- session.logout();
- }
- }
+ // Set up the initial content ...
+ Graph graph = Graph.create(source, context);
+
graph.create("/a").and().create("/a/b").and().create("/a/b/c").and().create("/b");
+ graph.set("booleanProperty").on("/a/b").to(true);
+
graph.set("stringProperty").on("/a/b/c").to("value");
- @Test( expected = AssertionError.class )
- public void shouldNotAllowNoSession() throws Exception {
- new JcrWorkspace(null, JcrSessionTest.WORKSPACE_NAME);
- }
+ // Make sure the path to the namespaces exists ...
+
graph.create("/jcr:system").and().create("/jcr:system/dna:namespaces");
- @Test( expected = AssertionError.class )
- public void shouldNotAllowNoWorkspaceName() throws Exception {
- new JcrWorkspace((JcrSession)session, null);
+ // Stub out the connection factory ...
+ connectionFactory = new RepositoryConnectionFactory() {
+ /**
+ * {@inheritDoc}
+ *
+ * @see
org.jboss.dna.graph.connector.RepositoryConnectionFactory#createConnection(java.lang.String)
+ */
+ @SuppressWarnings( "synthetic-access" )
+ public RepositoryConnection createConnection( String sourceName ) throws
RepositorySourceException {
+ return repositorySourceName.equals(sourceName) ? source.getConnection() :
null;
+ }
+ };
+
+ // Stub out the repository, since we only need a few methods ...
+ MockitoAnnotations.initMocks(this);
+ stub(repository.getRepositorySourceName()).toReturn(repositorySourceName);
+ stub(repository.getConnectionFactory()).toReturn(connectionFactory);
+
+ // Now create the workspace ...
+ sessionAttributes = new HashMap<String, Object>();
+ workspace = new JcrWorkspace(repository, workspaceName, context,
sessionAttributes);
}
@Test( expected = UnsupportedOperationException.class )
@@ -88,34 +106,48 @@
workspace.clone(null, null, null, false);
}
- @Test( expected = UnsupportedOperationException.class )
- public void shouldNotAllowCopy() throws Exception {
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCopyFromNullPathToNullPath() throws Exception {
workspace.copy(null, null);
}
+ @Test
+ public void shouldCopyFromPathToAnotherPathInSameWorkspace() throws Exception {
+ workspace.copy("/a/b", "/b/b-copy");
+ }
+
@Test( expected = UnsupportedOperationException.class )
public void shouldNotAllowCopyFromOtherWorkspace() throws Exception {
workspace.copy(null, null, null);
}
- @Test( expected = UnsupportedOperationException.class )
+ @Test
public void shouldNotAllowGetAccessibleWorkspaceNames() throws Exception {
- workspace.getAccessibleWorkspaceNames();
+ String[] names = workspace.getAccessibleWorkspaceNames();
+ assertThat(names.length, is(1));
+ assertThat(names[0], is(workspaceName));
}
- @Test( expected = UnsupportedOperationException.class )
- public void shouldNotAllowImportContentHandler() throws Exception {
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowImportContentHandlerWithNullPath() throws Exception {
workspace.getImportContentHandler(null, 0);
}
@Test
+ public void shouldGetImportContentHandlerWithValidPath() throws Exception {
+ assertThat(workspace.getImportContentHandler("/b", 0),
is(notNullValue()));
+ }
+
+ @Test
public void shouldProvideName() throws Exception {
- assertThat(workspace.getName(), is(JcrSessionTest.WORKSPACE_NAME));
+ assertThat(workspace.getName(), is(workspaceName));
}
@Test
public void shouldProvideNamespaceRegistry() throws Exception {
- assertThat(workspace.getNamespaceRegistry(), notNullValue());
+ NamespaceRegistry registry = workspace.getNamespaceRegistry();
+ assertThat(registry, is(notNullValue()));
+ assertThat(registry.getURI(JcrLexicon.Namespace.PREFIX),
is(JcrLexicon.Namespace.URI));
}
@Test( expected = UnsupportedOperationException.class )
@@ -135,7 +167,7 @@
@Test
public void shouldProvideSession() throws Exception {
- assertThat(workspace.getSession(), is(session));
+ assertThat(workspace.getSession(), is(notNullValue()));
}
@Test( expected = UnsupportedOperationException.class )
@@ -143,12 +175,17 @@
workspace.importXML(null, null, 0);
}
- @Test( expected = UnsupportedOperationException.class )
- public void shouldNotAllowMove() throws Exception {
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowMoveFromNullPath() throws Exception {
workspace.move(null, null);
}
@Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowMoveFromPathToAnotherPathInSameWorkspace() throws Exception
{
+ workspace.move("/a/b", "/b/b-copy");
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
public void shouldNotAllowRestore() throws Exception {
workspace.restore(null, false);
}
Added: trunk/dna-jcr/src/test/resources/cars.xml
===================================================================
--- trunk/dna-jcr/src/test/resources/cars.xml (rev 0)
+++ trunk/dna-jcr/src/test/resources/cars.xml 2009-02-27 22:21:50 UTC (rev 738)
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss DNA (
http://www.jboss.org/dna)
+ ~
+ ~ See the COPYRIGHT.txt file distributed with this work for information
+ ~ regarding copyright ownership. Some portions may be licensed
+ ~ to Red Hat, Inc. under one or more contributor license agreements.
+ ~ See the AUTHORS.txt file in the distribution for a full listing of
+ ~ individual contributors.
+ ~
+ ~ JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
+ ~ is licensed to you 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.
+ ~
+ ~ JBoss DNA 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/dna-jcr/src/test/resources/cars.xml
___________________________________________________________________
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 2009-02-24
14:40:05 UTC (rev 737)
+++
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java 2009-02-27
22:21:50 UTC (rev 738)
@@ -245,7 +245,7 @@
LoginContext loginContext = getLoginContext(); // will ask user to authenticate
if needed
switch (api) {
case JCR: {
- JcrRepository jcrRepository = new JcrRepository(context, sources);
+ JcrRepository jcrRepository = new JcrRepository(context, sources,
sourceName);
Session session = null;
if (loginContext != null) {
Credentials credentials = new JaasCredentials(loginContext);