DNA SVN: r620 - trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-11 23:35:25 -0500 (Tue, 11 Nov 2008)
New Revision: 620
Modified:
trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java
Log:
DNA-231 - org.jboss.dna.graph.xml.XmlSequencerTest failed with jdk 1.6 (not with jdk 1.5)
http://jira.jboss.com/jira/browse/DNA-231
Apparently the SAX parser in Java 1.6.0_07 (build 1.6.0_07-b06-153) on OS-X 10.5.5 does not call the handler methods in the proper order for entity references. For example, in 1.5 (and in 1.6 on Fedora), this will result in calls to 'startEntity(...)', 'characters(...)', and 'endEntity(...)'. Java 1.6.0_07 on OS-X results in 'startEntity(...)', 'endEntity(...)', and , 'characters(...)' where the 'characters' method is called with character content representing the replaced entity reference PLUS the next characters that would normally be supplied in the subsequent call to 'characters'.
This was addressed by changing how the flag used by these methods to record which entity reference is being processed, and by recording the replacement value when the entity declaration is processed (so that we can separate the entity replacement value from the 'extra' characters).
New test cases were added to properly verify this behavior, and to ensure that the changes work correctly. Tests were run in both Java 1.5 and 1.6 on both OS-X and on Fedora.
Modified: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java 2008-11-12 04:31:14 UTC (rev 619)
+++ trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java 2008-11-12 04:35:25 UTC (rev 620)
@@ -126,6 +126,7 @@
private StringBuilder cDataContent;
private StringBuilder contentBuilder;
private final Problems problems;
+ private final Map<String, String> entityValues = new HashMap<String, String>();
/**
* @param output
@@ -136,11 +137,11 @@
* @param scoping
*/
XmlSequencerHandler( SequencerOutput output,
- SequencerContext context,
- Name nameAttribute,
- Name defaultPrimaryType,
- TextDecoder textDecoder,
- XmlSequencer.AttributeScoping scoping ) {
+ SequencerContext context,
+ Name nameAttribute,
+ Name defaultPrimaryType,
+ TextDecoder textDecoder,
+ XmlSequencer.AttributeScoping scoping ) {
CheckArg.isNotNull(output, "output");
CheckArg.isNotNull(context, "context");
@@ -283,6 +284,8 @@
output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaDtdLexicon.ENTITY);
output.setProperty(currentPath, DnaDtdLexicon.NAME, name);
output.setProperty(currentPath, DnaDtdLexicon.VALUE, value);
+ // Record the name/value pair ...
+ entityValues.put(name, value);
endNode();
}
@@ -459,6 +462,18 @@
// into this method), we want to keep the entity reference ...
contentBuilder.append('&').append(currentEntityName).append(';');
+ // Normally, 'characters' is called with just the entity replacement characters,
+ // and is called between 'startEntity' and 'endEntity'. However, per DNA-231, some JVMs
+ // use an incorrect ordering: 'startEntity', 'endEntity' and then 'characters', and the
+ // content passed to the 'characters' call not only includes the entity replacement characters
+ // followed by other content. Look for this condition ...
+ String entityValue = entityValues.get(currentEntityName);
+ if (!content.equals(entityValue) && entityValue != null && entityValue.length() < content.length()) {
+ // Per DNA-231, there's extra content after the entity value. So replace the entity value in the
+ // content with the entity reference (not the replacement characters), and add the extra content ...
+ String extraContent = content.substring(entityValue.length());
+ contentBuilder.append(extraContent);
+ }
// We're done reading the entity characters, so null it out
currentEntityName = null;
} else {
17 years, 2 months
DNA SVN: r619 - in trunk: dna-graph/src/main/java/org/jboss/dna/graph/properties/basic and 6 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-11 23:31:14 -0500 (Tue, 11 Nov 2008)
New Revision: 619
Added:
trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencer.java
trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java
trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencerTest.java
trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerHandlerTest.java
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithCDATA.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithComments.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithDtdEntities.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespaces.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespacesWithoutDefault.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNestedNamespaces.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithOnlyRootElement.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithProcessingInstructions.xml
trunk/extensions/dna-sequencer-xml/src/test/resources/docWithoutNamespaces.xml
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/GraphImporter.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicPath.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/PathValueFactory.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/xml/XmlHandler.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerOutput.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/xml/XmlHandlerTest.java
trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java
trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java
Log:
DNA-223 - XML sequencer does not properly handle namespaces of unqualified attributes
http://jira.jboss.com/jira/browse/DNA-223
It is not really possible to correctly handle unqualified attributes in a general manner if we consider the XML Schema specification. This is because an XML schema by default will require that unqualified attributes inherit the element's namespace, and because within any single XML schema it is possible to define one element that requires unqualified attributes inherit the element's namespace while other element definitions require that unqualified attributes use the default namespace. In other words, a general-purpose sequencer cannot always do the "correct" thing without thoroughly understanding the XML Schema(s) used by an XML document.
Therefore, this has been addressed by changing the XML sequencer to be configurable as to the desired behavior. Note that this behavior is fixed for a particular document, and still won't properly handle an XML document that uses a schema with a mixture of qualified and unqualified attribute forms. The default is to use the default namespace (at that position in the document), which is really the default for XML documents. To make it easy to specify a sequencer by classname that inherits the element's namespace for unqualified attributes, there is also a new InheritingXmlSequencer, which extends XmlSequencer and simply overrides the default setting.
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 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/GraphImporter.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -156,8 +156,7 @@
}
public void create( Path path,
- List<Property> properties,
- Name elementName ) {
+ List<Property> properties ) {
assert properties != null;
if (properties.isEmpty()) {
batch.create(path).and();
@@ -166,6 +165,16 @@
}
}
+ public void create( Path path,
+ Property firstProperty,
+ Property... additionalProperties ) {
+ if (firstProperty == null) {
+ batch.create(path).and();
+ } else {
+ batch.create(path, firstProperty, additionalProperties);
+ }
+ }
+
public void submit() {
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicPath.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicPath.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicPath.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -53,6 +53,8 @@
public static final Path ROOT = new BasicPath(EMPTY_SEGMENTS, true);
+ public static final Path EMPTY_RELATIVE = new BasicPath(EMPTY_SEGMENTS, false);
+
public static final Path SELF_PATH = new BasicPath(Collections.singletonList(Path.SELF_SEGMENT), false);
private final List<Segment> segments;
@@ -84,7 +86,7 @@
*/
public Path getParent() {
if (this.isRoot()) return null;
- if (this.segments.size() == 1) return ROOT;
+ if (this.segments.size() == 1) return this.isAbsolute() ? ROOT : EMPTY_RELATIVE;
return subpath(0, this.segments.size() - 1);
}
@@ -96,6 +98,7 @@
if (degree == 0) return this;
if (this.isRoot()) return null;
int endIndex = this.segments.size() - degree;
+ if (endIndex == 0) return this.isAbsolute() ? ROOT : EMPTY_RELATIVE;
if (endIndex < 0) {
String msg = GraphI18n.pathAncestorDegreeIsInvalid.text(this.getString(), Inflector.getInstance().ordinalize(degree));
throw new InvalidPathException(msg);
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/PathValueFactory.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/PathValueFactory.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/PathValueFactory.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -169,9 +169,10 @@
* {@inheritDoc}
*/
public Path create( int value ) {
- throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Integer.class.getSimpleName(),
- value));
+ throw new ValueFormatException(value, getPropertyType(),
+ GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
+ Integer.class.getSimpleName(),
+ value));
}
/**
@@ -179,17 +180,18 @@
*/
public Path create( long value ) {
throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Long.class.getSimpleName(),
- value));
+ Long.class.getSimpleName(),
+ value));
}
/**
* {@inheritDoc}
*/
public Path create( boolean value ) {
- throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Boolean.class.getSimpleName(),
- value));
+ throw new ValueFormatException(value, getPropertyType(),
+ GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
+ Boolean.class.getSimpleName(),
+ value));
}
/**
@@ -197,8 +199,8 @@
*/
public Path create( float value ) {
throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Float.class.getSimpleName(),
- value));
+ Float.class.getSimpleName(),
+ value));
}
/**
@@ -206,8 +208,8 @@
*/
public Path create( double value ) {
throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Double.class.getSimpleName(),
- value));
+ Double.class.getSimpleName(),
+ value));
}
/**
@@ -216,17 +218,18 @@
public Path create( BigDecimal value ) {
throw new ValueFormatException(value, getPropertyType(),
GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- BigDecimal.class.getSimpleName(),
- value));
+ BigDecimal.class.getSimpleName(),
+ value));
}
/**
* {@inheritDoc}
*/
public Path create( Calendar value ) {
- throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Calendar.class.getSimpleName(),
- value));
+ throw new ValueFormatException(value, getPropertyType(),
+ GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
+ Calendar.class.getSimpleName(),
+ value));
}
/**
@@ -234,8 +237,8 @@
*/
public Path create( Date value ) {
throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Date.class.getSimpleName(),
- value));
+ Date.class.getSimpleName(),
+ value));
}
/**
@@ -244,9 +247,10 @@
* @see org.jboss.dna.graph.properties.ValueFactory#create(org.jboss.dna.graph.properties.DateTime)
*/
public Path create( DateTime value ) throws ValueFormatException {
- throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- DateTime.class.getSimpleName(),
- value));
+ throw new ValueFormatException(value, getPropertyType(),
+ GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
+ DateTime.class.getSimpleName(),
+ value));
}
/**
@@ -325,14 +329,14 @@
* @see org.jboss.dna.graph.properties.PathFactory#createRelativePath()
*/
public Path createRelativePath() {
- return BasicPath.SELF_PATH;
+ return BasicPath.EMPTY_RELATIVE;
}
/**
* {@inheritDoc}
*/
public Path createRelativePath( Name... segmentNames ) {
- if (segmentNames == null || segmentNames.length == 0) return BasicPath.SELF_PATH;
+ if (segmentNames == null || segmentNames.length == 0) return BasicPath.EMPTY_RELATIVE;
List<Segment> segments = new ArrayList<Segment>(segmentNames.length);
for (Name segmentName : segmentNames) {
if (segmentName == null) {
@@ -347,7 +351,7 @@
* {@inheritDoc}
*/
public Path createRelativePath( Segment... segments ) {
- if (segments == null || segments.length == 0) return BasicPath.SELF_PATH;
+ if (segments == null || segments.length == 0) return BasicPath.EMPTY_RELATIVE;
List<Segment> segmentsList = new ArrayList<Segment>(segments.length);
for (Segment segment : segments) {
if (segment == null) {
@@ -371,14 +375,15 @@
}
segmentsList.add(segment);
}
- if (segmentsList.isEmpty()) return BasicPath.SELF_PATH;
+ if (segmentsList.isEmpty()) return BasicPath.EMPTY_RELATIVE;
return new BasicPath(segmentsList, false);
}
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.properties.PathFactory#create(org.jboss.dna.graph.properties.Path, org.jboss.dna.graph.properties.Path)
+ * @see org.jboss.dna.graph.properties.PathFactory#create(org.jboss.dna.graph.properties.Path,
+ * org.jboss.dna.graph.properties.Path)
*/
public Path create( Path parentPath,
Path childPath ) {
@@ -538,7 +543,7 @@
Integer.parseInt(ndx));
} catch (NumberFormatException err) {
throw new ValueFormatException(segmentName, getPropertyType(), GraphI18n.invalidIndexInSegmentName.text(ndx,
- segmentName));
+ segmentName));
}
}
@@ -559,8 +564,8 @@
public Path create( Reference value ) {
throw new ValueFormatException(value, getPropertyType(),
GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- Reference.class.getSimpleName(),
- value));
+ Reference.class.getSimpleName(),
+ value));
}
/**
@@ -577,8 +582,8 @@
return create(asciiString);
}
throw new ValueFormatException(value, getPropertyType(), GraphI18n.errorConvertingType.text(URI.class.getSimpleName(),
- Path.class.getSimpleName(),
- value));
+ Path.class.getSimpleName(),
+ value));
}
/**
@@ -588,8 +593,8 @@
*/
public Path create( UUID value ) {
throw new ValueFormatException(value, getPropertyType(), GraphI18n.unableToCreateValue.text(getPropertyType().getName(),
- UUID.class.getSimpleName(),
- value));
+ UUID.class.getSimpleName(),
+ value));
}
/**
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/xml/XmlHandler.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/xml/XmlHandler.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/xml/XmlHandler.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -311,7 +311,7 @@
properties.clear();
Object typePropertyValue = null;
// Convert each of the attributes to a property ...
- for (int i = 0; i != attributes.getLength(); ++i) {
+ for (int i = 0, len = attributes.getLength(); i != len; ++i) {
String attributeLocalName = attributes.getLocalName(i);
String attributeUri = attributes.getURI(i);
Name attributeName = null;
@@ -333,7 +333,7 @@
nodeName = nameFactory.create(attributes.getValue(i)); // don't use a decoder
continue;
}
- if (attributeName.equals(typeAttribute)) {
+ if (typePropertyValue == null && attributeName.equals(typeAttribute)) {
typePropertyValue = nameFactory.create(attributes.getValue(i)); // don't use a decoder
continue;
}
@@ -342,25 +342,25 @@
properties.add(property);
}
// Create the node name if required ...
- Name elementName = nameFactory.create(uri, localName, decoder);
if (nodeName == null) {
// No attribute defines the node name ...
- nodeName = elementName;
+ nodeName = nameFactory.create(uri, localName, decoder);
} else {
- // A attribute defines the node name ...
- typePropertyValue = elementName;
+ typePropertyValue = nameFactory.create(uri, localName, decoder);
}
- // Set the type property, if required
if (typeAttribute != null) {
+ // A attribute defines the node name. Set the type property, if required
if (typePropertyValue == null) typePropertyValue = typeAttributeValue;
- propertyValues[0] = typePropertyValue;
- Property property = propertyFactory.create(typeAttribute, propertyValues);
- properties.add(property);
+ if (typePropertyValue != null) {
+ propertyValues[0] = typePropertyValue;
+ Property property = propertyFactory.create(typeAttribute, propertyValues);
+ properties.add(property);
+ }
}
// Update the current path ...
currentPath = pathFactory.create(currentPath, nodeName);
// Create the node, and note that we don't care about same-name siblings (as the graph will correct them) ...
- destination.create(currentPath, properties, elementName);
+ destination.create(currentPath, properties);
}
/**
@@ -390,7 +390,7 @@
/**
* Create a property with the given name and value, obtained from an attribute name and value in the XML content.
* <p>
- * By default, this method creates a property by directly using the value as the sole String value of the property.
+ * By default, this method creates a property by directly using the value as the sole value of the property.
* </p>
*
* @param propertyName the name of the property; never null
@@ -398,9 +398,10 @@
* @return the property; may not be null
*/
protected Property createProperty( Name propertyName,
- String value ) {
+ Object value ) {
propertyValues[0] = value;
- return propertyFactory.create(propertyName, propertyValues);
+ Property result = propertyFactory.create(propertyName, propertyValues);
+ return result;
}
/**
@@ -424,14 +425,22 @@
*
* @param path the absolute path of the node
* @param properties the properties for the node; never null, but may be empty if there are no properties
- * @param elementName the name of the XML element from which the node should be created; never null, and may or may not be
- * the same name as the last segment of the path
*/
public void create( Path path,
- List<Property> properties,
- Name elementName );
+ List<Property> properties );
/**
+ * Create a node at the supplied path and with the supplied attributes. The path will be absolute.
+ *
+ * @param path the absolute path of the node
+ * @param firstProperty the first property
+ * @param additionalProperties the remaining properties for the node
+ */
+ public void create( Path path,
+ Property firstProperty,
+ Property... additionalProperties );
+
+ /**
* Signal to this destination that any enqueued create requests should be submitted. Usually this happens at the end of
* the document parsing, but an implementer must allow for it to be called multiple times and anytime during parsing.
*/
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -29,15 +29,15 @@
import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.collection.SimpleProblems;
import org.jboss.dna.common.util.Logger;
+import org.jboss.dna.graph.BasicExecutionContext;
import org.jboss.dna.graph.DnaLexicon;
+import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.properties.NamespaceRegistry;
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.properties.Property;
import org.jboss.dna.graph.properties.PropertyFactory;
import org.jboss.dna.graph.properties.ValueFactories;
-import org.jboss.dna.graph.properties.basic.BasicNamespaceRegistry;
-import org.jboss.dna.graph.properties.basic.StandardValueFactories;
/**
* @author John Verhaeg
@@ -45,18 +45,17 @@
@Immutable
public class MockSequencerContext implements SequencerContext {
- private final ValueFactories factories;
- private final NamespaceRegistry registry = new BasicNamespaceRegistry();
+ private final ExecutionContext context = new BasicExecutionContext();
private final Problems problems = new SimpleProblems();
public MockSequencerContext() {
+ NamespaceRegistry registry = context.getNamespaceRegistry();
registry.register("jcr", "http://www.jcp.org/jcr/1.0");
registry.register("mix", "http://www.jcp.org/jcr/mix/1.0");
registry.register("nt", "http://www.jcp.org/jcr/nt/1.0");
registry.register(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
registry.register("dnadtd", "http://www.jboss.org/dna/dtd/1.0");
registry.register("dnaxml", "http://www.jboss.org/dna/xml/1.0");
- factories = new StandardValueFactories(registry);
}
/**
@@ -65,7 +64,7 @@
* @see org.jboss.dna.common.component.ClassLoaderFactory#getClassLoader(java.lang.String[])
*/
public ClassLoader getClassLoader( String... classpath ) {
- return null;
+ return context.getClassLoader(classpath);
}
/**
@@ -119,7 +118,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getAccessControlContext()
*/
public AccessControlContext getAccessControlContext() {
- return null;
+ return context.getAccessControlContext();
}
/**
@@ -128,7 +127,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getLogger(java.lang.Class)
*/
public Logger getLogger( Class<?> clazz ) {
- return null;
+ return context.getLogger(clazz);
}
/**
@@ -137,7 +136,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getLogger(java.lang.String)
*/
public Logger getLogger( String name ) {
- return null;
+ return context.getLogger(name);
}
/**
@@ -146,7 +145,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getLoginContext()
*/
public LoginContext getLoginContext() {
- return null;
+ return context.getLoginContext();
}
/**
@@ -155,7 +154,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getNamespaceRegistry()
*/
public NamespaceRegistry getNamespaceRegistry() {
- return registry;
+ return context.getNamespaceRegistry();
}
/**
@@ -164,7 +163,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getPropertyFactory()
*/
public PropertyFactory getPropertyFactory() {
- return null;
+ return context.getPropertyFactory();
}
/**
@@ -173,7 +172,7 @@
* @see org.jboss.dna.graph.ExecutionContext#getSubject()
*/
public Subject getSubject() {
- return null;
+ return context.getSubject();
}
/**
@@ -182,6 +181,6 @@
* @see org.jboss.dna.graph.ExecutionContext#getValueFactories()
*/
public ValueFactories getValueFactories() {
- return factories;
+ return context.getValueFactories();
}
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerOutput.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerOutput.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerOutput.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -21,12 +21,15 @@
*/
package org.jboss.dna.graph.sequencers;
+import java.util.Collections;
import java.util.HashMap;
+import java.util.LinkedList;
import java.util.Map;
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.properties.PathFactory;
+import org.jboss.dna.graph.properties.Property;
/**
* @author Randall Hauch
@@ -35,12 +38,19 @@
@NotThreadSafe
public class MockSequencerOutput implements SequencerOutput {
- private final Map<Path, Object[]> properties;
+ private final Map<Path, Map<Name, Property>> propertiesByPath;
private final SequencerContext context;
+ private final LinkedList<Path> nodePathsInCreationOrder;
public MockSequencerOutput( SequencerContext context ) {
+ this(context, false);
+ }
+
+ public MockSequencerOutput( SequencerContext context,
+ boolean recordOrderOfNodeCreation ) {
this.context = context;
- this.properties = new HashMap<Path, Object[]>();
+ this.propertiesByPath = new HashMap<Path, Map<Name, Property>>();
+ this.nodePathsInCreationOrder = recordOrderOfNodeCreation ? new LinkedList<Path>() : null;
}
/**
@@ -49,11 +59,24 @@
public void setProperty( Path nodePath,
Name propertyName,
Object... values ) {
- Path key = createKey(nodePath, propertyName);
+ Map<Name, Property> properties = propertiesByPath.get(nodePath);
if (values == null || values.length == 0) {
- this.properties.remove(key);
+ // remove the property ...
+ if (properties != null) {
+ properties.remove(propertyName);
+ if (properties.isEmpty()) {
+ propertiesByPath.remove(nodePath);
+ if (nodePathsInCreationOrder != null) nodePathsInCreationOrder.remove(nodePath);
+ }
+ }
} else {
- this.properties.put(key, values);
+ if (properties == null) {
+ properties = new HashMap<Name, Property>();
+ propertiesByPath.put(nodePath, properties);
+ if (nodePathsInCreationOrder != null) nodePathsInCreationOrder.add(nodePath);
+ }
+ Property property = context.getPropertyFactory().create(propertyName, values);
+ properties.put(propertyName, property);
}
}
@@ -88,32 +111,57 @@
setProperty(path, name, values);
}
- public Object[] getPropertyValues( String nodePath,
- String property ) {
- Path key = createKey(nodePath, property);
- return this.properties.get(key);
+ public LinkedList<Path> getOrderOfCreation() {
+ return nodePathsInCreationOrder;
}
- public boolean hasProperty( String nodePath,
- String property ) {
- Path key = createKey(nodePath, property);
- return this.properties.containsKey(key);
+ public boolean exists( Path nodePath ) {
+ return this.propertiesByPath.containsKey(nodePath);
}
- public boolean hasProperties() {
- return this.properties.size() > 0;
+ public Map<Name, Property> getProperties( Path nodePath ) {
+ Map<Name, Property> properties = this.propertiesByPath.get(nodePath);
+ if (properties == null) return null;
+ return Collections.unmodifiableMap(properties);
}
- protected Path createKey( String nodePath,
- String propertyName ) {
+ public Property getProperty( String nodePath,
+ String propertyName ) {
Path path = context.getValueFactories().getPathFactory().create(nodePath);
Name name = context.getValueFactories().getNameFactory().create(propertyName);
- return createKey(path, name);
+ return getProperty(path, name);
}
- protected Path createKey( Path nodePath,
- Name propertyName ) {
- return context.getValueFactories().getPathFactory().create(nodePath, propertyName);
+ public Property getProperty( Path nodePath,
+ Name propertyName ) {
+ Map<Name, Property> properties = this.propertiesByPath.get(nodePath);
+ if (properties == null) return null;
+ return properties.get(propertyName);
}
+ public Object[] getPropertyValues( String nodePath,
+ String propertyName ) {
+ Path path = context.getValueFactories().getPathFactory().create(nodePath);
+ return getPropertyValues(path, propertyName);
+ }
+
+ public Object[] getPropertyValues( Path path,
+ String propertyName ) {
+ Name name = context.getValueFactories().getNameFactory().create(propertyName);
+ Property prop = getProperty(path, name);
+ if (prop != null) {
+ return prop.getValuesAsArray();
+ }
+ return null;
+ }
+
+ public boolean hasProperty( String nodePath,
+ String property ) {
+ return getProperty(nodePath, property) != null;
+ }
+
+ public boolean hasProperties() {
+ return this.propertiesByPath.size() > 0;
+ }
+
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/xml/XmlHandlerTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/xml/XmlHandlerTest.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/xml/XmlHandlerTest.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -29,6 +29,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
+import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -432,11 +433,44 @@
private final LinkedList<CreateNodeRequest> requests = new LinkedList<CreateNodeRequest>();
public void create( Path path,
- List<Property> properties,
- Name elementName ) {
+ List<Property> properties ) {
requests.add(new CreateNodeRequest(new Location(path), properties));
}
+ public void create( final Path path,
+ final Property firstProperty,
+ final Property... additionalProperties ) {
+ Location location = new Location(path);
+ if (firstProperty == null) {
+ requests.add(new CreateNodeRequest(location));
+ } else {
+ if (additionalProperties == null || additionalProperties.length == 0) {
+ requests.add(new CreateNodeRequest(location, firstProperty));
+ } else {
+ Iterator<Property> iter = new Iterator<Property>() {
+ private int index = -1;
+
+ public boolean hasNext() {
+ return index < additionalProperties.length;
+ }
+
+ public Property next() {
+ if (index == -1) {
+ ++index;
+ return firstProperty;
+ }
+ return additionalProperties[index++];
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ };
+ requests.add(new CreateNodeRequest(location, iter));
+ }
+ }
+ }
+
@SuppressWarnings( "synthetic-access" )
public ExecutionContext getExecutionContext() {
return XmlHandlerTest.this.context;
Added: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencer.java (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencer.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,37 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.sequencer.xml;
+
+/**
+ * An XML sequencer that is a specialization of {@link XmlSequencer} by inheriting unqualified attribute namespaces
+ * {@link XmlSequencer.AttributeScoping#INHERIT_ELEMENT_NAMESPACE from the element} rather than from the
+ * {@link XmlSequencer.AttributeScoping#USE_DEFAULT_NAMESPACE default namespace}.
+ *
+ * @author Randall Hauch
+ */
+public class InheritingXmlSequencer extends XmlSequencer {
+
+ public InheritingXmlSequencer() {
+ setAttributeScoping(AttributeScoping.INHERIT_ELEMENT_NAMESPACE);
+ }
+
+}
Property changes on: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencer.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -22,42 +22,64 @@
package org.jboss.dna.sequencer.xml;
import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import org.jboss.dna.common.util.StringUtil;
-import org.jboss.dna.graph.JcrLexicon;
+import org.jboss.dna.common.text.TextDecoder;
+import org.jboss.dna.graph.JcrNtLexicon;
import org.jboss.dna.graph.properties.Name;
-import org.jboss.dna.graph.properties.NameFactory;
-import org.jboss.dna.graph.properties.NamespaceRegistry;
-import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.sequencers.SequencerContext;
import org.jboss.dna.graph.sequencers.SequencerOutput;
import org.jboss.dna.graph.sequencers.StreamSequencer;
-import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
-import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
-import org.xml.sax.ext.DefaultHandler2;
import org.xml.sax.helpers.XMLReaderFactory;
/**
+ * A sequencer for XML files, which maintains DTD, entity, comments, and other content. Note that by default the sequencer uses
+ * the {@link XmlSequencer.AttributeScoping#USE_DEFAULT_NAMESPACE default namespace} for unqualified attribute rather than
+ * {@link XmlSequencer.AttributeScoping#INHERIT_ELEMENT_NAMESPACE inheriting the namespace from the element}. (See also
+ * {@link InheritingXmlSequencer}.
+ *
* @author John Verhaeg
*/
public class XmlSequencer implements StreamSequencer {
- private static final String DEFAULT_PRIMARY_TYPE = "nt:unstructured";
- private static final String DECL_HANDLER_FEATURE = "http://xml.org/sax/properties/declaration-handler";
- private static final String ENTITY_RESOLVER_2_FEATURE = "http://xml.org/sax/features/use-entity-resolver2";
- private static final String LEXICAL_HANDLER_FEATURE = "http://xml.org/sax/properties/lexical-handler";
- private static final String RESOLVE_DTD_URIS_FEATURE = "http://xml.org/sax/features/resolve-dtd-uris";
- private static final String LOAD_EXTERNAL_DTDS_FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
+ /**
+ * The choices for how attributes that have no namespace prefix should be assigned a namespace.
+ *
+ * @author Randall Hauch
+ */
+ public enum AttributeScoping {
+ /** The attribute's namespace is the default namespace */
+ USE_DEFAULT_NAMESPACE,
+ /** The attribute's namespace is the same namespace as the containing element */
+ INHERIT_ELEMENT_NAMESPACE;
+ }
+ /*package*/static final String DEFAULT_PRIMARY_TYPE = "nt:unstructured";
+ /*package*/static final String DECL_HANDLER_FEATURE = "http://xml.org/sax/properties/declaration-handler";
+ /*package*/static final String ENTITY_RESOLVER_2_FEATURE = "http://xml.org/sax/features/use-entity-resolver2";
+ /*package*/static final String LEXICAL_HANDLER_FEATURE = "http://xml.org/sax/properties/lexical-handler";
+ /*package*/static final String RESOLVE_DTD_URIS_FEATURE = "http://xml.org/sax/features/resolve-dtd-uris";
+ /*package*/static final String LOAD_EXTERNAL_DTDS_FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
+
+ private AttributeScoping scoping = AttributeScoping.USE_DEFAULT_NAMESPACE;
+
/**
+ * @param scoping Sets scoping to the specified value.
+ */
+ public void setAttributeScoping( AttributeScoping scoping ) {
+ this.scoping = scoping;
+ }
+
+ /**
+ * @return scoping
+ */
+ public AttributeScoping getAttributeScoping() {
+ return scoping;
+ }
+
+ /**
* {@inheritDoc}
*
* @see org.jboss.dna.graph.sequencers.StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext)
@@ -67,8 +89,13 @@
SequencerContext context ) {
XMLReader reader;
try {
+ // Set up the XML handler ...
+ Name primaryType = JcrNtLexicon.UNSTRUCTURED;
+ Name nameAttribute = null;
+ TextDecoder decoder = null;
+ XmlSequencerHandler handler = new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ // Create the reader ...
reader = XMLReaderFactory.createXMLReader();
- Handler handler = new Handler(output, context);
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
// Ensure handler acting as entity resolver 2
@@ -97,9 +124,9 @@
* @param featureName the name of the feature; may not be null
* @param value the value for the feature
*/
- private void setFeature( XMLReader reader,
- String featureName,
- boolean value ) {
+ /*package*/static void setFeature( XMLReader reader,
+ String featureName,
+ boolean value ) {
try {
if (reader.getFeature(featureName) != value) {
reader.setFeature(featureName, value);
@@ -109,428 +136,4 @@
}
}
- private final class Handler extends DefaultHandler2 {
-
- private final SequencerOutput output;
- private final SequencerContext context;
-
- private Path path; // The DNA path of the node representing the current XML element
-
- // Cached instances of the name factory and commonly referenced names
- private final NameFactory nameFactory;
- private Name defaultPrimaryType;
-
- // Recursive map used to track the number of occurrences of names for elements under a particular path
- private Map<Name, List<IndexedName>> nameToIndexedNamesMap = new HashMap<Name, List<IndexedName>>();
-
- // The stack of recursive maps being processed, with the head entry being the map for the current path
- private final LinkedList<Map<Name, List<IndexedName>>> nameToIndexedNamesMapStack = new LinkedList<Map<Name, List<IndexedName>>>();
-
- // The stack of XML namespace in scope, with the head entry being namespace of the closest ancestor element declaring a
- // namespace.
- private final LinkedList<String> nsStack = new LinkedList<String>();
-
- // Builder used to concatenate concurrent lines of CDATA into a single value.
- private StringBuilder cDataBuilder;
-
- // Builder used to concatenate concurrent lines of element content and entity evaluations into a single value.
- private StringBuilder contentBuilder;
-
- // The entity being processed
- private String entity;
-
- Handler( SequencerOutput output,
- SequencerContext context ) {
- assert output != null;
- assert context != null;
- this.output = output;
- this.context = context;
- // Initialize path to a an empty path relative to the SequencerOutput's target path.
- path = context.getValueFactories().getPathFactory().createRelativePath();
- // Cache name factory since it is frequently used
- nameFactory = context.getValueFactories().getNameFactory();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
- */
- @Override
- public void characters( char[] ch,
- int start,
- int length ) {
- String content = String.valueOf(ch, start, length);
- // Check if data should be appended to previously parsed CDATA
- if (cDataBuilder == null) {
- // If content is for an entity, replace with entity reference
- if (entity != null) {
- content = '&' + entity + ';';
- }
- // Check if first line of content
- if (contentBuilder == null) {
- contentBuilder = new StringBuilder(content);
- } else {
- // Append additional lines or entity evaluations to previous content, separated by a space
- if (entity == null) {
- contentBuilder.append(' ');
- }
- contentBuilder.append(content);
- // Text within builder will be output when another element or CDATA is encountered
- }
- } else {
- cDataBuilder.append(ch, start, length);
- // Text within builder will be output at the end of CDATA
- }
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#comment(char[], int, int)
- */
- @Override
- public void comment( char[] ch,
- int start,
- int length ) {
- // Output separate nodes for each comment since multiple are allowed
- startElement(DnaXmlLexicon.COMMENT);
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.COMMENT);
- output.setProperty(path, DnaXmlLexicon.COMMENT_CONTENT, String.valueOf(ch, start, length));
- endElement();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#endCDATA()
- */
- @Override
- public void endCDATA() {
- // Output CDATA built in characters() method
- output.setProperty(path, DnaXmlLexicon.CDATA_CONTENT, cDataBuilder.toString());
- endElement();
- // Null-out builder to free memory
- cDataBuilder = null;
- }
-
- private void endContent() {
- if (contentBuilder != null) {
- // Normalize content
- String content = StringUtil.normalize(contentBuilder.toString());
- // Null-out builder to setup for subsequent content.
- // Must be done before call to startElement below to prevent infinite loop.
- contentBuilder = null;
- // Skip if nothing in content but whitespace
- if (content.length() > 0) {
- // Create separate node for each content entry since entries can be interspersed amongst child elements
- startElement(DnaXmlLexicon.ELEMENT_CONTENT);
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.ELEMENT_CONTENT);
- output.setProperty(path, DnaXmlLexicon.ELEMENT_CONTENT, content);
- endElement();
- }
- }
- }
-
- private void endElement() {
- // Recover parent's path, namespace, and indexedName map, clearing the ended element's map to free memory
- path = path.getParent();
- nameToIndexedNamesMap.clear();
- nameToIndexedNamesMap = nameToIndexedNamesMapStack.removeFirst();
- nsStack.removeFirst();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
- public void endElement( String uri,
- String localName,
- String name ) {
- // Check if content still needs to be output
- endContent();
- endElement();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#endEntity(java.lang.String)
- */
- @Override
- public void endEntity( String name ) {
- entity = null;
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#error(org.xml.sax.SAXParseException)
- */
- @Override
- public void error( SAXParseException error ) {
- context.getLogger(XmlSequencer.class).error(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
- context.getProblems().addError(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#externalEntityDecl(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
- public void externalEntityDecl( String name,
- String publicId,
- String systemId ) {
- // Add "synthetic" entity container to path to help prevent name collisions with XML elements
- Name entityName = DnaDtdLexicon.ENTITY;
- startElement(entityName);
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, entityName);
- output.setProperty(path, nameFactory.create(DnaDtdLexicon.NAME), name);
- output.setProperty(path, nameFactory.create(DnaDtdLexicon.PUBLIC_ID), publicId);
- output.setProperty(path, nameFactory.create(DnaDtdLexicon.SYSTEM_ID), systemId);
- endElement();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#fatalError(org.xml.sax.SAXParseException)
- */
- @Override
- public void fatalError( SAXParseException error ) {
- context.getLogger(XmlSequencer.class).error(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
- context.getProblems().addError(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
- }
-
- private Name getDefaultPrimaryType() {
- if (defaultPrimaryType == null) {
- defaultPrimaryType = nameFactory.create(DEFAULT_PRIMARY_TYPE);
- }
- return defaultPrimaryType;
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#internalEntityDecl(java.lang.String, java.lang.String)
- */
- @Override
- public void internalEntityDecl( String name,
- String value ) {
- // Add "synthetic" entity container to path to help prevent name collisions with XML elements
- Name entityName = DnaDtdLexicon.ENTITY;
- startElement(entityName);
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, entityName);
- output.setProperty(path, DnaDtdLexicon.NAME, name);
- output.setProperty(path, DnaDtdLexicon.VALUE, value);
- endElement();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#processingInstruction(java.lang.String, java.lang.String)
- */
- @Override
- public void processingInstruction( String target,
- String data ) {
- // Output separate nodes for each instruction since multiple are allowed
- Name name = DnaXmlLexicon.PROCESSING_INSTRUCTION;
- startElement(name);
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, name);
- output.setProperty(path, DnaXmlLexicon.TARGET, target);
- output.setProperty(path, DnaXmlLexicon.PROCESSING_INSTRUCTION_CONTENT, data);
- endElement();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#startCDATA()
- */
- @Override
- public void startCDATA() {
- // Output separate nodes for each CDATA since multiple are allowed
- startElement(DnaXmlLexicon.CDATA);
- // Prepare builder for concatenating consecutive lines of CDATA
- cDataBuilder = new StringBuilder();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#startDocument()
- */
- @Override
- public void startDocument() {
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.DOCUMENT);
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#startDTD(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
- public void startDTD( String name,
- String publicId,
- String systemId ) {
- output.setProperty(path, DnaDtdLexicon.NAME, name);
- output.setProperty(path, DnaDtdLexicon.PUBLIC_ID, publicId);
- output.setProperty(path, DnaDtdLexicon.SYSTEM_ID, systemId);
- }
-
- private void startElement( Name name ) {
- // Check if content still needs to be output
- endContent();
- // Add name to list of indexed names for this element to ensure we use the correct index (which is the size of the
- // list)
- List<IndexedName> indexedNames = nameToIndexedNamesMap.get(name);
- if (indexedNames == null) {
- indexedNames = new ArrayList<IndexedName>();
- nameToIndexedNamesMap.put(name, indexedNames);
- }
- IndexedName indexedName = new IndexedName();
- indexedNames.add(indexedName);
- // Add element name and the appropriate index to the path.
- // Per the JCR spec, the index must be relative to same-name sibling nodes
- path = context.getValueFactories().getPathFactory().create(path, name, indexedNames.size());
- path = path.getNormalizedPath();
- // Add the indexed name map to the stack and set the current map to the new element's map
- nameToIndexedNamesMapStack.addFirst(nameToIndexedNamesMap);
- nameToIndexedNamesMap = indexedName.nameToIndexedNamesMap;
- // Set the current namespace to whatever is declared by this element, or if not declared, to its nearest ancestor that
- // does declare a namespace.
- String ns = name.getNamespaceUri();
- if (ns.length() == 0) {
- nsStack.addFirst(nsStack.isEmpty() ? "" : nsStack.getFirst());
- } else {
- nsStack.addFirst(ns);
- }
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String,
- * org.xml.sax.Attributes)
- */
- @Override
- public void startElement( String uri,
- String localName,
- String name,
- Attributes attributes ) {
- // Look for the "jcr:name" attribute, and use that if it's there
- Name type = getDefaultPrimaryType();
- Name nameObj = nameFactory.create(name);
- for (int ndx = 0, len = attributes.getLength(); ndx < len; ++ndx) {
- String ns = attributes.getURI(ndx);
- String attrLocalName = attributes.getLocalName(ndx);
- Object value = attributes.getValue(ndx);
- String jcrNsUri = context.getNamespaceRegistry().getNamespaceForPrefix("jcr");
- if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("name")) {
- nameObj = nameFactory.create(value);
- break;
- }
- }
- startElement(nameObj);
- output.setProperty(path, JcrLexicon.PRIMARY_TYPE, type);
- // Output this element's attributes using the attribute's namespace, if supplied, or the current namespace in scope.
- String inheritedNs = nsStack.getFirst();
- for (int ndx = 0, len = attributes.getLength(); ndx < len; ++ndx) {
- String ns = attributes.getURI(ndx);
- String attrLocalName = attributes.getLocalName(ndx);
- Object value = attributes.getValue(ndx);
- String jcrNsUri = context.getNamespaceRegistry().getNamespaceForPrefix("jcr");
- if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("primaryType")) {
- value = nameFactory.create(value);
- }
- if (jcrNsUri != null && jcrNsUri.equals(ns) && attrLocalName.equals("name")) {
- continue;
- }
- output.setProperty(path, nameFactory.create(ns.length() == 0 ? inheritedNs : ns, attrLocalName), value);
- }
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#startEntity(java.lang.String)
- */
- @Override
- public void startEntity( String name ) {
- entity = name;
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#startPrefixMapping(java.lang.String, java.lang.String)
- */
- @Override
- public void startPrefixMapping( String prefix,
- String uri ) {
- // Register any unregistered namespaces
- NamespaceRegistry registry = context.getNamespaceRegistry();
- if (!registry.isRegisteredNamespaceUri(uri)) {
- registry.register(prefix, uri);
- }
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#warning(org.xml.sax.SAXParseException)
- */
- @Override
- public void warning( SAXParseException warning ) {
- context.getLogger(XmlSequencer.class).warn(warning, XmlSequencerI18n.warningSequencingXmlDocument);
- context.getProblems().addWarning(warning, XmlSequencerI18n.warningSequencingXmlDocument, warning);
- }
- }
-
- private class IndexedName {
-
- Map<Name, List<IndexedName>> nameToIndexedNamesMap = new HashMap<Name, List<IndexedName>>();
-
- IndexedName() {
- }
- }
}
Added: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,604 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.sequencer.xml;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import org.jboss.dna.common.collection.Problems;
+import org.jboss.dna.common.text.TextDecoder;
+import org.jboss.dna.common.text.XmlNameEncoder;
+import org.jboss.dna.common.util.CheckArg;
+import org.jboss.dna.common.util.StringUtil;
+import org.jboss.dna.graph.BasicExecutionContext;
+import org.jboss.dna.graph.ExecutionContext;
+import org.jboss.dna.graph.JcrLexicon;
+import org.jboss.dna.graph.properties.Name;
+import org.jboss.dna.graph.properties.NameFactory;
+import org.jboss.dna.graph.properties.NamespaceRegistry;
+import org.jboss.dna.graph.properties.Path;
+import org.jboss.dna.graph.properties.PathFactory;
+import org.jboss.dna.graph.properties.PropertyFactory;
+import org.jboss.dna.graph.properties.ValueFormatException;
+import org.jboss.dna.graph.properties.basic.LocalNamespaceRegistry;
+import org.jboss.dna.graph.sequencers.SequencerContext;
+import org.jboss.dna.graph.sequencers.SequencerOutput;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXParseException;
+import org.xml.sax.ext.DefaultHandler2;
+
+/**
+ * @author Randall Hauch
+ */
+public class XmlSequencerHandler extends DefaultHandler2 {
+
+ private final SequencerOutput output;
+ private final SequencerContext context;
+
+ /**
+ * Decoder for XML names, to turn '_xHHHH_' sequences in the XML element and attribute names into the corresponding UTF-16
+ * characters.
+ */
+ public static TextDecoder DEFAULT_DECODER = new XmlNameEncoder();
+
+ /**
+ * The default {@link XmlSequencer.AttributeScoping}.
+ */
+ public static XmlSequencer.AttributeScoping DEFAULT_ATTRIBUTE_SCOPING = XmlSequencer.AttributeScoping.USE_DEFAULT_NAMESPACE;
+
+ /**
+ * The name of the attribute that should be used for the node name.
+ */
+ protected final Name nameAttribute;
+
+ /**
+ * The default primary type.
+ */
+ protected final Name defaultPrimaryType;
+
+ /**
+ * The cached reference to the graph's path factory.
+ */
+ protected final PathFactory pathFactory;
+
+ /**
+ * The cached reference to the graph's name factory.
+ */
+ protected final NameFactory nameFactory;
+
+ /**
+ * The cached reference to the graph's property factory.
+ */
+ protected final PropertyFactory propertyFactory;
+
+ /**
+ * The cached reference to the graph's namespace registry.
+ */
+ protected final NamespaceRegistry namespaceRegistry;
+
+ /**
+ * The TextDecoder that is used to decode the names.
+ */
+ protected final TextDecoder decoder;
+
+ /**
+ * The stack of prefixes for each namespace, which is used to keep the {@link #namespaceRegistry local namespace registry} in
+ * sync with the namespaces in the XML document.
+ */
+ private final Map<String, LinkedList<String>> prefixStackByUri = new HashMap<String, LinkedList<String>>();
+
+ private final XmlSequencer.AttributeScoping attributeScoping;
+
+ /**
+ * The path for the node representing the current element. This starts out as the path supplied by the constructor, and never
+ * is shorter than that initial path.
+ */
+ protected Path currentPath;
+
+ // Recursive map used to track the number of occurrences of names for elements under a particular path
+ private Map<Name, List<IndexedName>> nameToIndexedNamesMap = new HashMap<Name, List<IndexedName>>();
+
+ // The stack of recursive maps being processed, with the head entry being the map for the current path
+ private final LinkedList<Map<Name, List<IndexedName>>> nameToIndexedNamesMapStack = new LinkedList<Map<Name, List<IndexedName>>>();
+
+ private String currentEntityName;
+ private StringBuilder cDataContent;
+ private StringBuilder contentBuilder;
+ private final Problems problems;
+
+ /**
+ * @param output
+ * @param context
+ * @param nameAttribute
+ * @param defaultPrimaryType
+ * @param textDecoder
+ * @param scoping
+ */
+ XmlSequencerHandler( SequencerOutput output,
+ SequencerContext context,
+ Name nameAttribute,
+ Name defaultPrimaryType,
+ TextDecoder textDecoder,
+ XmlSequencer.AttributeScoping scoping ) {
+ CheckArg.isNotNull(output, "output");
+ CheckArg.isNotNull(context, "context");
+
+ // Use the execution context ...
+ this.output = output;
+ this.context = context;
+ this.problems = context.getProblems();
+ assert this.problems != null;
+
+ this.nameAttribute = nameAttribute;
+ this.defaultPrimaryType = defaultPrimaryType;
+ this.decoder = textDecoder != null ? textDecoder : DEFAULT_DECODER;
+ this.attributeScoping = scoping != null ? scoping : DEFAULT_ATTRIBUTE_SCOPING;
+
+ // Set up a local namespace registry that is kept in sync with the namespaces found in this XML document ...
+ NamespaceRegistry namespaceRegistry = new LocalNamespaceRegistry(this.context.getNamespaceRegistry());
+ final ExecutionContext localContext = new BasicExecutionContext(this.context, namespaceRegistry);
+
+ // Set up references to frequently-used objects in the context ...
+ this.nameFactory = localContext.getValueFactories().getNameFactory();
+ this.pathFactory = localContext.getValueFactories().getPathFactory();
+ this.propertyFactory = localContext.getPropertyFactory();
+ this.namespaceRegistry = localContext.getNamespaceRegistry();
+ assert this.nameFactory != null;
+ assert this.pathFactory != null;
+ assert this.propertyFactory != null;
+ assert this.namespaceRegistry != null;
+
+ // Set up the initial path ...
+ this.currentPath = this.pathFactory.createRelativePath();
+ assert this.currentPath != null;
+ }
+
+ private void startNode( Name name ) {
+ // Check if content still needs to be output
+ if (contentBuilder != null) endContent();
+ // Add name to list of indexed names for this element to ensure we use the correct index (which is the size of the
+ // list)
+ List<IndexedName> indexedNames = nameToIndexedNamesMap.get(name);
+ if (indexedNames == null) {
+ indexedNames = new ArrayList<IndexedName>();
+ nameToIndexedNamesMap.put(name, indexedNames);
+ }
+ IndexedName indexedName = new IndexedName();
+ indexedNames.add(indexedName);
+ // Add element name and the appropriate index to the path.
+ // Per the JCR spec, the index must be relative to same-name sibling nodes
+ currentPath = pathFactory.create(currentPath, name, indexedNames.size()).getNormalizedPath();
+ // currentPath = currentPath.getNormalizedPath();
+ // Add the indexed name map to the stack and set the current map to the new element's map
+ nameToIndexedNamesMapStack.addFirst(nameToIndexedNamesMap);
+ nameToIndexedNamesMap = indexedName.nameToIndexedNamesMap;
+ }
+
+ private void endNode() {
+ // Recover parent's path, namespace, and indexedName map, clearing the ended element's map to free memory
+ currentPath = currentPath.getParent();
+ currentPath = currentPath.getNormalizedPath();
+ nameToIndexedNamesMap.clear();
+ nameToIndexedNamesMap = nameToIndexedNamesMapStack.removeFirst();
+ }
+
+ /**
+ * See if there is any element content that needs to be completed.
+ */
+ protected void endContent() {
+ // Process the content of the element ...
+ String content = StringUtil.normalize(contentBuilder.toString());
+ // Null-out builder to setup for subsequent content.
+ // Must be done before call to startElement below to prevent infinite loop.
+ contentBuilder = null;
+ // Skip if nothing in content but whitespace
+ if (content.length() > 0) {
+ // Create separate node for each content entry since entries can be interspersed amongst child elements
+ startNode(DnaXmlLexicon.ELEMENT_CONTENT);
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.ELEMENT_CONTENT);
+ output.setProperty(currentPath, DnaXmlLexicon.ELEMENT_CONTENT, content);
+ endNode();
+ }
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#startDocument()
+ */
+ @Override
+ public void startDocument() {
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.DOCUMENT);
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#startDTD(java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public void startDTD( String name,
+ String publicId,
+ String systemId ) {
+ output.setProperty(currentPath, DnaDtdLexicon.NAME, name);
+ output.setProperty(currentPath, DnaDtdLexicon.PUBLIC_ID, publicId);
+ output.setProperty(currentPath, DnaDtdLexicon.SYSTEM_ID, systemId);
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#externalEntityDecl(java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public void externalEntityDecl( String name,
+ String publicId,
+ String systemId ) {
+ // Add "synthetic" entity container to path to help prevent name collisions with XML elements
+ startNode(DnaDtdLexicon.ENTITY);
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaDtdLexicon.ENTITY);
+ output.setProperty(currentPath, DnaDtdLexicon.NAME, name);
+ if (publicId != null) output.setProperty(currentPath, DnaDtdLexicon.PUBLIC_ID, publicId);
+ if (systemId != null) output.setProperty(currentPath, DnaDtdLexicon.SYSTEM_ID, systemId);
+ endNode();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#internalEntityDecl(java.lang.String, java.lang.String)
+ */
+ @Override
+ public void internalEntityDecl( String name,
+ String value ) {
+ // Add "synthetic" entity container to path to help prevent name collisions with XML elements
+ startNode(DnaDtdLexicon.ENTITY);
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaDtdLexicon.ENTITY);
+ output.setProperty(currentPath, DnaDtdLexicon.NAME, name);
+ output.setProperty(currentPath, DnaDtdLexicon.VALUE, value);
+ endNode();
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#processingInstruction(java.lang.String, java.lang.String)
+ */
+ @Override
+ public void processingInstruction( String target,
+ String data ) {
+ // Output separate nodes for each instruction since multiple are allowed
+ startNode(DnaXmlLexicon.PROCESSING_INSTRUCTION);
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.PROCESSING_INSTRUCTION);
+ output.setProperty(currentPath, DnaXmlLexicon.TARGET, target.trim());
+ if (data != null) {
+ output.setProperty(currentPath, DnaXmlLexicon.PROCESSING_INSTRUCTION_CONTENT, data.trim());
+ }
+ endNode();
+ }
+
+ /**
+ * {@inheritDoc}
+ * <p>
+ * This method ensures that the namespace is registered with the {@link NamespaceRegistry registry}, using the supplied prefix
+ * to register the namespace if required. Note that because this class does not really use the namespace prefixes to create
+ * {@link Name} objects, no attempt is made to match the XML namespace prefixes.
+ * </p>
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#startPrefixMapping(java.lang.String, java.lang.String)
+ */
+ @Override
+ public void startPrefixMapping( String prefix,
+ String uri ) {
+ assert uri != null;
+ // Add the prefix to the stack ...
+ LinkedList<String> prefixStack = this.prefixStackByUri.get(uri);
+ if (prefixStack == null) {
+ prefixStack = new LinkedList<String>();
+ this.prefixStackByUri.put(uri, prefixStack);
+ }
+ prefixStack.addFirst(prefix);
+
+ // If the namespace is already registered, then we'll have to register it in the context's registry, too.
+ if (!namespaceRegistry.isRegisteredNamespaceUri(uri)) {
+ // The namespace is not already registered (locally or in the context's registry), so we have to
+ // register it with the context's registry (which the local register then inherits).
+ NamespaceRegistry contextRegistry = context.getNamespaceRegistry();
+ if (contextRegistry.getNamespaceForPrefix(prefix) != null) {
+ // The prefix is already bound, so register and generate a unique prefix
+ context.getNamespaceRegistry().getPrefixForNamespaceUri(uri, true);
+ // Now register locally with the supplied prefix ...
+ namespaceRegistry.register(prefix, uri);
+ } else {
+ context.getNamespaceRegistry().register(prefix, uri);
+ }
+ } else {
+ // It is already registered, but re-register it locally using the supplied prefix ...
+ namespaceRegistry.register(prefix, uri);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#endPrefixMapping(java.lang.String)
+ */
+ @Override
+ public void endPrefixMapping( String prefix ) {
+ assert prefix != null;
+ // Get the current URI for this prefix ...
+ String uri = namespaceRegistry.getNamespaceForPrefix(prefix);
+ assert uri != null;
+
+ // Get the previous prefix from the stack ...
+ LinkedList<String> prefixStack = this.prefixStackByUri.get(uri);
+ assert prefixStack != null;
+ assert !prefixStack.isEmpty();
+ String existingPrefix = prefixStack.removeFirst();
+ assert prefix.equals(existingPrefix);
+
+ // If there are no previous prefixes, then remove the mapping ...
+ if (prefixStack.isEmpty()) {
+ namespaceRegistry.unregister(uri);
+ prefixStackByUri.remove(uri);
+ } else {
+ String previous = prefixStack.getFirst();
+ namespaceRegistry.register(previous, uri);
+ }
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#startEntity(java.lang.String)
+ */
+ @Override
+ public void startEntity( String name ) {
+ // Record that we've started an entity by capturing the name of the entity ...
+ currentEntityName = name;
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#endEntity(java.lang.String)
+ */
+ @Override
+ public void endEntity( String name ) {
+ // currentEntityName is nulled in 'characters(...)', not here.
+ // See DNA-231 for an issue related to this
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#startCDATA()
+ */
+ @Override
+ public void startCDATA() {
+ // CDATA sections can start in the middle of element content, so there may already be some
+ // element content already processed ...
+ if (contentBuilder != null) endContent();
+
+ // Prepare builder for concatenating consecutive lines of CDATA
+ cDataContent = new StringBuilder();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#endCDATA()
+ */
+ @Override
+ public void endCDATA() {
+ // Output CDATA built in characters() method
+ startNode(DnaXmlLexicon.CDATA);
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, defaultPrimaryType);
+ output.setProperty(currentPath, DnaXmlLexicon.CDATA_CONTENT, cDataContent.toString());
+ endNode();
+ // Null-out builder to free memory
+ cDataContent = null;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
+ */
+ @Override
+ public void characters( char[] ch,
+ int start,
+ int length ) {
+ String content = String.valueOf(ch, start, length);
+ if (cDataContent != null) {
+ // Processing the characters in the CDATA, so add to the builder
+ cDataContent.append(ch, start, length);
+ // Text within builder will be output at the end of CDATA
+ } else {
+ if (contentBuilder == null) {
+ // This is the first line of content, so we have to create the StringBuilder ...
+ contentBuilder = new StringBuilder();
+ }
+ if (currentEntityName != null) {
+ // This is an entity reference, so rather than use the entity value characters (the content passed
+ // into this method), we want to keep the entity reference ...
+ contentBuilder.append('&').append(currentEntityName).append(';');
+
+ // We're done reading the entity characters, so null it out
+ currentEntityName = null;
+ } else {
+ // Just append the content normally ...
+ contentBuilder.append(content);
+ }
+ // Text within builder will be output when another element or CDATA is encountered
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.ext.DefaultHandler2#comment(char[], int, int)
+ */
+ @Override
+ public void comment( char[] ch,
+ int start,
+ int length ) {
+ // Output separate nodes for each comment since multiple are allowed
+ startNode(DnaXmlLexicon.COMMENT);
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.COMMENT);
+ output.setProperty(currentPath, DnaXmlLexicon.COMMENT_CONTENT, String.valueOf(ch, start, length).trim());
+ endNode();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String,
+ * org.xml.sax.Attributes)
+ */
+ @Override
+ public void startElement( String uri,
+ String localName,
+ String name,
+ Attributes attributes ) {
+ assert localName != null;
+
+ // Create the node with the name built from the element's name ...
+ Name nodeName = null;
+ if (nameAttribute != null) {
+ try {
+ String jcrNameValue = attributes.getValue(nameAttribute.getNamespaceUri(), nameAttribute.getLocalName());
+ nodeName = nameFactory.create(jcrNameValue);
+ } catch (ValueFormatException e) {
+ }
+ }
+ if (nodeName == null) nodeName = nameFactory.create(uri, localName, decoder);
+ startNode(nodeName);
+
+ // Set the type of the node ...
+ if (defaultPrimaryType != null) {
+ output.setProperty(currentPath, JcrLexicon.PRIMARY_TYPE, defaultPrimaryType);
+ }
+
+ // Now, set each attribute as a property ...
+ for (int i = 0, len = attributes.getLength(); i != len; ++i) {
+ String attributeLocalName = attributes.getLocalName(i);
+ String attributeUri = attributes.getURI(i);
+ Name attributeName = null;
+ if ((attributeUri == null || attributeUri.length() == 0) && attributes.getQName(i).indexOf(':') == -1) {
+ switch (this.attributeScoping) {
+ case INHERIT_ELEMENT_NAMESPACE:
+ attributeName = nameFactory.create(uri, attributeLocalName, decoder);
+ break;
+ case USE_DEFAULT_NAMESPACE:
+ attributeName = nameFactory.create(attributeLocalName, decoder);
+ break;
+ }
+ } else {
+ attributeName = nameFactory.create(attributeUri, attributeLocalName, decoder);
+ }
+ assert attributeName != null;
+ if (JcrLexicon.NAME.equals(attributeName)) {
+ // We don't want to record the "jcr:name" attribute since it won't match the node name ...
+ continue;
+ }
+ Object value = attributes.getValue(i);
+ if (JcrLexicon.PRIMARY_TYPE.equals(attributeName)) {
+ // Convert it to a name ...
+ value = nameFactory.create(value);
+ }
+ output.setProperty(currentPath, attributeName, attributes.getValue(i));
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.graph.xml.XmlHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
+ */
+ @Override
+ public void endElement( String uri,
+ String localName,
+ String name ) {
+ // Check if content still needs to be output
+ if (contentBuilder != null) endContent();
+
+ // End the current node ...
+ endNode();
+ }
+
+ /**
+ * <p>
+ * {@inheritDoc}
+ * </p>
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#warning(org.xml.sax.SAXParseException)
+ */
+ @Override
+ public void warning( SAXParseException warning ) {
+ problems.addWarning(warning, XmlSequencerI18n.warningSequencingXmlDocument, warning);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#error(org.xml.sax.SAXParseException)
+ */
+ @Override
+ public void error( SAXParseException error ) {
+ problems.addError(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.xml.sax.helpers.DefaultHandler#fatalError(org.xml.sax.SAXParseException)
+ */
+ @Override
+ public void fatalError( SAXParseException error ) {
+ problems.addError(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
+ }
+
+ private class IndexedName {
+
+ Map<Name, List<IndexedName>> nameToIndexedNamesMap = new HashMap<Name, List<IndexedName>>();
+
+ IndexedName() {
+ }
+ }
+}
Property changes on: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerHandler.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencerTest.java (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencerTest.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,114 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.sequencer.xml;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsInstanceOf.instanceOf;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import org.jboss.dna.graph.properties.Name;
+import org.jboss.dna.graph.sequencers.MockSequencerContext;
+import org.jboss.dna.graph.sequencers.MockSequencerOutput;
+import org.jboss.dna.graph.sequencers.SequencerContext;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author John Verhaeg
+ */
+public class InheritingXmlSequencerTest {
+
+ private static final String DOCUMENT = "dnaxml:document";
+
+ private XmlSequencer sequencer;
+ private InputStream stream;
+ private MockSequencerOutput output;
+ private URL xsd;
+ private SequencerContext context;
+
+ @Before
+ public void beforeEach() {
+ sequencer = new InheritingXmlSequencer();
+ context = new MockSequencerContext();
+ output = new MockSequencerOutput(context);
+ xsd = this.getClass().getClassLoader().getResource("Descriptor.1.0.xsd");
+ assertThat(xsd, is(notNullValue()));
+ }
+
+ @After
+ public void afterEach() throws Exception {
+ if (stream != null) {
+ try {
+ stream.close();
+ } finally {
+ stream = null;
+ }
+ }
+ }
+
+ @Test
+ public void shouldSequenceXsds() throws IOException {
+ assertThat(sequencer.getAttributeScoping(), is(XmlSequencer.AttributeScoping.INHERIT_ELEMENT_NAMESPACE));
+ verifyDocument(xsd);
+ verifyName("xs:schema", "jcr:primaryType", "nt:unstructured");
+ verifyString("xs:schema", "xs:targetNamespace", "http://ns.adobe.com/air/application/1.0");
+ verifyString("xs:schema", "xs:elementFormDefault", "qualified");
+ verifyName("xs:schema/xs:element", "jcr:primaryType", "nt:unstructured");
+ verifyString("xs:schema/xs:element", "xs:name", "application");
+ }
+
+ private <T> T verify( String nodePath,
+ String property,
+ Class<T> expectedClass ) {
+ Object[] values = output.getPropertyValues(nodePath.length() == 0 ? "" : nodePath, property);
+ assertThat(values, notNullValue());
+ assertThat(values.length, is(1));
+ Object value = values[0];
+ assertThat(value, instanceOf(expectedClass));
+ return expectedClass.cast(value);
+ }
+
+ private void verifyDocument( URL url ) throws IOException {
+ stream = url.openStream();
+ assertThat(stream, is(notNullValue()));
+ sequencer.sequence(stream, output, context);
+ verifyName("", "jcr:primaryType", DOCUMENT);
+ }
+
+ private void verifyName( String nodePath,
+ String property,
+ String expectedName ) {
+ Name name = verify(nodePath, property, Name.class);
+ assertThat(name, is(context.getValueFactories().getNameFactory().create(expectedName)));
+ }
+
+ private void verifyString( String nodePath,
+ String property,
+ String expectedString ) {
+ String string = verify(nodePath, property, String.class);
+ assertThat(string, is(expectedString));
+ }
+}
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/InheritingXmlSequencerTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerHandlerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerHandlerTest.java (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerHandlerTest.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,580 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.sequencer.xml;
+
+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.Assert.fail;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import org.jboss.dna.common.stats.Stopwatch;
+import org.jboss.dna.common.text.Jsr283Encoder;
+import org.jboss.dna.common.text.TextDecoder;
+import org.jboss.dna.graph.JcrLexicon;
+import org.jboss.dna.graph.JcrNtLexicon;
+import org.jboss.dna.graph.properties.Name;
+import org.jboss.dna.graph.properties.NamespaceRegistry;
+import org.jboss.dna.graph.properties.Path;
+import org.jboss.dna.graph.properties.PathFactory;
+import org.jboss.dna.graph.properties.Property;
+import org.jboss.dna.graph.sequencers.MockSequencerContext;
+import org.jboss.dna.graph.sequencers.MockSequencerOutput;
+import org.jboss.dna.graph.sequencers.SequencerContext;
+import org.junit.Before;
+import org.junit.Test;
+import org.xml.sax.InputSource;
+import org.xml.sax.SAXException;
+import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
+
+/**
+ * @author Randall Hauch
+ */
+public class XmlSequencerHandlerTest {
+
+ private static final String NT_NAMESPACE_URI = "http://www.jcp.org/jcr/nt/1.0";
+
+ private XmlSequencerHandler handler;
+ private SequencerContext context;
+ private MockSequencerOutput output;
+ private TextDecoder decoder;
+ private Name primaryType;
+ private Name nameAttribute;
+ private XmlSequencer.AttributeScoping scoping;
+ private LinkedList<Path> pathsInCreationOrder;
+
+ @Before
+ public void beforeEach() {
+ context = new MockSequencerContext();
+ output = new MockSequencerOutput(context, true);
+ context.getNamespaceRegistry().register(JcrLexicon.Namespace.PREFIX, JcrLexicon.Namespace.URI);
+ context.getNamespaceRegistry().register("nt", NT_NAMESPACE_URI);
+ context.getNamespaceRegistry().register(DnaXmlLexicon.Namespace.PREFIX, DnaXmlLexicon.Namespace.URI);
+ context.getNamespaceRegistry().register(DnaDtdLexicon.Namespace.PREFIX, DnaDtdLexicon.Namespace.URI);
+ decoder = null;
+ nameAttribute = JcrLexicon.NAME;
+ primaryType = JcrNtLexicon.UNSTRUCTURED;
+ scoping = XmlSequencer.AttributeScoping.USE_DEFAULT_NAMESPACE;
+ handler = new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotConstructInstanceWhenGivenNullContext() {
+ context = null;
+ new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotConstructInstanceWhenGivenNullOutput() {
+ output = null;
+ new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ }
+
+ @Test
+ public void shouldUseDefaultDecoderIfNoneIsProvidedInConstructor() {
+ decoder = null;
+ handler = new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ }
+
+ @Test
+ public void shouldUseDecoderProvidedInConstructor() {
+ decoder = new Jsr283Encoder();
+ new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithoutNamespaces() throws IOException, SAXException {
+ parse("docWithoutNamespaces.xml");
+ // Check the generated content; note that the attribute name doesn't match, so the nodes don't get special names
+ assertDocumentNode();
+ assertNode("Cars");
+ assertNode("Cars/Hybrid");
+ assertNode("Cars/Hybrid/car[1]", "name=Toyota Prius", "maker=Toyota", "model=Prius");
+ assertNode("Cars/Hybrid/car[2]", "name=Toyota Highlander", "maker=Toyota", "model=Highlander");
+ assertNode("Cars/Hybrid/car[3]", "name=Nissan Altima", "maker=Nissan", "model=Altima");
+ assertNode("Cars/Sports");
+ assertNode("Cars/Sports/car[1]", "name=Aston Martin DB9", "maker=Aston Martin", "model=DB9");
+ assertNode("Cars/Sports/car[2]", "name=Infiniti G37", "maker=Infiniti", "model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithNamespaces() throws IOException, SAXException {
+ context.getNamespaceRegistry().register("c", "http://default.namespace.com");
+ parse("docWithNamespaces.xml");
+ // Check the generated content.
+ // Note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ // Also, the "jcr:name" attribute values use the default namespace, which is "c" in the registry
+ assertDocumentNode();
+ assertNode("c:Cars");
+ assertNode("c:Cars/c:Hybrid");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Prius", "c:maker=Toyota", "c:model=Prius");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Highlander", "c:maker=Toyota", "c:model=Highlander");
+ assertNode("c:Cars/c:Hybrid/c:Nissan Altima", "c:maker=Nissan", "c:model=Altima");
+ assertNode("c:Cars/c:Sports");
+ assertNode("c:Cars/c:Sports/c:Aston Martin DB9", "c:maker=Aston Martin", "c:model=DB9");
+ assertNode("c:Cars/c:Sports/c:Infiniti G37", "c:maker=Infiniti", "c:model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithNestedNamespaceDeclarations() throws IOException, SAXException {
+ context.getNamespaceRegistry().register("c", "http://default.namespace.com");
+ context.getNamespaceRegistry().register("i", "http://attributes.com");
+ parse("docWithNestedNamespaces.xml");
+ // Check the generated content; note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ assertDocumentNode();
+ assertNode("Cars");
+ assertNode("Cars/c:Hybrid");
+ assertNode("Cars/c:Hybrid/c:Toyota Prius", "c:maker=Toyota", "c:model=Prius");
+ assertNode("Cars/c:Hybrid/c:Toyota Highlander", "c:maker=Toyota", "c:model=Highlander");
+ assertNode("Cars/c:Hybrid/c:Nissan Altima", "c:maker=Nissan", "c:model=Altima");
+ assertNode("Cars/Sports");
+ assertNode("Cars/Sports/Aston Martin DB9", "i:maker=Aston Martin", "model=DB9");
+ assertNode("Cars/Sports/Infiniti G37", "i:maker=Infiniti", "model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithNamespacePrefixesThatDoNotMatchRegistry() throws IOException, SAXException {
+ context.getNamespaceRegistry().register("c", "http://default.namespace.com");
+ parse("docWithNamespaces.xml");
+ // Check the generated content; note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ assertDocumentNode();
+ assertNode("c:Cars");
+ assertNode("c:Cars/c:Hybrid");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Prius", "c:maker=Toyota", "c:model=Prius");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Highlander", "c:maker=Toyota", "c:model=Highlander");
+ assertNode("c:Cars/c:Hybrid/c:Nissan Altima", "c:maker=Nissan", "c:model=Altima");
+ assertNode("c:Cars/c:Sports");
+ assertNode("c:Cars/c:Sports/c:Aston Martin DB9", "c:maker=Aston Martin", "c:model=DB9");
+ assertNode("c:Cars/c:Sports/c:Infiniti G37", "c:maker=Infiniti", "c:model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithNamespacesThatAreNotYetInRegistry() throws IOException, SAXException {
+ NamespaceRegistry reg = context.getNamespaceRegistry();
+ reg.unregister(JcrLexicon.Namespace.URI);
+ reg.unregister(NT_NAMESPACE_URI);
+ // Verify the prefixes don't exist ...
+ assertThat(reg.getPrefixForNamespaceUri(JcrLexicon.Namespace.URI, false), is(nullValue()));
+ assertThat(reg.getPrefixForNamespaceUri(NT_NAMESPACE_URI, false), is(nullValue()));
+ assertThat(reg.getPrefixForNamespaceUri("http://default.namespace.com", false), is(nullValue()));
+ // Parse the XML file ...
+ parse("docWithNestedNamespaces.xml");
+ // Get the prefix for the default namespace ...
+ String c = reg.getPrefixForNamespaceUri("http://default.namespace.com", false);
+ String i = reg.getPrefixForNamespaceUri("http://attributes.com", false);
+ String d = reg.getPrefixForNamespaceUri(reg.getDefaultNamespaceUri(), false);
+ assertThat("Namespace not properly registered in primary registry", c, is(notNullValue()));
+ assertThat("Namespace not properly registered in primary registry", d, is(notNullValue()));
+ assertThat("Namespace not properly registered in primary registry", i, is(notNullValue()));
+ if (c.length() != 0) c = c + ":";
+ if (d.length() != 0) d = d + ":";
+ if (i.length() != 0) i = i + ":";
+ // Check the generated content; note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ assertDocumentNode();
+ assertNode(d + "Cars");
+ assertNode(d + "Cars/" + c + "Hybrid");
+ assertNode(d + "Cars/" + c + "Hybrid/" + c + "Toyota Prius", c + "maker=Toyota", c + "model=Prius");
+ assertNode(d + "Cars/" + c + "Hybrid/" + c + "Toyota Highlander", c + "maker=Toyota", c + "model=Highlander");
+ assertNode(d + "Cars/" + c + "Hybrid/" + c + "Nissan Altima", c + "maker=Nissan", c + "model=Altima");
+ assertNode(d + "Cars/" + d + "Sports");
+ assertNode(d + "Cars/" + d + "Sports/Aston Martin DB9", i + "maker=Aston Martin", "model=DB9");
+ assertNode(d + "Cars/" + d + "Sports/Infiniti G37", i + "maker=Infiniti", "model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentThatUsesNameAttribute() throws IOException, SAXException {
+ context.getNamespaceRegistry().register("c", "http://default.namespace.com");
+ parse("docWithNamespaces.xml");
+ // Check the generated content; note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ assertDocumentNode();
+ assertNode("c:Cars");
+ assertNode("c:Cars/c:Hybrid");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Prius", "c:maker=Toyota", "c:model=Prius");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Highlander", "c:maker=Toyota", "c:model=Highlander");
+ assertNode("c:Cars/c:Hybrid/c:Nissan Altima", "c:maker=Nissan", "c:model=Altima");
+ assertNode("c:Cars/c:Sports");
+ assertNode("c:Cars/c:Sports/c:Aston Martin DB9", "c:maker=Aston Martin", "c:model=DB9");
+ assertNode("c:Cars/c:Sports/c:Infiniti G37", "c:maker=Infiniti", "c:model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithoutDefaultNamespaceThatUsesNameAttribute() throws IOException, SAXException {
+ parse("docWithNamespacesWithoutDefault.xml");
+ // Check the generated content; note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ assertDocumentNode();
+ assertNode("Cars");
+ assertNode("Cars/Hybrid");
+ assertNode("Cars/Hybrid/Toyota Prius", "maker=Toyota", "model=Prius");
+ assertNode("Cars/Hybrid/Toyota Highlander", "maker=Toyota", "model=Highlander");
+ assertNode("Cars/Hybrid/Nissan Altima", "maker=Nissan", "model=Altima");
+ assertNode("Cars/Sports");
+ assertNode("Cars/Sports/Aston Martin DB9", "maker=Aston Martin", "model=DB9");
+ assertNode("Cars/Sports/Infiniti G37", "maker=Infiniti", "model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithoutDefaultNamespaceThatUsesNoNameAttribute() throws IOException, SAXException {
+ nameAttribute = null;
+ handler = new XmlSequencerHandler(output, context, nameAttribute, primaryType, decoder, scoping);
+ parse("docWithNamespacesWithoutDefault.xml");
+ // Check the generated content; note that the attribute name DOES match, so the nodes names come from "jcr:name" attribute
+ assertDocumentNode();
+ assertNode("Cars");
+ assertNode("Cars/Hybrid");
+ assertNode("Cars/Hybrid/car[1]", "maker=Toyota", "model=Prius");
+ assertNode("Cars/Hybrid/car[2]", "maker=Toyota", "model=Highlander");
+ assertNode("Cars/Hybrid/car[3]", "maker=Nissan", "model=Altima");
+ assertNode("Cars/Sports");
+ assertNode("Cars/Sports/car[1]", "maker=Aston Martin", "model=DB9");
+ assertNode("Cars/Sports/car[2]", "maker=Infiniti", "model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentThatContainsNoContent() throws IOException, SAXException {
+ parse("docWithOnlyRootElement.xml");
+ assertNode("", "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}document");
+ assertNode("Cars");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithXmlComments() throws IOException, SAXException {
+ context.getNamespaceRegistry().register("c", "http://default.namespace.com");
+ parse("docWithComments.xml");
+ assertDocumentNode();
+ assertNode("c:Cars");
+ assertComment("c:Cars/dnaxml:comment[1]", "This is a comment");
+ assertNode("c:Cars/c:Hybrid");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Prius", "c:maker=Toyota", "c:model=Prius");
+ assertNode("c:Cars/c:Hybrid/c:Toyota Highlander", "c:maker=Toyota", "c:model=Highlander");
+ assertNode("c:Cars/c:Hybrid/c:Nissan Altima", "c:maker=Nissan", "c:model=Altima");
+ assertComment("c:Cars/dnaxml:comment[2]", "This is another comment");
+ assertNode("c:Cars/c:Sports");
+ assertNode("c:Cars/c:Sports/c:Aston Martin DB9", "c:maker=Aston Martin", "c:model=DB9");
+ assertNode("c:Cars/c:Sports/c:Infiniti G37", "c:maker=Infiniti", "c:model=G37");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithDtdEntities() throws IOException, SAXException {
+ // Note the expected element content has leading and trailing whitespace removed, and any sequential
+ // whitespace is replaced with a single space
+ String longContent = "This is some long content that spans multiple lines and should span multiple "
+ + "calls to 'character(...)'. Repeating to make really long. This is some "
+ + "long content that spans multiple lines and should span multiple "
+ + "calls to 'character(...)'. Repeating to make really long. "
+ + "This is some long content that spans multiple lines and should span multiple "
+ + "calls to 'character(...)'. Repeating to make really long. This is some "
+ + "long content that spans multiple lines and should span multiple "
+ + "calls to 'character(...)'. Repeating to make really long.";
+
+ parse("docWithDtdEntities.xml");
+ assertDocumentNode("book", "-//OASIS//DTD DocBook XML V4.4//EN", "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd");
+ assertComment("dnaxml:comment", "Document comment");
+ assertEntity(1, "%RH-ENTITIES", null, "Common_Config/rh-entities.ent");
+ assertEntity(2, "versionNumber", "0.1");
+ assertEntity(3, "copyrightYear", "2008");
+ assertEntity(4, "copyrightHolder", "Red Hat Middleware, LLC.");
+ assertNode("book");
+ assertNode("book/bookinfo");
+ assertNode("book/bookinfo/title");
+ assertNode("book/bookinfo/title/dnaxml:elementContent",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=JBoss DNA");
+ assertNode("book/bookinfo/releaseinfo");
+ assertNode("book/bookinfo/releaseinfo/dnaxml:elementContent",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=&versionNumber;");
+ assertNode("book/bookinfo/productnumber");
+ assertNode("book/bookinfo/productnumber/dnaxml:elementContent",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=some text with &versionNumber;inside");
+ assertNode("book/bookinfo/abstract");
+ assertNode("book/bookinfo/abstract/dnaxml:elementContent",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=" + longContent);
+ assertNode("book/programlisting1");
+ assertNode("book/programlisting1/dnaxml:elementContent",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=<dependency> </dependency>");
+ assertNode("book/programlisting2");
+ assertNode("book/programlisting2/dnaxml:cData", "dnaxml:cDataContent=\n<dependency>\n</dependency>\n");
+ assertNode("book/programlisting3");
+ assertNode("book/programlisting3/dnaxml:elementContent[1]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=mixture of text and");
+ assertNode("book/programlisting3/dnaxml:cData", "dnaxml:cDataContent=\n<dependency>\n</dependency>\n");
+ assertNode("book/programlisting3/dnaxml:elementContent[2]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=and some text");
+ assertComment("book/programlisting3/dnaxml:comment", "comment in content");
+ assertNode("book/programlisting3/dnaxml:elementContent[3]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=after.");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithProcessingInstructions() throws IOException, SAXException {
+ parse("docWithProcessingInstructions.xml");
+ assertDocumentNode();
+ assertPI(1, "target", "content");
+ assertPI(2, "target2", "other stuff in the processing instruction");
+ assertNode("Cars");
+ assertComment("Cars/dnaxml:comment", "This is a comment");
+ assertNode("Cars/Hybrid");
+ assertNode("Cars/Hybrid/Toyota Prius");
+ assertNode("Cars/Sports");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithCDATA() throws IOException, SAXException {
+ String cdata = "\n" + "\n" + " import mx.events.ValidationResultEvent;\t\t\t\n"
+ + " private var vResult:ValidationResultEvent;\n" + "\t\t\t\n"
+ + " // Event handler to validate and format input.\n"
+ + " private function Format():void {\n" + " \n"
+ + " vResult = numVal.validate();\n" + "\n"
+ + " if (vResult.type==ValidationResultEvent.VALID) {\n"
+ + " var temp:Number=Number(priceUS.text); \n"
+ + " formattedUSPrice.text= usdFormatter.format(temp);\n"
+ + " }\n" + " \n" + " else {\n"
+ + " formattedUSPrice.text=\"\";\n" + " }\n" + " }\n"
+ + " ";
+ parse("docWithCDATA.xml");
+ assertDocumentNode();
+ assertComment("dnaxml:comment", "Simple example to demonstrate the CurrencyFormatter.");
+ assertNode("mx:Application");
+ assertNode("mx:Application/mx:Script");
+ assertCdata("mx:Application/mx:Script/dnaxml:cData", cdata);
+ // Now there's an element that contains a mixture of regular element content, CDATA content, and comments
+ assertNode("mx:Application/programlisting3");
+ assertNode("mx:Application/programlisting3/dnaxml:elementContent[1]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=mixture of text and");
+ assertNode("mx:Application/programlisting3/dnaxml:cData",
+ "dnaxml:cDataContent=\n<dependency>entities like > are not replaced in a CDATA\n</dependency>\n");
+ assertNode("mx:Application/programlisting3/dnaxml:elementContent[2]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=and some text");
+ assertComment("mx:Application/programlisting3/dnaxml:comment", "comment in content");
+ assertNode("mx:Application/programlisting3/dnaxml:elementContent[3]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}elementContent",
+ "dnaxml:elementContent=after.");
+ // Now the final element
+ assertNode("mx:Application/mx:NumberValidator",
+ "id=numVal",
+ "source={priceUS}",
+ "property=text",
+ "allowNegative=true",
+ "domain=real");
+ assertNoMoreNodes();
+ }
+
+ @Test
+ public void shouldParseXmlDocumentWithDtd() throws IOException, SAXException {
+ parse("master.xml");
+ assertDocumentNode("book", "-//OASIS//DTD DocBook XML V4.4//EN", "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd");
+ }
+
+ protected void assertNoMoreNodes() {
+ if (!pathsInCreationOrder.isEmpty()) {
+ fail("Extra nodes were not expected:" + pathsInCreationOrder);
+ }
+ }
+
+ protected void assertNode( String path,
+ String... properties ) {
+ // Append an index to the path if not there ...
+ if (path.length() != 0 && !path.endsWith("]")) {
+ path = path + "[1]";
+ }
+
+ // Create the expected path ...
+ PathFactory factory = context.getValueFactories().getPathFactory();
+ Path expectedPath = null;
+ if (path.length() == 0) {
+ expectedPath = factory.createRelativePath();
+ } else {
+ expectedPath = factory.create(path);
+ }
+
+ // Pop the next node and compare ...
+ Path next = this.pathsInCreationOrder.removeFirst();
+ assertThat(next, is(expectedPath));
+
+ // Create the list of properties ...
+ Map<Name, Property> expectedProperties = new HashMap<Name, Property>();
+ for (String propertyString : properties) {
+ String[] strings = propertyString.split("=");
+ if (strings.length < 2) continue;
+ Name name = context.getValueFactories().getNameFactory().create(strings[0]);
+ Object[] values = new Object[strings.length - 1];
+ for (int i = 1; i != strings.length; ++i) {
+ values[i - 1] = strings[i];
+ }
+ Property property = context.getPropertyFactory().create(name, values);
+ expectedProperties.put(name, property);
+ }
+ // If properties does not contain a primaryType property, then add the default ...
+ if (!expectedProperties.containsKey(JcrLexicon.PRIMARY_TYPE)) {
+ Property property = context.getPropertyFactory().create(JcrLexicon.PRIMARY_TYPE, primaryType);
+ expectedProperties.put(property.getName(), property);
+ }
+
+ // Now get the Properties for this path ...
+ Map<Name, Property> actualProperties = output.getProperties(expectedPath);
+ assertThat("node not found", actualProperties, is(notNullValue()));
+ for (Property actual : actualProperties.values()) {
+ Property expected = expectedProperties.remove(actual.getName());
+ assertThat("unexpected actual property: " + actual, expected, is(notNullValue()));
+ assertThat(actual, is(expected));
+ }
+ if (!expectedProperties.isEmpty()) {
+ StringBuilder msg = new StringBuilder("missing actual properties: ");
+ boolean isFirst = true;
+ for (Property expected : expectedProperties.values()) {
+ if (!isFirst) msg.append(", ");
+ else isFirst = false;
+ msg.append(expected.getName());
+ }
+ assertThat(msg.toString(), expectedProperties.isEmpty(), is(true));
+ }
+ }
+
+ protected void assertComment( String path,
+ String comment ) {
+ assertNode(path, "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}comment", "dnaxml:commentContent=" + comment.trim());
+ }
+
+ protected void assertCdata( String path,
+ String content ) {
+ // Append an index to the path if not there ...
+ if (path.length() != 0 && !path.endsWith("]")) {
+ path = path + "[1]";
+ }
+ PathFactory factory = context.getValueFactories().getPathFactory();
+ Path expectedPath = factory.create("/" + path);
+
+ // Pop the next node and compare ...
+ Path next = this.pathsInCreationOrder.removeFirst();
+ assertThat(next, is(expectedPath));
+
+ // There should be a single property ...
+ Property actualPrimaryType = output.getProperty(expectedPath, JcrLexicon.PRIMARY_TYPE);
+ assertThat(actualPrimaryType.getValues().next(), is((Object)JcrNtLexicon.UNSTRUCTURED));
+ Property actual = output.getProperty(expectedPath, DnaXmlLexicon.CDATA_CONTENT);
+ assertThat("expected one CDATA property", actual, is(notNullValue()));
+ Property expected = context.getPropertyFactory().create(DnaXmlLexicon.CDATA_CONTENT, content);
+ assertThat("CDATA content differed", actual, is(expected));
+ }
+
+ protected void assertDocumentNode() {
+ assertNode("", "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}document");
+ }
+
+ protected void assertDocumentNode( String name,
+ String publicId,
+ String systemId ) {
+ assertNode("",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}document",
+ "dnadtd:name=" + name,
+ "dnadtd:publicId=" + publicId,
+ "dnadtd:systemId=" + systemId);
+ }
+
+ protected void assertEntity( int index,
+ String entityName,
+ String value ) {
+ String path = "dnadtd:entity[" + index + "]";
+ assertNode(path, "jcr:primaryType={http://www.jboss.org/dna/dtd/1.0}entity", "dnadtd:name=" + entityName, "dnadtd:value="
+ + value);
+ }
+
+ protected void assertEntity( int index,
+ String entityName,
+ String publicId,
+ String systemId ) {
+ String path = "dnadtd:entity[" + index + "]";
+ if (publicId != null) {
+ assertNode(path,
+ "jcr:primaryType={http://www.jboss.org/dna/dtd/1.0}entity",
+ "dnadtd:name=" + entityName,
+ "dnadtd:publicId=" + publicId,
+ "dnadtd:systemId=" + systemId);
+ } else {
+ assertNode(path,
+ "jcr:primaryType={http://www.jboss.org/dna/dtd/1.0}entity",
+ "dnadtd:name=" + entityName,
+ "dnadtd:systemId=" + systemId);
+ }
+ }
+
+ protected void assertPI( int index,
+ String target,
+ String data ) {
+ assertNode("dnaxml:processingInstruction[" + index + "]",
+ "jcr:primaryType={http://www.jboss.org/dna/xml/1.0}processingInstruction",
+ "dnaxml:target=" + target,
+ "dnaxml:processingInstructionContent=" + data);
+ }
+
+ protected void parse( String relativePathToXmlFile ) throws IOException, SAXException {
+ Stopwatch sw = new Stopwatch();
+ sw.start();
+ InputStream stream = getClass().getClassLoader().getResourceAsStream(relativePathToXmlFile);
+ try {
+ XMLReader reader = XMLReaderFactory.createXMLReader();
+ reader.setContentHandler(handler);
+ reader.setErrorHandler(handler);
+ // Ensure handler acting as entity resolver 2
+ reader.setProperty(XmlSequencer.DECL_HANDLER_FEATURE, handler);
+ // Ensure handler acting as lexical handler
+ reader.setProperty(XmlSequencer.LEXICAL_HANDLER_FEATURE, handler);
+ // Ensure handler acting as entity resolver 2
+ XmlSequencer.setFeature(reader, XmlSequencer.ENTITY_RESOLVER_2_FEATURE, true);
+ // Prevent loading of external DTDs
+ XmlSequencer.setFeature(reader, XmlSequencer.LOAD_EXTERNAL_DTDS_FEATURE, false);
+ // Prevent the resolving of DTD entities into fully-qualified URIS
+ XmlSequencer.setFeature(reader, XmlSequencer.RESOLVE_DTD_URIS_FEATURE, false);
+ reader.parse(new InputSource(stream));
+ } finally {
+ if (stream != null) stream.close();
+ sw.stop();
+ System.out.println("Parsing: " + sw);
+ }
+ pathsInCreationOrder = new LinkedList<Path>(output.getOrderOfCreation());
+ }
+}
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerHandlerTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java 2008-11-10 23:57:53 UTC (rev 618)
+++ trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java 2008-11-12 04:31:14 UTC (rev 619)
@@ -99,13 +99,14 @@
verifyDocument(xml1);
verifyName(COMMENT + "[1]", "jcr:primaryType", COMMENT);
String text = verify(COMMENT + "[1]", COMMENT_CONTENT, String.class);
- assertThat(text.startsWith("\n Licensed to the Apache Software Foundation (ASF)"), is(true));
- assertThat(text.endsWith(" limitations under the License.\n"), is(true));
+ assertThat(text.startsWith("Licensed to the Apache Software Foundation (ASF)"), is(true));
+ assertThat(text.indexOf('\n') > 0, is(true));
+ assertThat(text.endsWith(" limitations under the License."), is(true));
verifyString("/", DTD_NAME, "Repository");
verifyString("/", DTD_PUBLIC_ID, "-//The Apache Software Foundation//DTD Jackrabbit 1.2//EN");
verifyString("/", DTD_SYSTEM_ID, "http://jackrabbit.apache.org/dtd/repository-1.2.dtd");
verifyName(COMMENT + "[2]", "jcr:primaryType", COMMENT);
- verifyString(COMMENT + "[2]", COMMENT_CONTENT, " Example Repository Configuration File ");
+ verifyString(COMMENT + "[2]", COMMENT_CONTENT, "Example Repository Configuration File");
verifyName("Repository[1]", "jcr:primaryType", "nt:unstructured");
verifyName("Repository[1]/" + COMMENT + "[1]", "jcr:primaryType", COMMENT);
}
@@ -114,9 +115,9 @@
public void shouldHandleNamespaces() throws IOException {
verifyDocument(xml2);
verifyName("book[1]/bookinfo[1]/xi:include[1]", "jcr:primaryType", "nt:unstructured");
- verifyString("book[1]/bookinfo[1]/xi:include[1]", "xi:href", "Author_Group.xml");
+ verifyString("book[1]/bookinfo[1]/xi:include[1]", "href", "Author_Group.xml");
verifyName("book[1]/bookinfo[1]/xi:include[2]", "jcr:primaryType", "nt:unstructured");
- verifyString("book[1]/bookinfo[1]/xi:include[2]", "xi:href", "Legal_Notice.xml");
+ verifyString("book[1]/bookinfo[1]/xi:include[2]", "href", "Legal_Notice.xml");
}
@Test
@@ -175,18 +176,19 @@
@Test
public void shouldSequenceXsds() throws IOException {
+ sequencer.setAttributeScoping(XmlSequencer.AttributeScoping.INHERIT_ELEMENT_NAMESPACE);
verifyDocument(xsd);
- verifyName("xs:schema[1]", "jcr:primaryType", "nt:unstructured");
- verifyString("xs:schema[1]", "xs:targetNamespace", "http://ns.adobe.com/air/application/1.0");
- verifyString("xs:schema[1]", "xs:elementFormDefault", "qualified");
- verifyName("xs:schema[1]/xs:element[1]", "jcr:primaryType", "nt:unstructured");
- verifyString("xs:schema[1]/xs:element[1]", "xs:name", "application");
+ verifyName("xs:schema", "jcr:primaryType", "nt:unstructured");
+ verifyString("xs:schema", "xs:targetNamespace", "http://ns.adobe.com/air/application/1.0");
+ verifyString("xs:schema", "xs:elementFormDefault", "qualified");
+ verifyName("xs:schema/xs:element", "jcr:primaryType", "nt:unstructured");
+ verifyString("xs:schema/xs:element", "xs:name", "application");
}
private <T> T verify( String nodePath,
String property,
Class<T> expectedClass ) {
- Object[] values = output.getPropertyValues(nodePath.length() == 0 ? "." : nodePath, property);
+ Object[] values = output.getPropertyValues(nodePath.length() == 0 ? "" : nodePath, property);
assertThat(values, notNullValue());
assertThat(values.length, is(1));
Object value = values[0];
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithCDATA.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithCDATA.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithCDATA.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Simple example to demonstrate the CurrencyFormatter. -->
+<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
+
+ <mx:Script>
+ <![CDATA[
+
+ import mx.events.ValidationResultEvent;
+ private var vResult:ValidationResultEvent;
+
+ // Event handler to validate and format input.
+ private function Format():void {
+
+ vResult = numVal.validate();
+
+ if (vResult.type==ValidationResultEvent.VALID) {
+ var temp:Number=Number(priceUS.text);
+ formattedUSPrice.text= usdFormatter.format(temp);
+ }
+
+ else {
+ formattedUSPrice.text="";
+ }
+ }
+ ]]>
+ </mx:Script>
+ <programlisting3>mixture of text and <![CDATA[
+<dependency>entities like > are not replaced in a CDATA
+</dependency>
+]]> and some text <!-- comment in content -->after.</programlisting3>
+
+ <mx:NumberValidator id="numVal" source="{priceUS}" property="text"
+ allowNegative="true" domain="real"/>
+</mx:Application>
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithCDATA.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithComments.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithComments.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithComments.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Cars xmlns="http://default.namespace.com" xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <!-- This is a comment -->
+ <Hybrid>
+ <car jcr:name="Toyota Prius" maker="Toyota" model="Prius"/>
+ <car jcr:name="Toyota Highlander" maker="Toyota" model="Highlander"/>
+ <car jcr:name="Nissan Altima" maker="Nissan" model="Altima"/>
+ </Hybrid>
+ <!--
+ This is another comment
+ -->
+ <Sports>
+ <car jcr:name="Aston Martin DB9" maker="Aston Martin" model="DB9"/>
+ <car jcr:name="Infiniti G37" maker="Infiniti" model="G37" />
+ </Sports>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithComments.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithDtdEntities.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithDtdEntities.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithDtdEntities.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Document comment -->
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN" "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd" [
+<!ENTITY % RH-ENTITIES SYSTEM "Common_Config/rh-entities.ent">
+<!ENTITY versionNumber "0.1">
+<!ENTITY copyrightYear "2008">
+<!ENTITY copyrightHolder "Red Hat Middleware, LLC.">]>
+<book>
+ <bookinfo>
+ <title>JBoss DNA</title>
+ <releaseinfo>&versionNumber;</releaseinfo>
+ <productnumber>some text with &versionNumber;inside
+ </productnumber>
+ <abstract>
+ This is some long content that spans multiple lines and should span multiple calls to 'character(...)'. Repeating to make really long. This is some
+long content that spans multiple lines and should span multiple
+calls to 'character(...)'. Repeating to make really long. This is some long content that spans multiple lines and should span multiple calls to 'character(...)'. Repeating to make really long. This is some long content that spans multiple lines and should span multiple calls to 'character(...)'. Repeating to make really long.
+ </abstract>
+ </bookinfo>
+ <programlisting1>
+<dependency>
+</dependency>
+ </programlisting1>
+ <programlisting2><![CDATA[
+<dependency>
+</dependency>
+]]></programlisting2>
+ <programlisting3>mixture of text and <![CDATA[
+<dependency>
+</dependency>
+]]> and some text <!-- comment in content -->after.</programlisting3>
+</book>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithDtdEntities.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespaces.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespaces.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespaces.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Cars xmlns="http://default.namespace.com" xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <Hybrid>
+ <car jcr:name="Toyota Prius" maker="Toyota" model="Prius"/>
+ <car jcr:name="Toyota Highlander" maker="Toyota" model="Highlander"/>
+ <car jcr:name="Nissan Altima" maker="Nissan" model="Altima"/>
+ </Hybrid>
+ <Sports>
+ <car jcr:name="Aston Martin DB9" maker="Aston Martin" model="DB9"/>
+ <car jcr:name="Infiniti G37" maker="Infiniti" model="G37" />
+ </Sports>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespaces.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespacesWithoutDefault.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespacesWithoutDefault.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespacesWithoutDefault.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Cars xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <Hybrid>
+ <car jcr:name="Toyota Prius" maker="Toyota" model="Prius"/>
+ <car jcr:name="Toyota Highlander" maker="Toyota" model="Highlander"/>
+ <car jcr:name="Nissan Altima" maker="Nissan" model="Altima"/>
+ </Hybrid>
+ <Sports>
+ <car jcr:name="Aston Martin DB9" maker="Aston Martin" model="DB9"/>
+ <car jcr:name="Infiniti G37" maker="Infiniti" model="G37" />
+ </Sports>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNamespacesWithoutDefault.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNestedNamespaces.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNestedNamespaces.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNestedNamespaces.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Cars xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <Hybrid xmlns="http://default.namespace.com">
+ <car jcr:name="Toyota Prius" maker="Toyota" model="Prius"/>
+ <car jcr:name="Toyota Highlander" maker="Toyota" model="Highlander"/>
+ <car jcr:name="Nissan Altima" maker="Nissan" model="Altima"/>
+ </Hybrid>
+ <Sports xmlns:jcr2="http://www.jcp.org/jcr/1.0" xmlns:info="http://attributes.com">
+ <car jcr2:name="Aston Martin DB9" info:maker="Aston Martin" model="DB9"/>
+ <car jcr:name="Infiniti G37" info:maker="Infiniti" model="G37" />
+ </Sports>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithNestedNamespaces.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithOnlyRootElement.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithOnlyRootElement.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithOnlyRootElement.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Cars>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithOnlyRootElement.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithProcessingInstructions.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithProcessingInstructions.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithProcessingInstructions.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<?target content ?>
+<?target2 other stuff in the processing instruction ?>
+<Cars xmlns:jcr="http://www.jcp.org/jcr/1.0">
+ <!-- This is a comment -->
+ <Hybrid>
+ <car jcr:name="Toyota Prius"/>
+ </Hybrid>
+ <Sports>
+ </Sports>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithProcessingInstructions.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithoutNamespaces.xml
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/resources/docWithoutNamespaces.xml (rev 0)
+++ trunk/extensions/dna-sequencer-xml/src/test/resources/docWithoutNamespaces.xml 2008-11-12 04:31:14 UTC (rev 619)
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Cars>
+ <Hybrid>
+ <car name="Toyota Prius" maker="Toyota" model="Prius"/>
+ <car name="Toyota Highlander" maker="Toyota" model="Highlander"/>
+ <car name="Nissan Altima" maker="Nissan" model="Altima"/>
+ </Hybrid>
+ <Sports>
+ <car name="Aston Martin DB9" maker="Aston Martin" model="DB9"/>
+ <car name="Infiniti G37" maker="Infiniti" model="G37" />
+ </Sports>
+</Cars>
\ No newline at end of file
Property changes on: trunk/extensions/dna-sequencer-xml/src/test/resources/docWithoutNamespaces.xml
___________________________________________________________________
Name: svn:mime-type
+ text/plain
17 years, 2 months
DNA SVN: r618 - in trunk/dna-graph/src: main/java/org/jboss/dna/graph/requests/processor and 1 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-10 18:57:53 -0500 (Mon, 10 Nov 2008)
New Revision: 618
Modified:
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CompositeRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/Request.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/processor/RequestProcessor.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/AbstractRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CompositeRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CopyBranchRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/DeleteBranchRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/MoveBranchRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllChildrenRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllPropertiesRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBlockOfChildrenRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBranchRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadNodeRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadPropertyRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RemovePropertiesRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RenameNodeRequestTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/UpdatePropertiesRequestTest.java
Log:
DNA-217 - Connector SPI should have protocol for cancelling operations
http://jira.jboss.com/jira/browse/DNA-217
Added to Request a method isCancelled():boolean to check whether the request was cancelled, and another method "cancel():void" to mark a request as cancelled. Also added to the CompositeRequest the ability to mark the composite (or any contained request) as cancelled, but to have all other requests (including the composite) be also cancelled. This is done through a single AtomicBoolean instance shared amongst the composite and contained requests.
Also added tests to verify the desired behavior.
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CompositeRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CompositeRequest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CompositeRequest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -26,10 +26,17 @@
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.dna.common.util.CheckArg;
/**
- * A request that wraps multiple other requests.
+ * A request that wraps multiple other requests, allowing multiple requests to be treated as a single request.
+ * <p>
+ * Note that {@link #isCancelled()} and {@link #cancel()} apply to all requests contained by the composite request. In other
+ * words, cancelling this request immediately marks all contained requests as cancelled. However, cancelling any request in the
+ * request has the effect of cancelling all other requests in the composite, including the composite. (This is implemented by
+ * having all {@link Request} objects in the composite share the same cancelled flag object.)
+ * </p>
*
* @author Randall Hauch
*/
@@ -187,8 +194,13 @@
* @param requests the modifiable list of requests; may not be null
* @param readOnly true if all of the requests are {@link Request#isReadOnly() read-only}
*/
- protected CompositeRequest( List<? extends Request> requests,
- boolean readOnly ) {
+ /*package*/CompositeRequest( List<? extends Request> requests,
+ boolean readOnly ) {
+ // Iterate through the requests and set the cancelled flag of each request to this object's flag ...
+ final AtomicBoolean flag = super.getCancelledFlag();
+ for (Request request : requests) {
+ request.setCancelledFlag(flag);
+ }
this.requests = Collections.unmodifiableList(requests);
this.readOnly = readOnly;
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -73,6 +73,7 @@
public RemovePropertiesRequest( Location from,
Iterable<Name> propertyNames ) {
CheckArg.isNotNull(from, "from");
+ CheckArg.isNotNull(propertyNames, "propertyNames");
this.from = from;
Set<Name> names = new HashSet<Name>();
for (Name name : propertyNames) {
@@ -92,6 +93,7 @@
public RemovePropertiesRequest( Location from,
Iterator<Name> propertyNames ) {
CheckArg.isNotNull(from, "from");
+ CheckArg.isNotNull(propertyNames, "propertyNames");
this.from = from;
Set<Name> names = new HashSet<Name>();
while (propertyNames.hasNext()) {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/Request.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/Request.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/Request.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -22,6 +22,7 @@
package org.jboss.dna.graph.requests;
import java.io.Serializable;
+import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.dna.graph.connectors.RepositoryConnection;
/**
@@ -34,7 +35,12 @@
private static final long serialVersionUID = 1L;
private Throwable error;
+ private AtomicBoolean cancelled;
+ protected Request() {
+ this.cancelled = new AtomicBoolean(false);
+ }
+
/**
* Set the error for this request.
*
@@ -63,10 +69,61 @@
}
/**
+ * Check whether this request has been cancelled. Although it is a recommendation that the result of this method be followed
+ * wherever possible, it is not required to immediately stop processing the request if this method returns <code>true</code>.
+ * For example, if processing is almost complete, it may be appropriate to simply finish processing the request.
+ * <p>
+ * This method is safe to be called by different threads.
+ * </p>
+ *
+ * @return true if this request has been cancelled, or false otherwise.
+ */
+ public boolean isCancelled() {
+ return cancelled.get();
+ }
+
+ /**
+ * Set the cancelled state of this request. All requests are initially marked as not cancelled. Note that this is designed so
+ * that the same {@link AtomicBoolean} instance can be passed to multiple requests, allowing a single flag to dictate the
+ * cancelled state of all of those requests.
+ * <p>
+ * So, by default, each request should already be set up to not be cancelled, so for most cases this method does not need to
+ * be called at all. This method should be called when this flag is to be shared among multiple requests, usually when the
+ * requests are being initialized or assembled.
+ * </p>
+ *
+ * @param cancelled the new (potentially shared) cancelled state for the request; may not be null
+ */
+ /*package*/void setCancelledFlag( AtomicBoolean cancelled ) {
+ assert cancelled != null;
+ this.cancelled = cancelled;
+ }
+
+ /**
+ * Get this request's cancelled flag.
+ *
+ * @return the cancelled flag
+ */
+ /*package*/AtomicBoolean getCancelledFlag() {
+ return cancelled;
+ }
+
+ /**
+ * Cancel this request. After this method is called, the {@link #isCancelled() cancellation flag} is set, and any current or
+ * future processing of the request may be affected by the cancellation. (Note however, that processors may choose to not
+ * respect this request.)
+ * <p>
+ * This method is safe to be called by different threads.
+ * </p>
+ */
+ public void cancel() {
+ this.cancelled.set(true);
+ }
+
+ /**
* Return whether this request only reads information.
*
* @return true if this request reads information, or false if it requests that the repository content be changed in some way
*/
public abstract boolean isReadOnly();
-
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -70,6 +70,7 @@
public UpdatePropertiesRequest( Location on,
Iterable<Property> properties ) {
CheckArg.isNotNull(on, "on");
+ CheckArg.isNotNull(properties, "properties");
this.on = on;
List<Property> props = new LinkedList<Property>();
for (Property property : properties) {
@@ -89,6 +90,7 @@
public UpdatePropertiesRequest( Location on,
Iterator<Property> properties ) {
CheckArg.isNotNull(on, "on");
+ CheckArg.isNotNull(properties, "properties");
this.on = on;
List<Property> props = new LinkedList<Property>();
while (properties.hasNext()) {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/processor/RequestProcessor.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/processor/RequestProcessor.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/processor/RequestProcessor.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -120,6 +120,7 @@
*/
public void process( Request request ) {
if (request == null) return;
+ if (request.isCancelled()) return;
if (request instanceof CompositeRequest) {
process((CompositeRequest)request);
} else if (request instanceof CopyBranchRequest) {
@@ -166,6 +167,7 @@
Throwable firstError = null;
for (Request embedded : request) {
assert embedded != null;
+ if (embedded.isCancelled()) return;
process(embedded);
if (embedded.hasError()) {
if (numberOfErrors == 0) firstError = embedded.getError();
@@ -285,6 +287,7 @@
// Now read the locations ...
boolean first = true;
while (locationsToRead.peek() != null) {
+ if (request.isCancelled()) return;
LocationWithDepth read = locationsToRead.poll();
// Check the depth ...
@@ -353,6 +356,7 @@
request.setError(readChildren.getError());
return;
}
+ if (request.isCancelled()) return;
// Now, copy all of the results into the submitted request ...
for (Property property : readProperties) {
request.addProperty(property);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/AbstractRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/AbstractRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/AbstractRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -21,6 +21,8 @@
*/
package org.jboss.dna.graph.requests;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
import java.util.UUID;
import org.jboss.dna.graph.BasicExecutionContext;
import org.jboss.dna.graph.ExecutionContext;
@@ -29,6 +31,7 @@
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.properties.Property;
import org.junit.Before;
+import org.junit.Test;
/**
* @author Randall Hauch
@@ -84,4 +87,20 @@
protected Name createName( String name ) {
return context.getValueFactories().getNameFactory().create(name);
}
+
+ protected abstract Request createRequest();
+
+ @Test
+ public void shouldNotBeCancelledByDefault() {
+ Request request = createRequest();
+ assertThat(request.isCancelled(), is(false));
+ }
+
+ @Test
+ public void shouldBeCancelledAfterCallingCancel() {
+ Request request = createRequest();
+ assertThat(request.isCancelled(), is(false));
+ request.cancel();
+ assertThat(request.isCancelled(), is(true));
+ }
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CompositeRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CompositeRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CompositeRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -53,6 +53,39 @@
requestList = Arrays.asList(requests);
}
+ @Override
+ protected Request createRequest() {
+ return CompositeRequest.with(requests);
+ }
+
+ @Test
+ public void shouldCancelAllNestedRequestsAndCompositeAfterCallingCancel() {
+ Request composite = CompositeRequest.with(requests);
+ assertThat(composite.isCancelled(), is(false));
+ for (Request request : requests) {
+ assertThat(request.isCancelled(), is(false));
+ }
+ composite.cancel();
+ assertThat(composite.isCancelled(), is(true));
+ for (Request request : requests) {
+ assertThat(request.isCancelled(), is(true));
+ }
+ }
+
+ @Test
+ public void shouldCancelAllNestedRequestsAndCompositeAfterCallingCancelOnNestedRequest() {
+ Request composite = CompositeRequest.with(requests);
+ assertThat(composite.isCancelled(), is(false));
+ for (Request request : requests) {
+ assertThat(request.isCancelled(), is(false));
+ }
+ requests[0].cancel();
+ assertThat(composite.isCancelled(), is(true));
+ for (Request request : requests) {
+ assertThat(request.isCancelled(), is(true));
+ }
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingCompositeRequestWithNullRequest() {
CompositeRequest.with((Request)null);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CopyBranchRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CopyBranchRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/CopyBranchRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -41,6 +41,11 @@
super.beforeEach();
}
+ @Override
+ protected Request createRequest() {
+ return new CopyBranchRequest(validPathLocation1, validPathLocation2);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
new CopyBranchRequest(null, validPathLocation);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/DeleteBranchRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/DeleteBranchRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/DeleteBranchRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -41,14 +41,14 @@
super.beforeEach();
}
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ @Override
+ protected Request createRequest() {
+ return new DeleteBranchRequest(validPathLocation1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullFromLocation() {
+ new DeleteBranchRequest(null);
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/MoveBranchRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/MoveBranchRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/MoveBranchRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -41,14 +41,19 @@
super.beforeEach();
}
+ @Override
+ protected Request createRequest() {
+ return new MoveBranchRequest(validPathLocation1, validPathLocation2);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ new MoveBranchRequest(null, validPathLocation);
}
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ new MoveBranchRequest(validPathLocation, null);
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllChildrenRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllChildrenRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllChildrenRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -42,14 +42,14 @@
super.beforeEach();
}
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ @Override
+ protected Request createRequest() {
+ return new ReadAllChildrenRequest(validPathLocation1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullFromLocation() {
+ new ReadAllChildrenRequest(null);
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllPropertiesRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllPropertiesRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadAllPropertiesRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -42,14 +42,14 @@
super.beforeEach();
}
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ @Override
+ protected Request createRequest() {
+ return new ReadAllPropertiesRequest(validPathLocation1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullFromLocation() {
+ new ReadAllPropertiesRequest(null);
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBlockOfChildrenRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBlockOfChildrenRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBlockOfChildrenRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -41,16 +41,26 @@
super.beforeEach();
}
+ @Override
+ protected Request createRequest() {
+ return new ReadBlockOfChildrenRequest(validPathLocation1, 2, 10);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ new ReadBlockOfChildrenRequest(null, 0, 1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNegativeStartingIndex() {
+ new ReadBlockOfChildrenRequest(validPathLocation1, -1, 1);
}
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithNegativeCount() {
+ new ReadBlockOfChildrenRequest(validPathLocation1, 1, -1);
+ }
+
@Test
public void shouldCreateValidRequestWithValidLocation() {
request = new ReadBlockOfChildrenRequest(validPathLocation1, 2, 10);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBranchRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBranchRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadBranchRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -41,14 +41,14 @@
super.beforeEach();
}
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ @Override
+ protected Request createRequest() {
+ return new ReadBranchRequest(validPathLocation1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullFromLocation() {
+ new ReadBranchRequest(null);
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadNodeRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadNodeRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadNodeRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -42,6 +42,11 @@
super.beforeEach();
}
+ @Override
+ protected Request createRequest() {
+ return new ReadNodeRequest(validPathLocation1);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
new CopyBranchRequest(null, validPathLocation);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadPropertyRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadPropertyRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/ReadPropertyRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -47,13 +47,18 @@
validPropertyName = validProperty.getName();
}
+ @Override
+ protected Request createRequest() {
+ return new ReadPropertyRequest(validPathLocation1, validPropertyName);
+ }
+
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ public void shouldNotAllowCreatingRequestWithNullLocation() {
+ new ReadPropertyRequest(null, validPropertyName);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
+ public void shouldNotAllowCreatingRequestWithNullPropertyName() {
new CopyBranchRequest(validPathLocation, null);
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RemovePropertiesRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RemovePropertiesRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RemovePropertiesRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -27,6 +27,7 @@
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItems;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import org.jboss.dna.graph.properties.Name;
import org.junit.Before;
@@ -51,16 +52,46 @@
validPropertyName3 = createName("foo3");
}
+ @Override
+ protected Request createRequest() {
+ return new RemovePropertiesRequest(validPathLocation1, validPropertyName1);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ new RemovePropertiesRequest(null, validPropertyName1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullPropertyName() {
+ new RemovePropertiesRequest(validPathLocation, (Name[])null);
}
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithEmptyPropertyNameArray() {
+ new RemovePropertiesRequest(validPathLocation, new Name[] {});
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithNullPropertyNameIterator() {
+ new RemovePropertiesRequest(validPathLocation, (Iterator<Name>)null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithEmptyPropertyNameIterator() {
+ new RemovePropertiesRequest(validPathLocation, new ArrayList<Name>().iterator());
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithNullPropertyNameIterable() {
+ new RemovePropertiesRequest(validPathLocation, (Iterable<Name>)null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithEmptyPropertyNameIterable() {
+ new RemovePropertiesRequest(validPathLocation, new ArrayList<Name>());
+ }
+
@Test
public void shouldCreateValidRequestWithValidLocationAndValidPropertyName() {
request = new RemovePropertiesRequest(validPathLocation1, validPropertyName1);
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RenameNodeRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RenameNodeRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/RenameNodeRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -44,14 +44,19 @@
newName = createName("SomethingElse");
}
+ @Override
+ protected Request createRequest() {
+ return new RenameNodeRequest(validPathLocation1, newName);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ new RenameNodeRequest(null, newName);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullNewName() {
+ new RenameNodeRequest(validPathLocation1, null);
}
@Test
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/UpdatePropertiesRequestTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/UpdatePropertiesRequestTest.java 2008-11-10 20:21:55 UTC (rev 617)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/requests/UpdatePropertiesRequestTest.java 2008-11-10 23:57:53 UTC (rev 618)
@@ -27,6 +27,7 @@
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItems;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.List;
import org.jboss.dna.graph.properties.Property;
import org.junit.Before;
@@ -45,16 +46,46 @@
super.beforeEach();
}
+ @Override
+ protected Request createRequest() {
+ return new UpdatePropertiesRequest(validPathLocation1, validProperty1);
+ }
+
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowCreatingRequestWithNullFromLocation() {
- new CopyBranchRequest(null, validPathLocation);
+ new UpdatePropertiesRequest(null, validProperty1);
}
@Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowCreatingRequestWithNullToLocation() {
- new CopyBranchRequest(validPathLocation, null);
+ public void shouldNotAllowCreatingRequestWithNullPropertyName() {
+ new UpdatePropertiesRequest(validPathLocation, (Property[])null);
}
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithEmptyPropertyNameArray() {
+ new UpdatePropertiesRequest(validPathLocation, new Property[] {});
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithNullPropertyNameIterator() {
+ new UpdatePropertiesRequest(validPathLocation, (Iterator<Property>)null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithEmptyPropertyNameIterator() {
+ new UpdatePropertiesRequest(validPathLocation, new ArrayList<Property>().iterator());
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithNullPropertyNameIterable() {
+ new UpdatePropertiesRequest(validPathLocation, (Iterable<Property>)null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCreatingRequestWithEmptyPropertyNameIterable() {
+ new UpdatePropertiesRequest(validPathLocation, new ArrayList<Property>());
+ }
+
@Test
public void shouldCreateValidRequestWithValidLocationAndValidProperty() {
request = new UpdatePropertiesRequest(validPathLocation1, validProperty1);
17 years, 2 months
DNA SVN: r617 - in trunk: dna-common/src/main/resources/org/jboss/dna/common and 24 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-10 15:21:55 -0500 (Mon, 10 Nov 2008)
New Revision: 617
Removed:
trunk/dna-common/src/main/java/org/jboss/dna/common/monitor/
trunk/dna-common/src/test/java/org/jboss/dna/common/monitor/
Modified:
trunk/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java
trunk/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties
trunk/dna-common/src/test/java/org/jboss/dna/common/component/ComponentLibraryTest.java
trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentA.java
trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentB.java
trunk/dna-common/src/test/java/org/jboss/dna/common/component/SampleComponent.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/BasicExecutionContext.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContext.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContexts.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/SequencerContext.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/StreamSequencer.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/Sequencer.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerNodeContext.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencingService.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapter.java
trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties
trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerA.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerB.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/SequencerNodeContextTest.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapterTest.java
trunk/docs/gettingstarted/src/main/docbook/en-US/content/custom_sequencers.xml
trunk/docs/reference/src/main/docbook/en-US/content/sequencing.xml
trunk/docs/reference/src/main/docbook/en-US/custom.dtd
trunk/extensions/dna-sequencer-images/src/main/java/org/jboss/dna/sequencer/images/ImageMetadataSequencer.java
trunk/extensions/dna-sequencer-images/src/test/java/org/jboss/dna/sequencer/images/ImageMetadataSequencerTest.java
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaMetadataSequencer.java
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/metadata/JavaMetadata.java
trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataSequencerTest.java
trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataTest.java
trunk/extensions/dna-sequencer-mp3/src/main/java/org/jboss/dna/sequencer/mp3/Mp3MetadataSequencer.java
trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java
trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java
trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerI18n.java
trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java
trunk/extensions/dna-sequencer-zip/pom.xml
trunk/extensions/dna-sequencer-zip/src/main/java/org/jboss/dna/sequencer/zip/ZipSequencer.java
trunk/extensions/dna-sequencer-zip/src/test/java/org/jboss/dna/sequencer/zip/ZipSequencerTest.java
Log:
DNA-248 - Simplify the ActivityMonitor framework
http://jira.jboss.com/jira/browse/DNA-248
Despite building the simplified Task framework (see attached patch file), and after several days of thinking about it and a long discussion with John, it seems like this ProgressMonitor/ActivityMonitor/Task framework is just overkill for what we need. And it about 1900 LOC overkill. (Really, it started small and grew as we tried to generalize. Mostly it was me that was driving it.)
Turns out that only the sequencing used this framework, and its arguable whether there's any benefit to monitoring the progress and/or tasks for a singular sequencing activity. The connector framework doesn't really need the overhead either, especially when individual requests are so tiny and so many. So there really isn't a lot of similarity between the two data points (sequencers and connectors). Rather than try to force something to fit (really the purpose of this JIRA issue), it seems prudent to recognize that we don't really have a well-defined need with well-understood requirements, and that the best thing to do is to simply remove the ProgressMonitor/ActivityMonitor framework.
In doing so, the sequencers became a little simpler. The XML sequencer became a fair amount simpler. The code base became quite a bit smaller (>2400 LOC smaller). And we really didn't lose any functionality. (Sure, we kind of lost cancellation of sequencers, but that's probably not really true, either - it's quite possible that the only way to REALLY cancel a sequencer that's been stuck reading from a stream is to interrupt the thread, and the cancellation status wouldn't do that anyway.)
Modified: trunk/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/CommonI18n.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -48,8 +48,6 @@
public static I18n i18nRequiredToSuppliedParameterMismatch;
// Core-related fields
- public static I18n activityMonitorBeginTask;
- public static I18n activityMonitorStatus;
public static I18n argumentDidNotContainKey;
public static I18n argumentDidNotContainObject;
public static I18n argumentMayNotBeEmpty;
Modified: trunk/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties
===================================================================
--- trunk/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-common/src/main/resources/org/jboss/dna/common/CommonI18n.properties 2008-11-10 20:21:55 UTC (rev 617)
@@ -37,8 +37,6 @@
i18nRequiredToSuppliedParameterMismatch = Internationalization field "{0}" in {1}: {2}
# Core-related fields
-activityMonitorBeginTask = Beginning {0} ({1})
-activityMonitorStatus = {0}
argumentDidNotContainKey = "The {0} argument did not contain the expected key {1}
argumentDidNotContainObject = "The {0} argument did not contain the expected object {1}
argumentMayNotBeEmpty = The {0} argument may not be empty
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/component/ComponentLibraryTest.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/component/ComponentLibraryTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/component/ComponentLibraryTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -28,11 +28,9 @@
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;
import java.util.List;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
-import org.mockito.MockitoAnnotations.Mock;
/**
* @author Randall Hauch
@@ -46,8 +44,6 @@
private SampleComponentConfig configA2;
private String validDescription;
private String[] validClasspath;
- @Mock
- private ActivityMonitor nullMonitor;
@Before
public void beforeEach() {
@@ -152,19 +148,19 @@
// The very first component instance should still be runnable ...
for (int i = 0; i != 10; ++i) {
- firstComponent.doSomething(nullMonitor);
+ firstComponent.doSomething();
}
assertThat(firstComponent.getCounter(), is(10));
// The second component instance should still be runnable ...
for (int i = 0; i != 10; ++i) {
- secondComponentA.doSomething(nullMonitor);
+ secondComponentA.doSomething();
}
assertThat(secondComponentA.getCounter(), is(10));
// The third component instance should still be runnable ...
for (int i = 0; i != 10; ++i) {
- firstComponentB.doSomething(nullMonitor);
+ firstComponentB.doSomething();
}
assertThat(firstComponentB.getCounter(), is(10));
}
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentA.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentA.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentA.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -24,8 +24,6 @@
import java.util.concurrent.atomic.AtomicInteger;
import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
/**
* A sequencer that can be used for basic unit testing.
@@ -49,15 +47,9 @@
/**
* {@inheritDoc}
*/
- public void doSomething( ActivityMonitor activityMonitor ) {
- try {
- activityMonitor.beginTask(1, MockI18n.passthrough, "Incrementing counter");
- // increment the counter and record the progress ...
- this.counter.incrementAndGet();
- activityMonitor.worked(1);
- } finally {
- activityMonitor.done();
- }
+ public void doSomething() {
+ // increment the counter and record the progress ...
+ this.counter.incrementAndGet();
}
public int getCounter() {
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentB.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentB.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/component/MockComponentB.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -24,8 +24,6 @@
import java.util.concurrent.atomic.AtomicInteger;
import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
/**
* A sequencer that can be used for basic unit testing.
@@ -49,15 +47,9 @@
/**
* {@inheritDoc}
*/
- public void doSomething( ActivityMonitor activityMonitor ) {
- try {
- activityMonitor.beginTask(1, MockI18n.passthrough, "Incrementing counter");
- // increment the counter and record the progress ...
- this.counter.incrementAndGet();
- activityMonitor.worked(1);
- } finally {
- activityMonitor.done();
- }
+ public void doSomething() {
+ // increment the counter and record the progress ...
+ this.counter.incrementAndGet();
}
public int getCounter() {
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/component/SampleComponent.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/component/SampleComponent.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/component/SampleComponent.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -21,7 +21,6 @@
*/
package org.jboss.dna.common.component;
-import org.jboss.dna.common.monitor.ActivityMonitor;
/**
* @author Randall Hauch
@@ -29,5 +28,5 @@
*/
public interface SampleComponent extends Component<SampleComponentConfig> {
- public void doSomething( ActivityMonitor activityMonitor );
+ public void doSomething();
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/BasicExecutionContext.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/BasicExecutionContext.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/BasicExecutionContext.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -27,9 +27,6 @@
import javax.security.auth.login.LoginContext;
import org.jboss.dna.common.component.ClassLoaderFactory;
import org.jboss.dna.common.component.StandardClassLoaderFactory;
-import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
-import org.jboss.dna.common.monitor.SimpleActivityMonitor;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.properties.NamespaceRegistry;
import org.jboss.dna.graph.properties.PropertyFactory;
@@ -117,16 +114,6 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.ExecutionContext#createActivityMonitor(org.jboss.dna.common.i18n.I18n, java.lang.Object[])
- */
- public ActivityMonitor createActivityMonitor( I18n activityName,
- Object... activityNameParameters ) {
- return new SimpleActivityMonitor(activityName, activityNameParameters);
- }
-
- /**
- * {@inheritDoc}
- *
* @see org.jboss.dna.common.component.ClassLoaderFactory#getClassLoader(java.lang.String[])
*/
public ClassLoader getClassLoader( String... classpath ) {
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 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContext.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -25,8 +25,6 @@
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import org.jboss.dna.common.component.ClassLoaderFactory;
-import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.properties.NamespaceRegistry;
import org.jboss.dna.graph.properties.Property;
@@ -46,18 +44,6 @@
public interface ExecutionContext extends ClassLoaderFactory {
/**
- * Creates a thread-safe activity monitor with the specified activity name. This method should be used when the caller is
- * either not participating in an activity itself, or when a new activity needs to be performed that is not considered a
- * subtask of the caller's activity.
- *
- * @param activityName The internationalization object representing the activity's name.
- * @param activityNameParameters Any parameters needed to localize the activity's name.
- * @return A new activity monitor
- */
- ActivityMonitor createActivityMonitor( I18n activityName,
- Object... activityNameParameters );
-
- /**
* @return the access control context; may be <code>null</code>
*/
AccessControlContext getAccessControlContext();
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContexts.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContexts.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/ExecutionContexts.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -24,8 +24,6 @@
import java.security.AccessControlContext;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
-import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.properties.NameFactory;
@@ -152,16 +150,6 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.ExecutionContext#createActivityMonitor(org.jboss.dna.common.i18n.I18n, java.lang.Object[])
- */
- public ActivityMonitor createActivityMonitor( I18n activityName,
- Object... activityNameParameters ) {
- return delegate.createActivityMonitor(activityName, activityNameParameters);
- }
-
- /**
- * {@inheritDoc}
- *
* @see org.jboss.dna.common.component.ClassLoaderFactory#getClassLoader(java.lang.String[])
*/
public ClassLoader getClassLoader( String... classpath ) {
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/SequencerContext.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/SequencerContext.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/SequencerContext.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -22,6 +22,7 @@
package org.jboss.dna.graph.sequencers;
import java.util.Set;
+import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.properties.Path;
@@ -60,4 +61,12 @@
* @return the MIME-type
*/
String getMimeType();
+
+ /**
+ * Get an interface that can be used to record various problems, warnings, and errors that are not extreme enough to warrant
+ * throwing exceptions.
+ *
+ * @return the interface for recording problems; never null
+ */
+ Problems getProblems();
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/StreamSequencer.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/StreamSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/sequencers/StreamSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -22,7 +22,6 @@
package org.jboss.dna.graph.sequencers;
import java.io.InputStream;
-import org.jboss.dna.common.monitor.ActivityMonitor;
/**
* The interface for a DNA sequencer that processes a property as a stream to extract information from the content and store in
@@ -44,31 +43,12 @@
* be called. If the sequencer implements this interface, then this method is called with the property that is to be sequenced
* along with the interface used to register the output. The framework takes care of all the rest.
* </p>
- * <p>
- * This operation should report progress to the supplied {@link ActivityMonitor}. At the beginning of the operation, call
- * {@link ActivityMonitor#beginTask(double, org.jboss.dna.common.i18n.I18n, Object...)} with a meaningful message describing
- * the operation and a total for the amount of work that will be done by this sequencer. Then perform the sequencing work,
- * periodically reporting work by specifying the {@link ActivityMonitor#worked(double) amount of work} that has was just
- * completed or by {@link ActivityMonitor#createSubtask(double) creating a subtask} and reporting work against that subtask
- * monitor.
- * </p>
- * <p>
- * The implementation should also periodically check whether the operation has been {@link ActivityMonitor#isCancelled()
- * cancelled}. If this method returns true, the implementation should abort all work as soon as possible and close any
- * resources that were acquired or opened.
- * </p>
- * <p>
- * Finally, the implementation should call {@link ActivityMonitor#done()} when the operation has finished.
- * </p>
*
* @param stream the stream with the data to be sequenced; never <code>null</code>
* @param output the output from the sequencing operation; never <code>null</code>
* @param context the context for the sequencing operation; never <code>null</code>
- * @param activityMonitor the activity monitor that should be kept updated with the sequencer's progress and that should be
- * frequently consulted as to whether this operation has been {@link ActivityMonitor#isCancelled() cancelled}.
*/
void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor );
+ SequencerContext context );
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/sequencers/MockSequencerContext.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -26,9 +26,8 @@
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
-import org.jboss.dna.common.monitor.SimpleActivityMonitor;
+import org.jboss.dna.common.collection.Problems;
+import org.jboss.dna.common.collection.SimpleProblems;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.properties.Name;
@@ -48,6 +47,7 @@
private final ValueFactories factories;
private final NamespaceRegistry registry = new BasicNamespaceRegistry();
+ private final Problems problems = new SimpleProblems();
public MockSequencerContext() {
registry.register("jcr", "http://www.jcp.org/jcr/1.0");
@@ -62,16 +62,6 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.ExecutionContext#createActivityMonitor(org.jboss.dna.common.i18n.I18n, java.lang.Object[])
- */
- public ActivityMonitor createActivityMonitor( I18n activityName,
- Object... activityNameParameters ) {
- return new SimpleActivityMonitor(activityName, activityNameParameters);
- }
-
- /**
- * {@inheritDoc}
- *
* @see org.jboss.dna.common.component.ClassLoaderFactory#getClassLoader(java.lang.String[])
*/
public ClassLoader getClassLoader( String... classpath ) {
@@ -117,6 +107,15 @@
/**
* {@inheritDoc}
*
+ * @see org.jboss.dna.graph.sequencers.SequencerContext#getProblems()
+ */
+ public Problems getProblems() {
+ return problems;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @see org.jboss.dna.graph.ExecutionContext#getAccessControlContext()
*/
public AccessControlContext getAccessControlContext() {
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryI18n.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -77,11 +77,7 @@
public static I18n errorFindingSequencersToRunAgainstNode;
public static I18n errorInRepositoryWhileFindingSequencersToRunAgainstNode;
public static I18n executionContextHasBeenClosed;
- public static I18n sequencerTask;
- public static I18n sequencerSubtask;
public static I18n unableToFindPropertyForSequencing;
- public static I18n sequencingPropertyOnNode;
- public static I18n writingOutputSequencedFromPropertyOnNodes;
// Properties
public static I18n errorReadingPropertiesFromContainerNode;
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/Sequencer.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/Sequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/Sequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -26,8 +26,8 @@
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import net.jcip.annotations.ThreadSafe;
+import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.component.Component;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.repository.observation.NodeChange;
import org.jboss.dna.repository.observation.NodeChangeListener;
import org.jboss.dna.repository.observation.NodeChanges;
@@ -52,7 +52,7 @@
* Execute the sequencing operation on the supplied node, which has recently been created or changed. The implementation of
* this method is responsible for {@link JcrExecutionContext#getSessionFactory() getting sessions}, modifying the appropriate
* nodes, {@link Session#save() saving} any changes made by this sequencer, and {@link Session#logout() closing} all sessions
- * (and any other acquired resources), even in the case of {@link ActivityMonitor#isCancelled() cancellation} or exceptions.
+ * (and any other acquired resources), even in the case of exceptions.
* <p>
* The {@link SequencingService} determines the sequencers that should be executed by monitoring the changes to one or more
* workspaces (it is a {@link NodeChangeListener} registered with the {@link ObservationService}). Changes in those workspaces
@@ -68,22 +68,6 @@
* Also, in such cases the sequencer's configuration may imply multiple output nodes, so it is left to the sequencer to define
* the behavior in such cases.
* </p>
- * <p>
- * This operation should report progress to the supplied {@link ActivityMonitor}. At the beginning of the operation, call
- * {@link ActivityMonitor#beginTask(double, org.jboss.dna.common.i18n.I18n, Object...)} with a meaningful message describing
- * the operation and a total for the amount of work that will be done by this sequencer. Then perform the sequencing work,
- * periodically reporting work by specifying the {@link ActivityMonitor#worked(double) amount of work} that has was just
- * completed or by {@link ActivityMonitor#createSubtask(double) creating a subtask} and reporting work against that subtask
- * monitor.
- * </p>
- * <p>
- * The implementation should also periodically check whether the operation has been {@link ActivityMonitor#isCancelled()
- * cancelled}. If this method returns true, the implementation should abort all work as soon as possible and close any
- * resources that were acquired or opened.
- * </p>
- * <p>
- * Finally, the implementation should call {@link ActivityMonitor#done()} when the operation has finished.
- * </p>
*
* @param input the node that has recently been created or changed; never null
* @param sequencedPropertyName the name of the property that caused this sequencer to be executed; never null and never empty
@@ -92,8 +76,7 @@
* @param outputPaths the paths to the nodes where the sequencing content should be placed; never null and never empty, but
* the set may contain paths for non-existant nodes or may reference the <code>input</code> node
* @param context the context in which this sequencer is executing; never null
- * @param activityMonitor the activity monitor that should be kept updated with the sequencer's progress and that should be
- * frequently consulted as to whether this operation has been {@link ActivityMonitor#isCancelled() cancelled}.
+ * @param problems the interface used for recording problems; never null
* @throws RepositoryException if there is a problem while working with the repository
* @throws SequencerException if there is an error in this sequencer
*/
@@ -102,6 +85,6 @@
NodeChange changes,
Set<RepositoryNodePath> outputPaths,
JcrExecutionContext context,
- ActivityMonitor activityMonitor ) throws RepositoryException, SequencerException;
+ Problems problems ) throws RepositoryException, SequencerException;
}
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerNodeContext.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerNodeContext.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerNodeContext.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -35,8 +35,7 @@
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
+import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.properties.Name;
@@ -65,15 +64,19 @@
private final Path path;
private final Set<Property> props;
private final JcrExecutionContext context;
+ private final Problems problems;
SequencerNodeContext( Node input,
javax.jcr.Property sequencedProperty,
- JcrExecutionContext context ) throws RepositoryException {
+ JcrExecutionContext context,
+ Problems problems ) throws RepositoryException {
assert input != null;
assert sequencedProperty != null;
assert context != null;
+ assert problems != null;
this.context = context;
this.sequencedProperty = sequencedProperty;
+ this.problems = problems;
this.factories = context.getValueFactories();
// Translate JCR path and property values to DNA constructs and cache them to improve performance and prevent
// RepositoryException from being thrown by getters
@@ -142,16 +145,6 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.ExecutionContext#createActivityMonitor(org.jboss.dna.common.i18n.I18n, java.lang.Object[])
- */
- public ActivityMonitor createActivityMonitor( I18n activityName,
- Object... activityNameParameters ) {
- return context.createActivityMonitor(activityName, activityNameParameters);
- }
-
- /**
- * {@inheritDoc}
- *
* @see org.jboss.dna.graph.ExecutionContext#getAccessControlContext()
*/
public AccessControlContext getAccessControlContext() {
@@ -210,6 +203,15 @@
/**
* {@inheritDoc}
*
+ * @see org.jboss.dna.graph.sequencers.SequencerContext#getProblems()
+ */
+ public Problems getProblems() {
+ return problems;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @see org.jboss.dna.graph.sequencers.SequencerContext#getMimeType()
*/
@SuppressWarnings( "null" )
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencingService.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencingService.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencingService.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -43,12 +43,10 @@
import javax.security.auth.login.LoginContext;
import net.jcip.annotations.Immutable;
import net.jcip.annotations.ThreadSafe;
+import org.jboss.dna.common.collection.SimpleProblems;
import org.jboss.dna.common.component.ClassLoaderFactory;
import org.jboss.dna.common.component.ComponentLibrary;
import org.jboss.dna.common.component.StandardClassLoaderFactory;
-import org.jboss.dna.common.i18n.I18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
-import org.jboss.dna.common.monitor.LoggingActivityMonitor;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
import org.jboss.dna.common.util.Logger;
@@ -514,57 +512,37 @@
}
} else {
// Run each of those sequencers ...
- ActivityMonitor activityMonitor = context.createActivityMonitor(RepositoryI18n.sequencerTask, changedNode);
- if (logger.isTraceEnabled()) {
- activityMonitor = new LoggingActivityMonitor(activityMonitor, logger, Logger.Level.TRACE);
- }
- try {
- activityMonitor.beginTask(sequencerCalls.size(), RepositoryI18n.sequencerTask, changedNode);
- for (Map.Entry<SequencerCall, Set<RepositoryNodePath>> entry : sequencerCalls.entrySet()) {
- final SequencerCall sequencerCall = entry.getKey();
- final Set<RepositoryNodePath> outputPaths = entry.getValue();
- final Sequencer sequencer = sequencerCall.getSequencer();
- final String sequencerName = sequencer.getConfiguration().getName();
- final String propertyName = sequencerCall.getSequencedPropertyName();
+ for (Map.Entry<SequencerCall, Set<RepositoryNodePath>> entry : sequencerCalls.entrySet()) {
+ final SequencerCall sequencerCall = entry.getKey();
+ final Set<RepositoryNodePath> outputPaths = entry.getValue();
+ final Sequencer sequencer = sequencerCall.getSequencer();
+ final String sequencerName = sequencer.getConfiguration().getName();
+ final String propertyName = sequencerCall.getSequencedPropertyName();
- // Get the paths to the nodes where the sequencer should write it's output ...
- assert outputPaths != null && outputPaths.size() != 0;
+ // Get the paths to the nodes where the sequencer should write it's output ...
+ assert outputPaths != null && outputPaths.size() != 0;
- // Create a new execution context for each sequencer
- final Context executionContext = new Context(context);
- final ActivityMonitor sequenceMonitor = activityMonitor.createSubtask(1);
+ // Create a new execution context for each sequencer
+ final Context executionContext = new Context(context);
+ final SimpleProblems problems = new SimpleProblems();
+ try {
+ sequencer.execute(node, propertyName, changedNode, outputPaths, executionContext, problems);
+ } catch (RepositoryException e) {
+ logger.error(e, RepositoryI18n.errorInRepositoryWhileSequencingNode, sequencerName, changedNode);
+ } catch (SequencerException e) {
+ logger.error(e, RepositoryI18n.errorWhileSequencingNode, sequencerName, changedNode);
+ } finally {
try {
- sequenceMonitor.beginTask(100, RepositoryI18n.sequencerSubtask, sequencerName);
- sequencer.execute(node,
- propertyName,
- changedNode,
- outputPaths,
- executionContext,
- sequenceMonitor.createSubtask(80)); // 80%
- } catch (RepositoryException e) {
- logger.error(e, RepositoryI18n.errorInRepositoryWhileSequencingNode, sequencerName, changedNode);
- } catch (SequencerException e) {
- logger.error(e, RepositoryI18n.errorWhileSequencingNode, sequencerName, changedNode);
+ // Save the changes made by each sequencer ...
+ if (session != null) session.save();
} finally {
- try {
- // Save the changes made by each sequencer ...
- if (session != null) session.save();
- sequenceMonitor.worked(10); // 90% of sequenceMonitor
- } finally {
- try {
- // And always close the context.
- // This closes all sessions that may have been created by the sequencer.
- executionContext.close();
- } finally {
- sequenceMonitor.done(); // 100% of sequenceMonitor
- }
- }
+ // And always close the context.
+ // This closes all sessions that may have been created by the sequencer.
+ executionContext.close();
}
}
- this.statistics.recordNodeSequenced();
- } finally {
- activityMonitor.done();
}
+ this.statistics.recordNodeSequenced();
}
} finally {
if (session != null) session.logout();
@@ -608,16 +586,6 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.ExecutionContext#createActivityMonitor(org.jboss.dna.common.i18n.I18n, java.lang.Object[])
- */
- public ActivityMonitor createActivityMonitor( I18n activityName,
- Object... activityNameParameters ) {
- return delegate.createActivityMonitor(activityName, activityNameParameters);
- }
-
- /**
- * {@inheritDoc}
- *
* @see org.jboss.dna.common.component.ClassLoaderFactory#getClassLoader(java.lang.String[])
*/
public ClassLoader getClassLoader( String... classpath ) {
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapter.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapter.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapter.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -31,7 +31,7 @@
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
-import org.jboss.dna.common.monitor.ActivityMonitor;
+import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.properties.Binary;
import org.jboss.dna.graph.properties.DateTime;
@@ -82,88 +82,71 @@
NodeChange changes,
Set<RepositoryNodePath> outputPaths,
JcrExecutionContext execContext,
- ActivityMonitor activityMonitor ) throws RepositoryException, SequencerException {
+ Problems problems ) throws RepositoryException, SequencerException {
// 'sequencedPropertyName' contains the name of the modified property on 'input' that resulted in the call to this
// sequencer.
// 'changes' contains all of the changes to this node that occurred in the transaction.
// 'outputPaths' contains the paths of the node(s) where this sequencer is to save it's data.
+ // Get the property that contains the data, given by 'propertyName' ...
+ Property sequencedProperty = null;
try {
- activityMonitor.beginTask(100, RepositoryI18n.sequencingPropertyOnNode, sequencedPropertyName, input.getPath());
+ sequencedProperty = input.getProperty(sequencedPropertyName);
+ } catch (PathNotFoundException e) {
+ String msg = RepositoryI18n.unableToFindPropertyForSequencing.text(sequencedPropertyName, input.getPath());
+ throw new SequencerException(msg, e);
+ }
- // Get the property that contains the data, given by 'propertyName' ...
- Property sequencedProperty = null;
- try {
- sequencedProperty = input.getProperty(sequencedPropertyName);
- } catch (PathNotFoundException e) {
- String msg = RepositoryI18n.unableToFindPropertyForSequencing.text(sequencedPropertyName, input.getPath());
- throw new SequencerException(msg, e);
+ // Get the binary property with the image content, and build the image metadata from the image ...
+ SequencerOutputMap output = new SequencerOutputMap(execContext.getValueFactories());
+ InputStream stream = null;
+ Throwable firstError = null;
+ try {
+ stream = sequencedProperty.getStream();
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
+ this.streamSequencer.sequence(stream, output, sequencerContext);
+ } catch (Throwable t) {
+ // Record the error ...
+ firstError = t;
+ } finally {
+ if (stream != null) {
+ // Always close the stream, recording the error if we've not yet seen an error
+ try {
+ stream.close();
+ } catch (Throwable t) {
+ if (firstError == null) firstError = t;
+ } finally {
+ stream = null;
+ }
}
- activityMonitor.worked(10);
+ if (firstError != null) {
+ // Wrap and throw the first error that we saw ...
+ throw new SequencerException(firstError);
+ }
+ }
- // Get the binary property with the image content, and build the image metadata from the image ...
- SequencerOutputMap output = new SequencerOutputMap(execContext.getValueFactories());
- InputStream stream = null;
- Throwable firstError = null;
- ActivityMonitor sequencingMonitor = activityMonitor.createSubtask(50);
+ // Find each output node and save the image metadata there ...
+ for (RepositoryNodePath outputPath : outputPaths) {
+ Session session = null;
try {
- stream = sequencedProperty.getStream();
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
- this.streamSequencer.sequence(stream, output, sequencerContext, sequencingMonitor);
- } catch (Throwable t) {
- // Record the error ...
- firstError = t;
- } finally {
- sequencingMonitor.done();
- if (stream != null) {
- // Always close the stream, recording the error if we've not yet seen an error
- try {
- stream.close();
- } catch (Throwable t) {
- if (firstError == null) firstError = t;
- } finally {
- stream = null;
- }
- }
- if (firstError != null) {
- // Wrap and throw the first error that we saw ...
- throw new SequencerException(firstError);
- }
- }
+ // Get the name of the repository workspace and the path to the output node
+ final String repositoryWorkspaceName = outputPath.getRepositoryWorkspaceName();
+ final String nodePath = outputPath.getNodePath();
- // Find each output node and save the image metadata there ...
- ActivityMonitor writingActivity = activityMonitor.createSubtask(40);
- writingActivity.beginTask(outputPaths.size(),
- RepositoryI18n.writingOutputSequencedFromPropertyOnNodes,
- sequencedPropertyName,
- input.getPath(),
- outputPaths.size());
- for (RepositoryNodePath outputPath : outputPaths) {
- Session session = null;
- try {
- // Get the name of the repository workspace and the path to the output node
- final String repositoryWorkspaceName = outputPath.getRepositoryWorkspaceName();
- final String nodePath = outputPath.getNodePath();
+ // Create a session to the repository where the data should be written ...
+ session = execContext.getSessionFactory().createSession(repositoryWorkspaceName);
- // Create a session to the repository where the data should be written ...
- session = execContext.getSessionFactory().createSession(repositoryWorkspaceName);
+ // Find or create the output node in this session ...
+ Node outputNode = execContext.getTools().findOrCreateNode(session, nodePath);
- // Find or create the output node in this session ...
- Node outputNode = execContext.getTools().findOrCreateNode(session, nodePath);
-
- // Now save the image metadata to the output node ...
- if (saveOutput(outputNode, output, execContext)) {
- session.save();
- }
- } finally {
- writingActivity.worked(1);
- // Always close the session ...
- if (session != null) session.logout();
+ // Now save the image metadata to the output node ...
+ if (saveOutput(outputNode, output, execContext)) {
+ session.save();
}
+ } finally {
+ // Always close the session ...
+ if (session != null) session.logout();
}
- writingActivity.done();
- } finally {
- activityMonitor.done();
}
}
Modified: trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties
===================================================================
--- trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/main/resources/org/jboss/dna/repository/RepositoryI18n.properties 2008-11-10 20:21:55 UTC (rev 617)
@@ -62,11 +62,7 @@
errorInRepositoryWhileFindingSequencersToRunAgainstNode = Error in repository while finding sequencers to run against node {0}
errorFindingSequencersToRunAgainstNode = Error finding sequencers to run against node {0}
executionContextHasBeenClosed = This execution context has been closed and may not be used to create another session
-sequencerTask = Sequencing {0}
-sequencerSubtask = running {0}
unableToFindPropertyForSequencing = Unable to find the {0} property while sequencing node {1}
-sequencingPropertyOnNode = Sequencing the {0} property on node {1}
-writingOutputSequencedFromPropertyOnNodes = Writing the output of the sequencing of the {0} property on node {1} to {2} nodes
errorReadingPropertiesFromContainerNode = Error reading properties from property container node {0}
requiredPropertyOnNodeWasExpectedToBeStringValue = The required {0} property on node {1} was expected to be a string value
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerA.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerA.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerA.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -28,8 +28,7 @@
import java.util.concurrent.atomic.AtomicInteger;
import javax.jcr.Node;
import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
+import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.repository.observation.NodeChange;
import org.jboss.dna.repository.util.JcrExecutionContext;
import org.jboss.dna.repository.util.RepositoryNodePath;
@@ -71,16 +70,10 @@
NodeChange changes,
Set<RepositoryNodePath> outputPaths,
JcrExecutionContext context,
- ActivityMonitor activityMonitor ) {
- try {
- activityMonitor.beginTask(1, MockI18n.passthrough, "Incrementing counter");
- // increment the counter and record the progress ...
- this.counter.incrementAndGet();
- this.latch.countDown();
- activityMonitor.worked(1);
- } finally {
- activityMonitor.done();
- }
+ Problems problems ) {
+ // increment the counter and record the progress ...
+ this.counter.incrementAndGet();
+ this.latch.countDown();
}
public int getCounter() {
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerB.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerB.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/MockSequencerB.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -28,8 +28,7 @@
import java.util.concurrent.atomic.AtomicInteger;
import javax.jcr.Node;
import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
+import org.jboss.dna.common.collection.Problems;
import org.jboss.dna.repository.observation.NodeChange;
import org.jboss.dna.repository.util.JcrExecutionContext;
import org.jboss.dna.repository.util.RepositoryNodePath;
@@ -71,16 +70,10 @@
NodeChange changes,
Set<RepositoryNodePath> outputPaths,
JcrExecutionContext context,
- ActivityMonitor activityMonitor ) {
- try {
- activityMonitor.beginTask(1, MockI18n.passthrough, "Incrementing counter");
- // increment the counter and record the progress ...
- this.counter.incrementAndGet();
- this.latch.countDown();
- activityMonitor.worked(1);
- } finally {
- activityMonitor.done();
- }
+ Problems problems ) {
+ // increment the counter and record the progress ...
+ this.counter.incrementAndGet();
+ this.latch.countDown();
}
public int getCounter() {
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/SequencerNodeContextTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/SequencerNodeContextTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/SequencerNodeContextTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -29,6 +29,8 @@
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import org.jboss.dna.common.collection.Problems;
+import org.jboss.dna.common.collection.SimpleProblems;
import org.jboss.dna.common.jcr.AbstractJcrRepositoryTest;
import org.jboss.dna.graph.properties.NamespaceRegistry;
import org.jboss.dna.graph.properties.Property;
@@ -52,6 +54,7 @@
private JcrExecutionContext execContext;
private Session session;
private JcrTools tools;
+ private Problems problems;
@Mock
private javax.jcr.Property sequencedProperty;
@@ -73,6 +76,7 @@
startRepository();
session = getRepository().login(getTestCredentials());
tools = new JcrTools();
+ problems = new SimpleProblems();
}
@After
@@ -105,46 +109,46 @@
@Test( expected = java.lang.AssertionError.class )
public void shouldNotAllowNullInputNode() throws Exception {
- new SequencerNodeContext(null, sequencedProperty, execContext);
+ new SequencerNodeContext(null, sequencedProperty, execContext, problems);
}
@Test( expected = java.lang.AssertionError.class )
public void shouldNotAllowNullSequencedProperty() throws Exception {
Node input = tools.findOrCreateNode(session, "/a");
- new SequencerNodeContext(input, null, execContext);
+ new SequencerNodeContext(input, null, execContext, problems);
}
@Test( expected = java.lang.AssertionError.class )
public void shouldNotAllowNullExecutionContext() throws Exception {
Node input = tools.findOrCreateNode(session, "/a");
- new SequencerNodeContext(input, sequencedProperty, null);
+ new SequencerNodeContext(input, sequencedProperty, null, problems);
}
@Test
public void shouldProvideNamespaceRegistry() throws Exception {
Node input = tools.findOrCreateNode(session, "/a/b/c");
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
assertThat(sequencerContext.getNamespaceRegistry(), notNullValue());
}
@Test
public void shouldProvideValueFactories() throws Exception {
Node input = tools.findOrCreateNode(session, "/a/b/c");
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
assertThat(sequencerContext.getValueFactories(), notNullValue());
}
@Test
public void shouldProvidePathToInput() throws Exception {
Node input = tools.findOrCreateNode(session, "/a/b/c");
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
assertThat(sequencerContext.getInputPath(), is(execContext.getValueFactories().getPathFactory().create("/a/b/c")));
}
@Test
public void shouldNeverReturnNullInputProperties() throws Exception {
Node input = tools.findOrCreateNode(session, "/a/b/c");
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
assertThat(sequencerContext.getInputProperties(), notNullValue());
assertThat(sequencerContext.getInputProperties().isEmpty(), is(false));
}
@@ -154,7 +158,7 @@
Node input = tools.findOrCreateNode(session, "/a/b/c");
input.setProperty("x", true);
input.setProperty("y", new String[] {"asdf", "xyzzy"});
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
assertThat(sequencerContext.getInputProperties(), notNullValue());
assertThat(sequencerContext.getInputProperties().isEmpty(), is(false));
assertThat(sequencerContext.getInputProperties().size(), is(3));
@@ -168,7 +172,7 @@
@Test
public void shouldProvideMimeType() throws Exception {
Node input = tools.findOrCreateNode(session, "/a/b/c");
- SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext);
+ SequencerNodeContext sequencerContext = new SequencerNodeContext(input, sequencedProperty, execContext, problems);
assertThat(sequencerContext.getMimeType(), is("text/plain"));
}
}
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapterTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapterTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/sequencers/StreamSequencerAdapterTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -35,10 +35,9 @@
import javax.jcr.Node;
import javax.jcr.Session;
import javax.jcr.observation.Event;
+import org.jboss.dna.common.collection.Problems;
+import org.jboss.dna.common.collection.SimpleProblems;
import org.jboss.dna.common.jcr.AbstractJcrRepositoryTest;
-import org.jboss.dna.common.monitor.ActivityMonitor;
-import org.jboss.dna.common.monitor.CapturedActivityInfo;
-import org.jboss.dna.common.monitor.RecordingActivityMonitor;
import org.jboss.dna.graph.properties.NamespaceRegistry;
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.sequencers.SequencerContext;
@@ -70,8 +69,8 @@
private SequencerOutputMap sequencerOutput;
private String sampleData = "The little brown fox didn't something bad.";
private JcrExecutionContext context;
- private RecordingActivityMonitor activityMonitor;
private String repositoryWorkspaceName = "something";
+ private Problems problems;
@Before
public void beforeEach() {
@@ -83,10 +82,10 @@
return createTestSession();
}
};
+ problems = new SimpleProblems();
NamespaceRegistry registry = new JcrNamespaceRegistry(sessionFactory, "doesn't matter");
this.context = new BasicJcrExecutionContext(sessionFactory, registry, null, null);
this.sequencerOutput = new SequencerOutputMap(this.context.getValueFactories());
- this.activityMonitor = new RecordingActivityMonitor(StreamSequencerAdapterTest.class.getName());
final SequencerOutputMap finalOutput = sequencerOutput;
this.streamSequencer = new StreamSequencer() {
@@ -96,8 +95,7 @@
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
+ SequencerContext context ) {
for (SequencerOutputMap.Entry entry : finalOutput) {
Path nodePath = entry.getPath();
for (SequencerOutputMap.PropertyValue property : entry.getPropertyValues()) {
@@ -134,13 +132,8 @@
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
- try {
- sequencer.sequence(stream, output, context, activityMonitor);
- } catch (AssertionError err) {
- activityMonitor.captureError(err);
- }
+ SequencerContext context ) {
+ sequencer.sequence(stream, output, context);
}
};
StreamSequencerAdapter adapter = new StreamSequencerAdapter(streamSequencer);
@@ -154,10 +147,7 @@
Set<RepositoryNodePath> outputPaths = new HashSet<RepositoryNodePath>();
outputPaths.add(new RepositoryNodePath(repositoryWorkspaceName, outputNode.getPath()));
sequencerOutput.setProperty("alpha/beta", "isSomething", true);
- adapter.execute(inputNode, "sequencedProperty", nodeChange, outputPaths, context, activityMonitor);
- for (CapturedActivityInfo info : activityMonitor.getStatus().getCapturedInformation()) {
- if (info.isError()) throw info.getThrowable();
- }
+ adapter.execute(inputNode, "sequencedProperty", nodeChange, outputPaths, context, problems);
}
@Test
@@ -219,7 +209,7 @@
sequencerOutput.setProperty("alpha/beta", "isSomething", true);
// Call the sequencer ...
- sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, activityMonitor);
+ sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, problems);
}
@Test( expected = SequencerException.class )
@@ -252,7 +242,7 @@
sequencerOutput.setProperty("alpha/beta", "isSomething", true);
// Call the sequencer, which should cause the exception ...
- sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, activityMonitor);
+ sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, problems);
}
@Test
@@ -285,7 +275,7 @@
sequencerOutput.setProperty("alpha/beta", "isSomething", true);
// Call the sequencer ...
- sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, activityMonitor);
+ sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, problems);
// Check to see that the output nodes have been created ...
assertThat(session.getRootNode().hasNode("d/e"), is(true));
@@ -317,7 +307,7 @@
sequencerOutput.setProperty("alpha/beta", "isSomething", true);
// Call the sequencer ...
- sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, activityMonitor);
+ sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, problems);
// Check to see that the "/d/e" node has been created ...
assertThat(session.getRootNode().hasNode("d/e"), is(true));
@@ -351,7 +341,7 @@
sequencerOutput.setProperty("alpha/beta", "isSomething", true);
// Call the sequencer ...
- sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, activityMonitor);
+ sequencer.execute(nodeC, "sequencedProperty", nodeChange, outputPaths, context, problems);
// Check to see that the output nodes have been created ...
assertThat(session.getRootNode().hasNode("d/e"), is(true));
@@ -380,8 +370,7 @@
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
+ SequencerContext context ) {
assertThat(stream, notNullValue());
}
});
@@ -393,8 +382,7 @@
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
+ SequencerContext context ) {
assertThat(output, notNullValue());
}
});
@@ -406,23 +394,10 @@
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
+ SequencerContext context ) {
assertThat(context, notNullValue());
}
});
}
- @Test
- public void shouldPassNonNullActivityMonitorToSequencer() throws Throwable {
- testSequencer(new StreamSequencer() {
-
- public void sequence( InputStream stream,
- SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
- assertThat(activityMonitor, notNullValue());
- }
- });
- }
}
Modified: trunk/docs/gettingstarted/src/main/docbook/en-US/content/custom_sequencers.xml
===================================================================
--- trunk/docs/gettingstarted/src/main/docbook/en-US/content/custom_sequencers.xml 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/docs/gettingstarted/src/main/docbook/en-US/content/custom_sequencers.xml 2008-11-10 20:21:55 UTC (rev 617)
@@ -183,17 +183,19 @@
*
* @param stream the stream with the data to be sequenced; never null
* @param output the output from the sequencing operation; never null
- * @param progressMonitor the progress monitor that should be kept
- * updated with the sequencer's progress and that should be
- * frequently consulted as to whether this operation has been cancelled.
+ * @param context the context for the sequencing operation; never null
*/
- void sequence( InputStream stream, SequencerOutput output, ProgressMonitor progressMonitor );
+ void sequence( InputStream stream, SequencerOutput output, SequencerContext context );
]]></programlisting>
<para>The job of a stream sequencer is to process the data in the supplied stream, and place into the <code>SequencerOutput</code>
any information that is to go into the JCR repository. JBoss DNA figures out when your sequencer should be called
(of course, using the sequencing configuration you'll add in a bit), and then makes sure the generated information
is saved in the correct place in the repository.
</para>
+ <para>The <code>SequencerContext</code> provides information about
+ the current sequencing operation, including the location and properties of the node being sequenced, the MIME type
+ of the node being sequenced, and a location to record problems that aren't severe enough to warrant throwing an exception.
+ </para>
<para>The <code>SequencerOutput</code> class is fairly easy to use. There are basically two methods you need to call.
One method sets the property values, while the other sets references to other nodes in the repository. Use these
methods to describe the properties of the nodes you want to create, using relative paths for the nodes and
@@ -261,9 +263,7 @@
* {@inheritDoc}
*/
public void sequence( InputStream stream, SequencerOutput output,
- ProgressMonitor progressMonitor ) {
- progressMonitor.beginTask(10, ImageSequencerI18n.sequencerTaskName);
-
+ SequencerContext context ) {
ImageMetadata metadata = new ImageMetadata();
metadata.setInput(stream);
metadata.setDetermineImageNumber(true);
@@ -273,8 +273,6 @@
if (!metadata.check()) {
metadata = null;
}
- progressMonitor.worked(5);
- if (progressMonitor.isCancelled()) return;
// Generate the output graph if we found useful metadata ...
if (metadata != null) {
@@ -294,8 +292,6 @@
output.setProperty(METADATA_NODE, IMAGE_PHYSICAL_WIDTH_INCHES, metadata.getPhysicalWidthInch());
output.setProperty(METADATA_NODE, IMAGE_PHYSICAL_HEIGHT_INCHES, metadata.getPhysicalHeightInch());
}
-
- progressMonitor.done();
}
}
]]></programlisting>
@@ -304,22 +300,7 @@
and with the <code>image:metadata</code> node type. No mixins are defined for the node, but several properties are set on the node
using the values obtained from the image metadata. After this method returns, the constructed graph will be saved to the repository
in all of the places defined by its configuration. (This is why only relative paths are used in the sequencer.)
- </para>
- <para>Also note how the progress monitor is used. Reporting progress through the supplied <code>ProgressMonitor</code> is very easy, and it ensures that JBoss DNA
- can accurately monitor and report the status of sequencing activities to the users. At the beginning of the operation, call
- <code>beginTask(...)</code> with a meaningful message describing
- the operation and a total for the amount of work that will be done by this sequencer. Then perform the sequencing work,
- periodically reporting work by specifying the incremental amount of work with the <code>worked(double)</code> method, or
- by creating a subtask with the <code>createSubtask(double)</code> method and reporting work against that subtask
- monitor.
- </para>
- <para>Your method should periodically use the ProgressMonitor's <code>isCancelled()</code> method to check whether the operation has been
- cancelled.. If this method returns true, the implementation should abort all work as
- soon as possible and close any resources that were acquired or opened.
- </para>
- <para>
- Finally, when your sequencing operation is completed, it should call <code>done()</code> on the progress monitor.
- </para>
+ </para>
</sect1>
<sect1 id="testing_custom_sequencers">
<title>Testing custom sequencers</title>
@@ -338,11 +319,11 @@
<programlisting role="JAVA"><![CDATA[
Sequencer sequencer = new ImageMetadataSequencer();
MockSequencerOutput output = new MockSequencerOutput();
-ProgressMonitor progress = new SimpleProgressMonitor("Test activity");
+MockSequencerContext context = new MockSequencerContext();
InputStream stream = null;
try {
stream = this.getClass().getClassLoader().getResource("caution.gif").openStream();
- sequencer.sequence(stream,output,progress); // writes to 'output'
+ sequencer.sequence(stream,output,context); // writes to 'output'
assertThat(output.getPropertyValues("image:metadata", "jcr:primaryType"),
is(new Object[] {"image:metadata"}));
assertThat(output.getPropertyValues("image:metadata", "jcr:mimeType"),
@@ -357,11 +338,11 @@
<programlisting role="JAVA"><![CDATA[
Sequencer sequencer = new ImageMetadataSequencer();
MockSequencerOutput output = new MockSequencerOutput();
-ProgressMonitor progress = new SimpleProgressMonitor("Test activity");
+MockSequencerContext context = new MockSequencerContext();
InputStream stream = null;
try {
stream = this.getClass().getClassLoader().getResource("caution.pict").openStream();
- sequencer.sequence(stream,output,progress); // writes to 'output'
+ sequencer.sequence(stream,output,context); // writes to 'output'
assertThat(output.hasProperties(), is(false));
assertThat(output.hasReferences(), is(false));
} finally {
Modified: trunk/docs/reference/src/main/docbook/en-US/content/sequencing.xml
===================================================================
--- trunk/docs/reference/src/main/docbook/en-US/content/sequencing.xml 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/docs/reference/src/main/docbook/en-US/content/sequencing.xml 2008-11-10 20:21:55 UTC (rev 617)
@@ -601,17 +601,19 @@
*
* @param stream the stream with the data to be sequenced; never null
* @param output the output from the sequencing operation; never null
- * @param progressMonitor the progress monitor that should be kept
- * updated with the sequencer's progress and that should be
- * frequently consulted as to whether this operation has been cancelled.
+ * @param context the context for the sequencing operation; never null
*/
- void sequence( &InputStream; stream, &SequencerOutput; output, &ProgressMonitor; progressMonitor );
+ void sequence( &InputStream; stream, &SequencerOutput; output, &SequencerContext; context );
</programlisting>
<para>The job of a stream sequencer is to process the data in the supplied stream, and place into the &SequencerOutput;
any information that is to go into the JCR repository. JBoss DNA figures out when your sequencer should be called
(of course, using the sequencing configuration you'll add in a bit), and then makes sure the generated information
is saved in the correct place in the repository.
</para>
+ <para>The &SequencerContext; provides information about
+ the current sequencing operation, including the location and properties of the node being sequenced, the MIME type
+ of the node being sequenced, and a location to record problems that aren't severe enough to warrant throwing an exception.
+ </para>
<para>The &SequencerOutput; class is fairly easy to use. There are basically two methods you need to call.
One method sets the property values, while the other sets references to other nodes in the repository. Use these
methods to describe the properties of the nodes you want to create, using relative paths for the nodes and
@@ -679,9 +681,7 @@
* {@inheritDoc}
*/
public void sequence( &InputStream; stream, &SequencerOutput; output,
- &ProgressMonitor; progressMonitor ) {
- progressMonitor.beginTask(10, &ImageSequencerI18n;.sequencerTaskName);
-
+ &SequencerContext; context ) {
&ImageMetadata; metadata = new &ImageMetadata;();
metadata.setInput(stream);
metadata.setDetermineImageNumber(true);
@@ -691,9 +691,6 @@
if (!metadata.check()) {
metadata = null;
}
- progressMonitor.worked(5);
- if (progressMonitor.isCancelled()) return;
-
// Generate the output graph if we found useful metadata ...
if (metadata != null) {
// Place the image metadata into the output map ...
@@ -712,8 +709,6 @@
output.setProperty(METADATA_NODE, IMAGE_PHYSICAL_WIDTH_INCHES, metadata.getPhysicalWidthInch());
output.setProperty(METADATA_NODE, IMAGE_PHYSICAL_HEIGHT_INCHES, metadata.getPhysicalHeightInch());
}
-
- progressMonitor.done();
}
}
</programlisting>
@@ -723,21 +718,6 @@
using the values obtained from the image metadata. After this method returns, the constructed graph will be saved to the repository
in all of the places defined by its configuration. (This is why only relative paths are used in the sequencer.)
</para>
- <para>Also note how the progress monitor is used. Reporting progress through the supplied &ProgressMonitor;> is very easy, and it ensures that JBoss DNA
- can accurately monitor and report the status of sequencing activities to the users. At the beginning of the operation, call
- <code>beginTask(...)</code> with a meaningful message describing
- the operation and a total for the amount of work that will be done by this sequencer. Then perform the sequencing work,
- periodically reporting work by specifying the incremental amount of work with the <code>worked(double)</code> method, or
- by creating a subtask with the <code>createSubtask(double)</code> method and reporting work against that subtask
- monitor.
- </para>
- <para>Your method should periodically use the &ProgressMonitor;'s <code>isCancelled()</code> method to check whether the operation has been
- cancelled.. If this method returns true, the implementation should abort all work as
- soon as possible and close any resources that were acquired or opened.
- </para>
- <para>
- Finally, when your sequencing operation is completed, it should call <code>done()</code> on the progress monitor.
- </para>
</sect2>
<sect2 id="testing_custom_sequencers">
<title>Testing custom sequencers</title>
@@ -755,12 +735,12 @@
this example code does not do any error handling and does not make all the assertions a real test would.</para>
<programlisting>
&StreamSequencer; sequencer = new &ImageMetadataSequencer;();
-MockSequencerOutput output = new MockSequencerOutput();
-&ProgressMonitor; progress = new &SimpleProgressMonitor;("Test activity");
+&MockSequencerOutput; output = new &MockSequencerOutput;();
+&MockSequencerContext; context = new &MockSequencerContext;();
&InputStream; stream = null;
try {
stream = this.getClass().getClassLoader().getResource("caution.gif").openStream();
- sequencer.sequence(stream,output,progress); // writes to 'output'
+ sequencer.sequence(stream,output,context); // writes to 'output'
assertThat(output.getPropertyValues("image:metadata", "jcr:primaryType"),
is(new Object[] {"image:metadata"}));
assertThat(output.getPropertyValues("image:metadata", "jcr:mimeType"),
@@ -774,12 +754,12 @@
<para>It's also useful to test that a sequencer produces no output for something it should not understand:</para>
<programlisting>
&Sequencer; sequencer = new &ImageMetadataSequencer;();
-MockSequencerOutput output = new MockSequencerOutput();
-&ProgressMonitor; progress = new &SimpleProgressMonitor;("Test activity");
+&MockSequencerOutput; output = new &MockSequencerOutput;();
+&MockSequencerContext; context = new &MockSequencerContext;();
&InputStream; stream = null;
try {
stream = this.getClass().getClassLoader().getResource("caution.pict").openStream();
- sequencer.sequence(stream,output,progress); // writes to 'output'
+ sequencer.sequence(stream,output,context); // writes to 'output'
assertThat(output.hasProperties(), is(false));
assertThat(output.hasReferences(), is(false));
} finally {
Modified: trunk/docs/reference/src/main/docbook/en-US/custom.dtd
===================================================================
--- trunk/docs/reference/src/main/docbook/en-US/custom.dtd 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/docs/reference/src/main/docbook/en-US/custom.dtd 2008-11-10 20:21:55 UTC (rev 617)
@@ -45,8 +45,6 @@
<!-- Types in dna-common -->
<!ENTITY Logger "<ulink url='&API;common/util/Logger.html'><interface>Logger</interface></ulink>">
-<!ENTITY ProgressMonitor "<ulink url='&API;common/monitor/ProgressMonitor.html'><interface>ProgressMonitor</interface></ulink>">
-<!ENTITY SimpleProgressMonitor "<ulink url='&API;common/monitor/SimpleProgressMonitor.html'><classname>SimpleProgressMonitor</classname></ulink>">
<!ENTITY ClassLoaderFactory "<ulink url='&API;common/component/ClassLoaderFactory.html'><interface>ClassLoaderFactory</interface></ulink>">
<!ENTITY StandardClassLoaderFactory "<ulink url='&API;common/component/ClassLoaderFactory.html'><classname>StandardClassLoaderFactory</classname></ulink>">
@@ -63,7 +61,10 @@
<!ENTITY RepositoryConnection "<ulink url='&API;graph/connectors/RepositoryConnection.html'><interface>RepositoryConnection</interface></ulink>">
<!ENTITY StreamSequencer "<ulink url='&API;graph/sequencers/StreamSequencer.html'><interface>StreamSequencer</interface></ulink>">
<!ENTITY SequencerOutput "<ulink url='&API;graph/sequencers/SequencerOutput.html'><interface>SequencerOutput</interface></ulink>">
+<!ENTITY SequencerContext "<ulink url='&API;graph/sequencers/SequencerContext.html'><interface>SequencerContext</interface></ulink>">
<!ENTITY MimeTypeDetector "<ulink url='&API;graph/mimetype/MimeTypeDetector.html'><interface>MimeTypeDetector</interface></ulink>">
+<!ENTITY MockSequencerOutput "<ulink url='&API;graph/sequencers/MockSequencerOutput.html'><interface>MockSequencerOutput</interface></ulink>">
+<!ENTITY MockSequencerContext "<ulink url='&API;graph/sequencers/MockSequencerContext.html'><interface>MockSequencerContext</interface></ulink>">
<!-- Types in dna-repository -->
Modified: trunk/extensions/dna-sequencer-images/src/main/java/org/jboss/dna/sequencer/images/ImageMetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-images/src/main/java/org/jboss/dna/sequencer/images/ImageMetadataSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-images/src/main/java/org/jboss/dna/sequencer/images/ImageMetadataSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -22,7 +22,6 @@
package org.jboss.dna.sequencer.images;
import java.io.InputStream;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.properties.NameFactory;
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.properties.PathFactory;
@@ -87,13 +86,11 @@
/**
* {@inheritDoc}
*
- * @see StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext, ActivityMonitor)
+ * @see StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext)
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
- activityMonitor.beginTask(10, ImageSequencerI18n.sequencerTaskName);
+ SequencerContext context ) {
ImageMetadata metadata = new ImageMetadata();
metadata.setInput(stream);
@@ -104,8 +101,6 @@
if (!metadata.check()) {
metadata = null;
}
- activityMonitor.worked(5);
- if (activityMonitor.isCancelled()) return;
// Generate the output graph if we found useful metadata ...
if (metadata != null) {
@@ -129,7 +124,5 @@
output.setProperty(metadataNode, nameFactory.create(IMAGE_PHYSICAL_WIDTH_INCHES), metadata.getPhysicalWidthInch());
output.setProperty(metadataNode, nameFactory.create(IMAGE_PHYSICAL_HEIGHT_INCHES), metadata.getPhysicalHeightInch());
}
-
- activityMonitor.done();
}
}
Modified: trunk/extensions/dna-sequencer-images/src/test/java/org/jboss/dna/sequencer/images/ImageMetadataSequencerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-images/src/test/java/org/jboss/dna/sequencer/images/ImageMetadataSequencerTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-images/src/test/java/org/jboss/dna/sequencer/images/ImageMetadataSequencerTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -28,8 +28,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.sequencers.MockSequencerContext;
import org.jboss.dna.graph.sequencers.MockSequencerOutput;
import org.jboss.dna.graph.sequencers.SequencerContext;
@@ -46,7 +44,6 @@
private ImageMetadataSequencer sequencer;
private InputStream content;
private MockSequencerOutput output;
- private ActivityMonitor activityMonitor;
private URL cautionGif;
private URL cautionJpg;
private URL cautionPict;
@@ -59,7 +56,6 @@
context = new MockSequencerContext();
context.getNamespaceRegistry().register("image", "http://jboss.org/dna/images/1.0");
output = new MockSequencerOutput(context);
- activityMonitor = context.createActivityMonitor(MockI18n.passthrough, "Test Activity");
cautionGif = this.getClass().getClassLoader().getResource("caution.gif");
cautionJpg = this.getClass().getClassLoader().getResource("caution.jpg");
cautionPict = this.getClass().getClassLoader().getResource("caution.pict");
@@ -83,7 +79,7 @@
assertThat(url, is(notNullValue()));
content = url.openStream();
assertThat(content, is(notNullValue()));
- sequencer.sequence(content, output, context, activityMonitor);
+ sequencer.sequence(content, output, context);
assertThat(output.getPropertyValues("image:metadata", "jcr:primaryType"), is(new Object[] {"image:metadata"}));
assertThat(output.getPropertyValues("image:metadata", "jcr:mimeType"), is(new Object[] {"image/jpeg"}));
assertThat(output.getPropertyValues("image:metadata", "image:formatName"), is(new Object[] {"JPEG"}));
@@ -106,7 +102,7 @@
assertThat(url, is(notNullValue()));
content = url.openStream();
assertThat(content, is(notNullValue()));
- sequencer.sequence(content, output, context, activityMonitor);
+ sequencer.sequence(content, output, context);
assertThat(output.getPropertyValues("image:metadata", "jcr:primaryType"), is(new Object[] {"image:metadata"}));
assertThat(output.getPropertyValues("image:metadata", "jcr:mimeType"), is(new Object[] {"image/png"}));
assertThat(output.getPropertyValues("image:metadata", "image:formatName"), is(new Object[] {"PNG"}));
@@ -127,7 +123,7 @@
assertThat(url, is(notNullValue()));
content = url.openStream();
assertThat(content, is(notNullValue()));
- sequencer.sequence(content, output, context, activityMonitor);
+ sequencer.sequence(content, output, context);
assertThat(output.getPropertyValues("image:metadata", "jcr:mimeType"), is(new Object[] {"image/gif"}));
assertThat(output.getPropertyValues("image:metadata", "image:formatName"), is(new Object[] {"GIF"}));
assertThat(output.getPropertyValues("image:metadata", "image:width"), is(new Object[] {48}));
@@ -147,7 +143,7 @@
assertThat(url, is(notNullValue()));
content = url.openStream();
assertThat(content, is(notNullValue()));
- sequencer.sequence(content, output, context, activityMonitor);
+ sequencer.sequence(content, output, context);
assertThat(output.hasProperties(), is(false));
}
Modified: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaMetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaMetadataSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaMetadataSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -25,7 +25,6 @@
import java.io.InputStream;
import java.util.List;
import org.apache.commons.lang.StringUtils;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.properties.NameFactory;
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.properties.PathFactory;
@@ -175,22 +174,17 @@
* {@inheritDoc}
*
* @see org.jboss.dna.graph.sequencers.StreamSequencer#sequence(java.io.InputStream,
- * org.jboss.dna.graph.sequencers.SequencerOutput, org.jboss.dna.graph.sequencers.SequencerContext,
- * org.jboss.dna.common.monitor.ActivityMonitor)
+ * org.jboss.dna.graph.sequencers.SequencerOutput, org.jboss.dna.graph.sequencers.SequencerContext)
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
- activityMonitor.beginTask(10, JavaMetadataI18n.sequencerTaskName);
-
+ SequencerContext context ) {
JavaMetadata javaMetadata = null;
NameFactory nameFactory = context.getValueFactories().getNameFactory();
PathFactory pathFactory = context.getValueFactories().getPathFactory();
try {
- javaMetadata = JavaMetadata.instance(stream, JavaMetadataUtil.length(stream), null, activityMonitor.createSubtask(10));
- if (activityMonitor.isCancelled()) return;
+ javaMetadata = JavaMetadata.instance(stream, JavaMetadataUtil.length(stream), null);
} catch (IOException e) {
e.printStackTrace();
return;
@@ -720,7 +714,5 @@
// enumeration declaration
}
}
-
- activityMonitor.done();
}
}
Modified: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/metadata/JavaMetadata.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/metadata/JavaMetadata.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/metadata/JavaMetadata.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -24,7 +24,6 @@
import java.io.InputStream;
import java.util.List;
import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.sequencer.java.AbstractJavaMetadata;
import org.jboss.dna.sequencer.java.CompilationUnitParser;
import org.jboss.dna.sequencer.java.JavaMetadataUtil;
@@ -53,15 +52,12 @@
* @param inputStream - the <code>InputStream</code> in our case a <code>FileInputStream</code> of the java file.
* @param length - the length of the java file.
* @param encoding - the encoding that can be used.
- * @param activityMonitor - The basic <code>ActivityMonitor</code> that facilitates the updating and monitoring of progress
- * towards the completion of an activity.
* @return the new instace of <code>JavaMetadata</code>
* @see java.io.File#length()
*/
public static JavaMetadata instance( InputStream inputStream,
long length,
- String encoding,
- ActivityMonitor activityMonitor ) {
+ String encoding ) {
JavaMetadata javaMetadata = new JavaMetadata();
char[] source = null;
Modified: trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataSequencerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataSequencerTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataSequencerTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -29,8 +29,6 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.sequencers.MockSequencerContext;
import org.jboss.dna.graph.sequencers.MockSequencerOutput;
import org.jboss.dna.graph.sequencers.SequencerContext;
@@ -46,7 +44,6 @@
private JavaMetadataSequencer sequencer;
private InputStream content;
private MockSequencerOutput output;
- private ActivityMonitor activityMonitor;
private File source;
private SequencerContext context;
@@ -56,7 +53,6 @@
context.getNamespaceRegistry().register("java", "http://jboss.org/dna/java/1.0");
sequencer = new JavaMetadataSequencer();
output = new MockSequencerOutput(context);
- this.activityMonitor = context.createActivityMonitor(MockI18n.passthrough, "Test java monitor activity");
source = new File("src/test/workspace/projectX/src/org/acme/MySource.java");
}
@@ -79,7 +75,7 @@
public void shouldGenerateMetadataForJavaSourceFile() throws IOException {
content = getJavaSrc(source);
assertThat(content, is(notNullValue()));
- sequencer.sequence(content, output, context, activityMonitor);
+ sequencer.sequence(content, output, context);
assertThat(output.getPropertyValues("java:compilationUnit", "jcr:primaryType"), is(new Object[] {"java:compilationUnit"}));
// support sequencing package declaration( FQL name of the package). Not supported is to get information for package
Modified: trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataTest.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -69,7 +69,7 @@
public void beforeEach() throws Exception {
source = new File("src/test/workspace/projectX/src/org/acme/MySource.java");
stream = getJavaSrc(source);
- javaMetadata = JavaMetadata.instance(stream, JavaMetadataUtil.length(stream), null, null);
+ javaMetadata = JavaMetadata.instance(stream, JavaMetadataUtil.length(stream), null);
rootNode = CompilationUnitParser.runJLS3Conversion(JavaMetadataUtil.getJavaSourceFromTheInputStream(getJavaSrc(source),
source.length(),
null), true);
@@ -185,19 +185,18 @@
assertThat(parameterizedFieldMetadata2.getType(), is("A"));
assertThat(parameterizedFieldMetadata2.getVariables().get(0).getName(), is("o"));
-
SimpleTypeFieldMetadata simpleFieldMetadata = (SimpleTypeFieldMetadata)fields.get(4);
assertNotNull(simpleFieldMetadata);
assertTrue(simpleFieldMetadata.getModifiers().size() > 0);
assertThat(simpleFieldMetadata.getType(), is("X"));
assertThat(simpleFieldMetadata.getVariables().get(0).getName(), is("x"));
-
+
ArrayTypeFieldMetadata arrayTypeFieldMetadata1 = (ArrayTypeFieldMetadata)fields.get(5);
assertNotNull(arrayTypeFieldMetadata1);
assertTrue(arrayTypeFieldMetadata1.getModifiers().size() > 0);
assertThat(arrayTypeFieldMetadata1.getType(), is("int"));
assertThat(arrayTypeFieldMetadata1.getVariables().get(0).getName(), is("ia"));
-
+
ArrayTypeFieldMetadata arrayTypeFieldMetadata2 = (ArrayTypeFieldMetadata)fields.get(6);
assertNotNull(arrayTypeFieldMetadata2);
assertTrue(arrayTypeFieldMetadata2.getModifiers().size() > 0);
@@ -250,7 +249,7 @@
assertNotNull(methodTypeMemberMetadata5);
assertThat(methodTypeMemberMetadata5.getName(), is("doSomething"));
assertTrue(methodTypeMemberMetadata5.getParameters().size() > 0);
-
+
MethodTypeMemberMetadata methodTypeMemberMetadata6 = (MethodTypeMemberMetadata)methods.get(6);
assertTrue(methodTypeMemberMetadata6.getModifiers().size() == 1);
assertEquals(methodTypeMemberMetadata6.getReturnType().getType(), "double");
Modified: trunk/extensions/dna-sequencer-mp3/src/main/java/org/jboss/dna/sequencer/mp3/Mp3MetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-mp3/src/main/java/org/jboss/dna/sequencer/mp3/Mp3MetadataSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-mp3/src/main/java/org/jboss/dna/sequencer/mp3/Mp3MetadataSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -22,7 +22,6 @@
package org.jboss.dna.sequencer.mp3;
import java.io.InputStream;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.sequencers.SequencerContext;
import org.jboss.dna.graph.sequencers.SequencerOutput;
import org.jboss.dna.graph.sequencers.StreamSequencer;
@@ -62,12 +61,11 @@
/**
* {@inheritDoc}
*
- * @see StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext, ActivityMonitor)
+ * @see StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext)
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
+ SequencerContext context ) {
Mp3Metadata metadata = Mp3Metadata.instance(stream);
if (metadata != null) {
Modified: trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-msoffice/src/main/java/org/jboss/dna/sequencer/msoffice/MSOfficeMetadataSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -24,7 +24,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.sequencers.SequencerContext;
import org.jboss.dna.graph.sequencers.SequencerOutput;
import org.jboss.dna.graph.sequencers.StreamSequencer;
@@ -115,12 +114,9 @@
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
- activityMonitor.beginTask(10, MSOfficeMetadataI18n.sequencerTaskName);
+ SequencerContext context ) {
MSOfficeMetadata metadata = MSOfficeMetadataReader.instance(stream);
- activityMonitor.worked(3);
String mimeType = context.getMimeType();
@@ -147,7 +143,7 @@
} else {
return;
}
- activityMonitor.worked(1);
+
// process PowerPoint specific metadata
if (mimeType.equals("application/vnd.ms-powerpoint")) { // replace true with check if it's ppt file being sequenced
try {
@@ -165,7 +161,6 @@
context.getLogger(this.getClass()).debug(e, "Error while extracting the PowerPoint metadata");
}
}
- activityMonitor.worked(2);
if (mimeType.equals("application/vnd.ms-word")) {
// Sometime in the future this will sequence WORD Table of contents.
@@ -177,7 +172,6 @@
}
}
- activityMonitor.worked(2);
if (mimeType.equals("application/vnd.ms-excel")) {
try {
@@ -193,7 +187,5 @@
context.getLogger(this.getClass()).debug(e, "Error while extracting the Excel metadata");
}
}
- activityMonitor.worked(2);
- activityMonitor.done();
}
}
Modified: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -27,7 +27,6 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.JcrLexicon;
import org.jboss.dna.graph.properties.Name;
@@ -39,7 +38,6 @@
import org.jboss.dna.graph.sequencers.StreamSequencer;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
@@ -62,18 +60,15 @@
/**
* {@inheritDoc}
*
- * @see org.jboss.dna.graph.sequencers.StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext,
- * ActivityMonitor)
+ * @see org.jboss.dna.graph.sequencers.StreamSequencer#sequence(InputStream, SequencerOutput, SequencerContext)
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor monitor ) {
- monitor.beginTask(100.0, XmlSequencerI18n.sequencingXmlDocument);
+ SequencerContext context ) {
XMLReader reader;
try {
reader = XMLReaderFactory.createXMLReader();
- Handler handler = new Handler(output, context, monitor);
+ Handler handler = new Handler(output, context);
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
// Ensure handler acting as entity resolver 2
@@ -90,9 +85,7 @@
reader.parse(new InputSource(stream));
} catch (Exception error) {
context.getLogger(getClass()).error(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
- monitor.captureError(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
- } finally {
- monitor.done();
+ context.getProblems().addError(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
}
}
@@ -120,10 +113,7 @@
private final SequencerOutput output;
private final SequencerContext context;
- private final ActivityMonitor monitor;
- private double progress;
-
private Path path; // The DNA path of the node representing the current XML element
// Cached instances of the name factory and commonly referenced names
@@ -150,14 +140,11 @@
private String entity;
Handler( SequencerOutput output,
- SequencerContext context,
- ActivityMonitor monitor ) {
+ SequencerContext context ) {
assert output != null;
- assert monitor != null;
assert context != null;
this.output = output;
this.context = context;
- this.monitor = monitor;
// Initialize path to a an empty path relative to the SequencerOutput's target path.
path = context.getValueFactories().getPathFactory().createRelativePath();
// Cache name factory since it is frequently used
@@ -169,30 +156,12 @@
* {@inheritDoc}
* </p>
*
- * @see org.xml.sax.ext.DefaultHandler2#attributeDecl(java.lang.String, java.lang.String, java.lang.String,
- * java.lang.String, java.lang.String)
- */
- @Override
- public void attributeDecl( String name,
- String name2,
- String type,
- String mode,
- String value ) throws SAXException {
- stopIfCancelled();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
* @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
@Override
public void characters( char[] ch,
int start,
- int length ) throws SAXException {
- stopIfCancelled();
+ int length ) {
String content = String.valueOf(ch, start, length);
// Check if data should be appended to previously parsed CDATA
if (cDataBuilder == null) {
@@ -215,7 +184,6 @@
cDataBuilder.append(ch, start, length);
// Text within builder will be output at the end of CDATA
}
- updateProgress();
}
/**
@@ -228,14 +196,12 @@
@Override
public void comment( char[] ch,
int start,
- int length ) throws SAXException {
- stopIfCancelled();
+ int length ) {
// Output separate nodes for each comment since multiple are allowed
startElement(DnaXmlLexicon.COMMENT);
output.setProperty(path, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.COMMENT);
output.setProperty(path, DnaXmlLexicon.COMMENT_CONTENT, String.valueOf(ch, start, length));
endElement();
- updateProgress();
}
/**
@@ -243,30 +209,15 @@
* {@inheritDoc}
* </p>
*
- * @see org.xml.sax.ext.DefaultHandler2#elementDecl(java.lang.String, java.lang.String)
- */
- @Override
- public void elementDecl( String name,
- String model ) throws SAXException {
- stopIfCancelled();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
* @see org.xml.sax.ext.DefaultHandler2#endCDATA()
*/
@Override
- public void endCDATA() throws SAXException {
- stopIfCancelled();
+ public void endCDATA() {
// Output CDATA built in characters() method
output.setProperty(path, DnaXmlLexicon.CDATA_CONTENT, cDataBuilder.toString());
endElement();
// Null-out builder to free memory
cDataBuilder = null;
- updateProgress();
}
private void endContent() {
@@ -287,30 +238,6 @@
}
}
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.helpers.DefaultHandler#endDocument()
- */
- @Override
- public void endDocument() throws SAXException {
- stopIfCancelled();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
- * @see org.xml.sax.ext.DefaultHandler2#endDTD()
- */
- @Override
- public void endDTD() throws SAXException {
- stopIfCancelled();
- }
-
private void endElement() {
// Recover parent's path, namespace, and indexedName map, clearing the ended element's map to free memory
path = path.getParent();
@@ -329,12 +256,10 @@
@Override
public void endElement( String uri,
String localName,
- String name ) throws SAXException {
- stopIfCancelled();
+ String name ) {
// Check if content still needs to be output
endContent();
endElement();
- updateProgress();
}
/**
@@ -345,10 +270,8 @@
* @see org.xml.sax.ext.DefaultHandler2#endEntity(java.lang.String)
*/
@Override
- public void endEntity( String name ) throws SAXException {
- stopIfCancelled();
+ public void endEntity( String name ) {
entity = null;
- updateProgress();
}
/**
@@ -361,7 +284,7 @@
@Override
public void error( SAXParseException error ) {
context.getLogger(XmlSequencer.class).error(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
- monitor.captureError(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
+ context.getProblems().addError(error, XmlSequencerI18n.errorSequencingXmlDocument, error);
}
/**
@@ -374,8 +297,7 @@
@Override
public void externalEntityDecl( String name,
String publicId,
- String systemId ) throws SAXException {
- stopIfCancelled();
+ String systemId ) {
// Add "synthetic" entity container to path to help prevent name collisions with XML elements
Name entityName = DnaDtdLexicon.ENTITY;
startElement(entityName);
@@ -384,7 +306,6 @@
output.setProperty(path, nameFactory.create(DnaDtdLexicon.PUBLIC_ID), publicId);
output.setProperty(path, nameFactory.create(DnaDtdLexicon.SYSTEM_ID), systemId);
endElement();
- updateProgress();
}
/**
@@ -397,7 +318,7 @@
@Override
public void fatalError( SAXParseException error ) {
context.getLogger(XmlSequencer.class).error(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
- monitor.captureError(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
+ context.getProblems().addError(error, XmlSequencerI18n.fatalErrorSequencingXmlDocument, error);
}
private Name getDefaultPrimaryType() {
@@ -412,26 +333,11 @@
* {@inheritDoc}
* </p>
*
- * @see org.xml.sax.helpers.DefaultHandler#ignorableWhitespace(char[], int, int)
- */
- @Override
- public void ignorableWhitespace( char[] ch,
- int start,
- int length ) throws SAXException {
- stopIfCancelled();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
* @see org.xml.sax.ext.DefaultHandler2#internalEntityDecl(java.lang.String, java.lang.String)
*/
@Override
public void internalEntityDecl( String name,
- String value ) throws SAXException {
- stopIfCancelled();
+ String value ) {
// Add "synthetic" entity container to path to help prevent name collisions with XML elements
Name entityName = DnaDtdLexicon.ENTITY;
startElement(entityName);
@@ -439,7 +345,6 @@
output.setProperty(path, DnaDtdLexicon.NAME, name);
output.setProperty(path, DnaDtdLexicon.VALUE, value);
endElement();
- updateProgress();
}
/**
@@ -447,26 +352,11 @@
* {@inheritDoc}
* </p>
*
- * @see org.xml.sax.helpers.DefaultHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String)
- */
- @Override
- public void notationDecl( String name,
- String publicId,
- String systemId ) throws SAXException {
- stopIfCancelled();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
* @see org.xml.sax.helpers.DefaultHandler#processingInstruction(java.lang.String, java.lang.String)
*/
@Override
public void processingInstruction( String target,
- String data ) throws SAXException {
- stopIfCancelled();
+ String data ) {
// Output separate nodes for each instruction since multiple are allowed
Name name = DnaXmlLexicon.PROCESSING_INSTRUCTION;
startElement(name);
@@ -474,7 +364,6 @@
output.setProperty(path, DnaXmlLexicon.TARGET, target);
output.setProperty(path, DnaXmlLexicon.PROCESSING_INSTRUCTION_CONTENT, data);
endElement();
- updateProgress();
}
/**
@@ -482,28 +371,14 @@
* {@inheritDoc}
* </p>
*
- * @see org.xml.sax.helpers.DefaultHandler#skippedEntity(java.lang.String)
- */
- @Override
- public void skippedEntity( String name ) throws SAXException {
- stopIfCancelled();
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
* @see org.xml.sax.ext.DefaultHandler2#startCDATA()
*/
@Override
- public void startCDATA() throws SAXException {
- stopIfCancelled();
+ public void startCDATA() {
// Output separate nodes for each CDATA since multiple are allowed
startElement(DnaXmlLexicon.CDATA);
// Prepare builder for concatenating consecutive lines of CDATA
cDataBuilder = new StringBuilder();
- updateProgress();
}
/**
@@ -514,10 +389,8 @@
* @see org.xml.sax.helpers.DefaultHandler#startDocument()
*/
@Override
- public void startDocument() throws SAXException {
- stopIfCancelled();
+ public void startDocument() {
output.setProperty(path, JcrLexicon.PRIMARY_TYPE, DnaXmlLexicon.DOCUMENT);
- updateProgress();
}
/**
@@ -530,12 +403,10 @@
@Override
public void startDTD( String name,
String publicId,
- String systemId ) throws SAXException {
- stopIfCancelled();
+ String systemId ) {
output.setProperty(path, DnaDtdLexicon.NAME, name);
output.setProperty(path, DnaDtdLexicon.PUBLIC_ID, publicId);
output.setProperty(path, DnaDtdLexicon.SYSTEM_ID, systemId);
- updateProgress();
}
private void startElement( Name name ) {
@@ -579,8 +450,7 @@
public void startElement( String uri,
String localName,
String name,
- Attributes attributes ) throws SAXException {
- stopIfCancelled();
+ Attributes attributes ) {
// Look for the "jcr:name" attribute, and use that if it's there
Name type = getDefaultPrimaryType();
Name nameObj = nameFactory.create(name);
@@ -611,7 +481,6 @@
}
output.setProperty(path, nameFactory.create(ns.length() == 0 ? inheritedNs : ns, attrLocalName), value);
}
- updateProgress();
}
/**
@@ -622,10 +491,8 @@
* @see org.xml.sax.ext.DefaultHandler2#startEntity(java.lang.String)
*/
@Override
- public void startEntity( String name ) throws SAXException {
- stopIfCancelled();
+ public void startEntity( String name ) {
entity = name;
- updateProgress();
}
/**
@@ -637,58 +504,25 @@
*/
@Override
public void startPrefixMapping( String prefix,
- String uri ) throws SAXException {
- stopIfCancelled();
+ String uri ) {
// Register any unregistered namespaces
NamespaceRegistry registry = context.getNamespaceRegistry();
if (!registry.isRegisteredNamespaceUri(uri)) {
registry.register(prefix, uri);
}
- updateProgress();
}
- private void stopIfCancelled() throws SAXException {
- if (monitor.isCancelled()) {
- throw new SAXException(XmlSequencerI18n.canceledSequencingXmlDocument.text());
- }
- }
-
/**
* <p>
* {@inheritDoc}
* </p>
*
- * @see org.xml.sax.helpers.DefaultHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String,
- * java.lang.String)
- */
- @Override
- public void unparsedEntityDecl( String name,
- String publicId,
- String systemId,
- String notationName ) throws SAXException {
- stopIfCancelled();
- }
-
- private void updateProgress() {
- if (progress == 100.0) {
- progress = 1;
- } else {
- progress++;
- }
- monitor.worked(progress);
- }
-
- /**
- * <p>
- * {@inheritDoc}
- * </p>
- *
* @see org.xml.sax.helpers.DefaultHandler#warning(org.xml.sax.SAXParseException)
*/
@Override
public void warning( SAXParseException warning ) {
context.getLogger(XmlSequencer.class).warn(warning, XmlSequencerI18n.warningSequencingXmlDocument);
- monitor.captureWarning(warning, XmlSequencerI18n.warningSequencingXmlDocument, warning);
+ context.getProblems().addWarning(warning, XmlSequencerI18n.warningSequencingXmlDocument, warning);
}
}
Modified: trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerI18n.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerI18n.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-xml/src/main/java/org/jboss/dna/sequencer/xml/XmlSequencerI18n.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -34,7 +34,7 @@
public static I18n errorSequencingXmlDocument;
public static I18n fatalErrorSequencingXmlDocument;
- public static I18n sequencingXmlDocument;
+ // public static I18n sequencingXmlDocument;
public static I18n canceledSequencingXmlDocument;
public static I18n warningSequencingXmlDocument;
Modified: trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-xml/src/test/java/org/jboss/dna/sequencer/xml/XmlSequencerTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -28,8 +28,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
-import org.jboss.dna.common.i18n.MockI18n;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.sequencers.MockSequencerContext;
import org.jboss.dna.graph.sequencers.MockSequencerOutput;
@@ -61,7 +59,6 @@
private XmlSequencer sequencer;
private InputStream stream;
private MockSequencerOutput output;
- private ActivityMonitor monitor;
private URL xml1;
private URL xml2;
private URL xml3;
@@ -74,7 +71,6 @@
sequencer = new XmlSequencer();
context = new MockSequencerContext();
output = new MockSequencerOutput(context);
- monitor = context.createActivityMonitor(MockI18n.passthrough, "Test activity");
xml1 = this.getClass().getClassLoader().getResource("jackrabbitInMemoryTestRepositoryConfig.xml");
assertThat(xml1, is(notNullValue()));
xml2 = this.getClass().getClassLoader().getResource("master.xml");
@@ -201,7 +197,7 @@
private void verifyDocument( URL url ) throws IOException {
stream = url.openStream();
assertThat(stream, is(notNullValue()));
- sequencer.sequence(stream, output, context, monitor);
+ sequencer.sequence(stream, output, context);
verifyName("", "jcr:primaryType", DOCUMENT);
}
Modified: trunk/extensions/dna-sequencer-zip/pom.xml
===================================================================
--- trunk/extensions/dna-sequencer-zip/pom.xml 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-zip/pom.xml 2008-11-10 20:21:55 UTC (rev 617)
@@ -33,6 +33,14 @@
<artifactId>junit-dep</artifactId>
<version>4.4</version>
</dependency>
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ </dependency>
<!--
Logging (require SLF4J API for compiling, but use Log4J and its SLF4J binding for testing)
-->
Modified: trunk/extensions/dna-sequencer-zip/src/main/java/org/jboss/dna/sequencer/zip/ZipSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-zip/src/main/java/org/jboss/dna/sequencer/zip/ZipSequencer.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-zip/src/main/java/org/jboss/dna/sequencer/zip/ZipSequencer.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -26,7 +26,6 @@
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-import org.jboss.dna.common.monitor.ActivityMonitor;
import org.jboss.dna.graph.sequencers.SequencerContext;
import org.jboss.dna.graph.sequencers.SequencerOutput;
import org.jboss.dna.graph.sequencers.StreamSequencer;
@@ -41,13 +40,11 @@
* {@inheritDoc}
*
* @see org.jboss.dna.graph.sequencers.StreamSequencer#sequence(java.io.InputStream,
- * org.jboss.dna.graph.sequencers.SequencerOutput, org.jboss.dna.graph.sequencers.SequencerContext,
- * org.jboss.dna.common.monitor.ActivityMonitor)
+ * org.jboss.dna.graph.sequencers.SequencerOutput, org.jboss.dna.graph.sequencers.SequencerContext)
*/
public void sequence( InputStream stream,
SequencerOutput output,
- SequencerContext context,
- ActivityMonitor activityMonitor ) {
+ SequencerContext context ) {
try {
ZipInputStream in = new ZipInputStream(stream);
ZipEntry entry = in.getNextEntry();
Modified: trunk/extensions/dna-sequencer-zip/src/test/java/org/jboss/dna/sequencer/zip/ZipSequencerTest.java
===================================================================
--- trunk/extensions/dna-sequencer-zip/src/test/java/org/jboss/dna/sequencer/zip/ZipSequencerTest.java 2008-11-05 18:14:32 UTC (rev 616)
+++ trunk/extensions/dna-sequencer-zip/src/test/java/org/jboss/dna/sequencer/zip/ZipSequencerTest.java 2008-11-10 20:21:55 UTC (rev 617)
@@ -24,6 +24,7 @@
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
import java.io.InputStream;
import org.jboss.dna.graph.sequencers.SequencerContext;
import org.junit.After;
@@ -55,8 +56,8 @@
InputStream is = getTestZip("testzip.zip");
ZipSequencer zs = new ZipSequencer();
SequencingOutputTestClass seqtest = new SequencingOutputTestClass();
- SequencerContext context = null;
- zs.sequence(is, seqtest, context, null);
+ SequencerContext context = mock(SequencerContext.class);
+ zs.sequence(is, seqtest, context);
assertThat(seqtest.properties.get(2).getPath(), is("zip:content/test subfolder/test2.txt/jcr:content"));
}
17 years, 2 months
DNA SVN: r616 - in trunk: dna-common/src/test/java/org/jboss/dna/common/util and 11 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-05 13:14:32 -0500 (Wed, 05 Nov 2008)
New Revision: 616
Added:
trunk/dna-common/src/main/java/org/jboss/dna/common/util/Base64.java
trunk/dna-common/src/test/java/org/jboss/dna/common/util/Base64Test.java
Removed:
trunk/dna-common/src/main/java/org/jboss/dna/common/util/DateUtil.java
trunk/dna-common/src/test/java/org/jboss/dna/common/util/DateUtilTest.java
Modified:
trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java
trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/Location.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicProperty.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/InMemoryBinary.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/JodaDateTime.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CreateNodeRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java
trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphImporterTest.java
trunk/dna-graph/src/test/java/org/jboss/dna/graph/connectors/SimpleRepository.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/rules/RuleService.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerOutputMap.java
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java
trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/merge/MergePlan.java
trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheConnection.java
Log:
DNA-247 - Remove DateUtil class and StringUtil.readableString(...) methods
http://jira.jboss.com/jira/browse/DNA-247
Removed the DateUtil class, since it provided a subset of the functionality that is already available in Joda Time, which is being used by 'dna-graph'. Also deleted the StringUtil.readableString(...) methods, replacing them with calls to List.toString(), Set.toString(), Property.toString(), and Map.toString(). Since the toString() method on arrays is crappy, used "Arrays.asList(array).toString()".
Ensured that Property.toString() returns a readable string, and that the Value classes all have readable toString() methods. Most were find, but the InMemoryBinary value class had a poor toString() method, so this was changed to output the Base64 encoding of the binary content. To do this, I added a Base64 utility class based on Federate's class (which was simplified from the public domain class at http://iharder.sourceforge.net/current/java/base64/).
Added: trunk/dna-common/src/main/java/org/jboss/dna/common/util/Base64.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/util/Base64.java (rev 0)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/util/Base64.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -0,0 +1,404 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.common.util;
+
+/**
+ * <p>
+ * Encodes and decodes to and from Base64 notation.
+ * </p>
+ * <p>
+ * Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.
+ * </p>
+ * <p>
+ * The <tt>options</tt> parameter, which appears in a few places, is used to pass several pieces of information to the encoder. In
+ * the "higher level" methods such as encodeBytes( bytes, options ) the options parameter can be used to indicate such things as
+ * first gzipping the bytes before encoding them, not inserting linefeeds (though that breaks strict Base64 compatibility), and
+ * encoding using the URL-safe and Ordered dialects.
+ * </p>
+ * <p>
+ * The constants defined in Base64 can be OR-ed together to combine options, so you might make a call like this:
+ * </p>
+ * <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DONT_BREAK_LINES );</code>
+ * <p>
+ * to compress the data before encoding it and then making the output have no newline characters.
+ * </p>
+ * <p>
+ * Change Log:
+ * </p>
+ * <ul>
+ * <li>v2.2.2 - Fixed encodeFileToFile and decodeFileToFile to use the Base64.InputStream class to encode and decode on the fly
+ * which uses less memory than encoding/decoding an entire file into memory before writing.</li>
+ * <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug when using very small files (~< 40 bytes).</li>
+ * <li>v2.2 - Added some helper methods for encoding/decoding directly from one file to the next. Also added a main() method to
+ * support command line encoding/decoding from one file to the next. Also added these Base64 dialects:
+ * <ol>
+ * <li>The default is RFC3548 format.</li>
+ * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates URL and file name friendly format as described in
+ * Section 4 of RFC3548. http://www.faqs.org/rfcs/rfc3548.html</li>
+ * <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates URL and file name friendly format that preserves
+ * lexical ordering as described in http://www.faqs.org/qa/rfcc-1940.html</li>
+ * </ol>
+ * Special thanks to Jim Kellerman at <a href="http://www.powerset.com/">http://www.powerset.com/</a> for contributing the new
+ * Base64 dialects.</li>
+ * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added some convenience methods for reading and writing
+ * to and from files.</li>
+ * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems with other encodings (like EBCDIC).</li>
+ * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the encoded data was a single byte.</li>
+ * <li>v2.0 - I got rid of methods that used booleans to set options. Now everything is more consolidated and cleaner. The code
+ * now detects when data that's being decoded is gzip-compressed and will decompress it automatically. Generally things are
+ * cleaner. You'll probably have to change some method calls that you were making to support the new options format (<tt>int</tt>s
+ * that you "OR" together).</li>
+ * <li>v1.5.1 - Fixed bug when decompressing and decoding to a byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
+ * Added the ability to "suspend" encoding in the Output Stream so you can turn on and off the encoding if you need to embed
+ * base64 data in an otherwise "normal" stream (like an XML file).</li>
+ * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. This helps when using GZIP streams. Added the
+ * ability to GZip-compress objects before encoding them.</li>
+ * <li>v1.4 - Added helper methods to read/write files.</li>
+ * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
+ * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream where last buffer being read, if not
+ * completely full, was not returned.</li>
+ * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
+ * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
+ * </ul>
+ * <p>
+ * I am placing this code in the Public Domain. Do with it as you will. This software comes with no guarantees or warranties but
+ * with plenty of well-wishing instead! Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
+ * periodically to check for updates or to contribute improvements.
+ * </p>
+ *
+ * @author Robert Harder
+ * @author rob(a)iharder.net
+ * @version 2.2.2
+ */
+public class Base64 {
+
+ /* ******** P R I V A T E F I E L D S ******** */
+
+ /** Maximum line length (76) of Base64 output. */
+ private final static int MAX_LINE_LENGTH = 76;
+
+ /** The equals sign (=) as a byte. */
+ private final static byte EQUALS_SIGN = (byte)'=';
+
+ /** The new line character (\n) as a byte. */
+ private final static byte NEW_LINE = (byte)'\n';
+
+ /** Preferred encoding. */
+ private final static String PREFERRED_ENCODING = "UTF-8";
+
+ private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
+ private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
+
+ /* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
+
+ /** The 64 valid Base64 values. */
+ /* Host platform me be something funny like EBCDIC, so we hardcode these values. */
+ private final static byte[] _STANDARD_ALPHABET = {(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F',
+ (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q',
+ (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b',
+ (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m',
+ (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x',
+ (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8',
+ (byte)'9', (byte)'+', (byte)'/'};
+
+ /**
+ * Translates a Base64 value to either its 6-bit reconstruction value or a negative number indicating some other meaning.
+ **/
+ private final static byte[] _STANDARD_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
+ -5, -5, // Whitespace: Tab and Linefeed
+ -9, -9, // Decimal 11 - 12
+ -5, // Whitespace: Carriage Return
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
+ -9, -9, -9, -9, -9, // Decimal 27 - 31
+ -5, // Whitespace: Space
+ -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
+ 62, // Plus sign at decimal 43
+ -9, -9, -9, // Decimal 44 - 46
+ 63, // Slash at decimal 47
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
+ -9, -9, -9, // Decimal 58 - 60
+ -1, // Equals sign at decimal 61
+ -9, -9, -9, // Decimal 62 - 64
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
+ 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
+ -9, -9, -9, -9, -9, -9, // Decimal 91 - 96
+ 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
+ -9, -9, -9, -9 // Decimal 123 - 126
+ /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
+ -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
+ };
+
+ /** Defeats instantiation. */
+ private Base64() {
+ }
+
+ /* ******** E N C O D I N G M E T H O D S ******** */
+
+ /**
+ * <p>
+ * Encodes up to three bytes of the array <var>source</var> and writes the resulting four Base64 bytes to
+ * <var>destination</var>. The source and destination arrays can be manipulated anywhere along their length by specifying
+ * <var>srcOffset</var> and <var>destOffset</var>. This method does not check to make sure your arrays are large enough to
+ * accomodate <var>srcOffset</var> + 3 for the <var>source</var> array or <var>destOffset</var> + 4 for the
+ * <var>destination</var> array. The actual number of significant bytes in your array is given by <var>numSigBytes</var>.
+ * </p>
+ * <p>
+ * This is the lowest level of the encoding methods with all possible parameters.
+ * </p>
+ *
+ * @param source the array to convert
+ * @param srcOffset the index where conversion begins
+ * @param numSigBytes the number of significant bytes in your array
+ * @param destination the array to hold the conversion
+ * @param destOffset the index where output will be put
+ * @return the <var>destination</var> array
+ * @since 1.3
+ */
+ private static byte[] encode3to4( byte[] source,
+ int srcOffset,
+ int numSigBytes,
+ byte[] destination,
+ int destOffset ) {
+ byte[] ALPHABET = _STANDARD_ALPHABET;
+
+ // 1 2 3
+ // 01234567890123456789012345678901 Bit position
+ // --------000000001111111122222222 Array position from threeBytes
+ // --------| || || || | Six bit groups to index ALPHABET
+ // >>18 >>12 >> 6 >> 0 Right shift necessary
+ // 0x3f 0x3f 0x3f Additional AND
+
+ // Create buffer with zero-padding if there are only one or two
+ // significant bytes passed in the array.
+ // We have to shift left 24 in order to flush out the 1's that appear
+ // when Java treats a value as negative that is cast from a byte to an int.
+ int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
+ | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
+ | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
+
+ switch (numSigBytes) {
+ case 3:
+ destination[destOffset] = ALPHABET[(inBuff >>> 18)];
+ destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
+ destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
+ destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
+ return destination;
+
+ case 2:
+ destination[destOffset] = ALPHABET[(inBuff >>> 18)];
+ destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
+ destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
+ destination[destOffset + 3] = EQUALS_SIGN;
+ return destination;
+
+ case 1:
+ destination[destOffset] = ALPHABET[(inBuff >>> 18)];
+ destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
+ destination[destOffset + 2] = EQUALS_SIGN;
+ destination[destOffset + 3] = EQUALS_SIGN;
+ return destination;
+
+ default:
+ return destination;
+ } // end switch
+ } // end encode3to4
+
+ /**
+ * Encodes a byte array into Base64 notation. Does not GZip-compress data.
+ *
+ * @param source The data to convert
+ * @return the encoded data
+ * @since 1.4
+ */
+ public static String encodeBytes( byte[] source ) {
+ // Convert option to boolean in way that code likes it.
+ boolean breakLines = false;
+ int len = source.length;
+ int len43 = len * 4 / 3;
+ byte[] outBuff = new byte[(len43) // Main 4:3
+ + ((len % 3) > 0 ? 4 : 0) // Account for padding
+ + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines
+ int d = 0;
+ int e = 0;
+ int len2 = len - 2;
+ int lineLength = 0;
+ for (; d < len2; d += 3, e += 4) {
+ encode3to4(source, d, 3, outBuff, e);
+
+ lineLength += 4;
+ if (breakLines && lineLength == MAX_LINE_LENGTH) {
+ outBuff[e + 4] = NEW_LINE;
+ e++;
+ lineLength = 0;
+ } // end if: end of line
+ } // en dfor: each piece of array
+
+ if (d < len) {
+ encode3to4(source, d, len - d, outBuff, e);
+ e += 4;
+ } // end if: some padding needed
+
+ // Return value according to relevant encoding.
+ try {
+ return new String(outBuff, 0, e, PREFERRED_ENCODING);
+ } // end try
+ catch (java.io.UnsupportedEncodingException uue) {
+ return new String(outBuff, 0, e);
+ } // end catch
+
+ } // end else: don't compress
+
+ /* ******** D E C O D I N G M E T H O D S ******** */
+
+ /**
+ * Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three of them) to
+ * <var>destination</var>. The source and destination arrays can be manipulated anywhere along their length by specifying
+ * <var>srcOffset</var> and <var>destOffset</var>. This method does not check to make sure your arrays are large enough to
+ * accomodate <var>srcOffset</var> + 4 for the <var>source</var> array or <var>destOffset</var> + 3 for the
+ * <var>destination</var> array. This method returns the actual number of bytes that were converted from the Base64 encoding.
+ * <p>
+ * This is the lowest level of the decoding methods with all possible parameters.
+ * </p>
+ *
+ * @param source the array to convert
+ * @param srcOffset the index where conversion begins
+ * @param destination the array to hold the conversion
+ * @param destOffset destination offset
+ * @return the number of decoded bytes converted
+ * @since 1.3
+ */
+ private static int decode4to3( byte[] source,
+ int srcOffset,
+ byte[] destination,
+ int destOffset ) {
+ byte[] DECODABET = _STANDARD_DECODABET;
+
+ // Example: Dk==
+ if (source[srcOffset + 2] == EQUALS_SIGN) {
+ // Two ways to do the same thing. Don't know which way I like best.
+ // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
+ // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
+ int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
+
+ destination[destOffset] = (byte)(outBuff >>> 16);
+ return 1;
+ }
+
+ // Example: DkL=
+ else if (source[srcOffset + 3] == EQUALS_SIGN) {
+ // Two ways to do the same thing. Don't know which way I like best.
+ // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
+ // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
+ // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
+ int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
+ | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
+
+ destination[destOffset] = (byte)(outBuff >>> 16);
+ destination[destOffset + 1] = (byte)(outBuff >>> 8);
+ return 2;
+ }
+
+ // Example: DkLE
+ else {
+ // Two ways to do the same thing. Don't know which way I like best.
+ // int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
+ // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
+ // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
+ // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
+ int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18) | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
+ | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6) | ((DECODABET[source[srcOffset + 3]] & 0xFF));
+
+ destination[destOffset] = (byte)(outBuff >> 16);
+ destination[destOffset + 1] = (byte)(outBuff >> 8);
+ destination[destOffset + 2] = (byte)(outBuff);
+
+ return 3;
+ }
+ } // end decodeToBytes
+
+ /**
+ * Decodes data from Base64 notation.
+ *
+ * @param s the string to decode
+ * @return the decoded data
+ * @since 1.4
+ */
+ public static byte[] decode( String s ) {
+ byte[] source;
+ try {
+ source = s.getBytes(PREFERRED_ENCODING);
+ } // end try
+ catch (java.io.UnsupportedEncodingException uee) {
+ source = s.getBytes();
+ } // end catch
+ // </change>
+ if (source.length % 4 != 0) {
+ throw new IllegalArgumentException("Source bytes are not valid"); //$NON-NLS-1$
+ }
+ byte[] DECODABET = _STANDARD_DECODABET;
+ int len = source.length;
+ byte[] outBuff = new byte[len * 3 / 4]; // Upper limit on size of output
+ int outBuffPosn = 0;
+
+ byte[] b4 = new byte[4];
+ int b4Posn = 0;
+ int i = 0;
+ byte sbiCrop = 0;
+ byte sbiDecode = 0;
+ for (i = 0; i < len; i++) {
+ sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
+ sbiDecode = DECODABET[sbiCrop];
+
+ if (sbiDecode >= WHITE_SPACE_ENC) // White space, Equals sign or better
+ {
+ if (sbiDecode >= EQUALS_SIGN_ENC) {
+ b4[b4Posn++] = sbiCrop;
+ if (b4Posn > 3) {
+ outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn);
+ b4Posn = 0;
+
+ // If that was the equals sign, break out of 'for' loop
+ if (sbiCrop == EQUALS_SIGN) break;
+ } // end if: quartet built
+
+ } // end if: equals sign or better
+
+ } // end if: white space, equals sign or better
+ else {
+ throw new IllegalArgumentException("Source bytes are not valid"); //$NON-NLS-1$
+ } // end else:
+ } // each input character
+
+ byte[] out = new byte[outBuffPosn];
+ System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
+ return out;
+ } // end decode
+}
Property changes on: trunk/dna-common/src/main/java/org/jboss/dna/common/util/Base64.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted: trunk/dna-common/src/main/java/org/jboss/dna/common/util/DateUtil.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/util/DateUtil.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/util/DateUtil.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -1,277 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.dna.common.util;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.Locale;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import net.jcip.annotations.ThreadSafe;
-import org.jboss.dna.common.CommonI18n;
-
-/**
- * Utilities for working with dates.
- * <p>
- * Many of the methods that convert dates to and from strings utilize the <a href="http://en.wikipedia.org/wiki/ISO_8601">ISO
- * 8601:2004</a> standard string format <code>yyyy-MM-ddTHH:mm:ss.SSSZ</code>, where <blockquote>
- *
- * <pre>
- * Symbol Meaning Presentation Example
- * ------ ------- ------------ -------
- * y year (Number) 1996
- * M month in year (Number) 07
- * d day in month (Number) 10
- * h hour in am/pm (1˜12) (Number) 12
- * H hour in day (0˜23) (Number) 0
- * m minute in hour (Number) 30
- * s second in minute (Number) 55
- * S millisecond (Number) 978
- * Z time zone (Number) -0600
- * </pre>
- *
- * </blockquote>
- * </p>
- * <p>
- * This class is written to be thread safe. As {@link SimpleDateFormat} is not threadsafe, no shared instances are used.
- * </p>
- * @author Randall Hauch
- */
-@ThreadSafe
-public class DateUtil {
-
- public static final String ISO_8601_2004_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
-
- /**
- * Parse the date contained in the supplied string. The date must follow one of the standard ISO 8601 formats, of the form
- * <code><i>datepart</i>T<i>timepart</i></code>, where <code><i>datepart</i></code> is one of the following forms:
- * <p>
- * <dl>
- * <dt>YYYYMMDD</dt>
- * <dd>The 4-digit year, the 2-digit month (00-12), and the 2-digit day of the month (00-31). The month and day are optional,
- * but the month is required if the day is given.</dd>
- * <dt>YYYY-MM-DD</dt>
- * <dd>The 4-digit year, the 2-digit month (00-12), and the 2-digit day of the month (00-31). The month and day are optional,
- * but the month is required if the day is given.</dd>
- * <dt>YYYY-Www-D</dt>
- * <dd>The 4-digit year followed by 'W', the 2-digit week number (00-53), and the day of the week (1-7). The day of week
- * number is optional.</dd>
- * <dt>YYYYWwwD</dt>
- * <dd>The 4-digit year followed by 'W', the 2-digit week number (00-53), and the day of the week (1-7). The day of week
- * number is optional.</dd>
- * <dt>YYYY-DDD</dt>
- * <dd>The 4-digit year followed by the 3-digit day of the year (000-365)</dd>
- * <dt>YYYYDDD</dt>
- * <dd>The 4-digit year followed by the 3-digit day of the year (000-365)</dd>
- * </dl>
- * </p>
- * <p>
- * The <code><i>timepart</i></code> consists of one of the following forms that contain the 2-digit hour (00-24), the
- * 2-digit minutes (00-59), the 2-digit seconds (00-59), and the 1-to-3 digit milliseconds. The minutes, seconds and
- * milliseconds are optional, but any component is required if it is followed by another component (e.g., minutes are required
- * if the seconds are given).
- * <dl>
- * <dt>hh:mm:ss.SSS</dt>
- * <dt>hhmmssSSS</dt>
- * </dl>
- * </p>
- * <p>
- * followed by one of the following time zone definitions:
- * <dt>Z</dt>
- * <dd>The uppercase or lowercase 'Z' to denote UTC time</dd>
- * <dt>±hh:mm</dt>
- * <dd>The 2-digit hour and the 2-digit minute offset from UTC</dd>
- * <dt>±hhmm</dt>
- * <dd>The 2-digit hour and the 2-digit minute offset from UTC</dd>
- * <dt>±hh</dt>
- * <dd>The 2-digit hour offset from UTC</dd>
- * <dt>hh:mm</dt>
- * <dd>The 2-digit hour and the 2-digit minute offset from UTC</dd>
- * <dt>hhmm</dt>
- * <dd>The 2-digit hour and the 2-digit minute offset from UTC</dd>
- * <dt>hh</dt>
- * <dd>The 2-digit hour offset from UTC</dd>
- * </dl>
- * </p>
- * @param dateString the string containing the date to be parsed
- * @return the parsed date as a {@link Calendar} object.
- * @throws ParseException if there is a problem parsing the string
- */
- public static Calendar getCalendarFromStandardString( final String dateString ) throws ParseException {
- // Example: 2008-02-16T12:30:45.123-0600
- // Example: 2008-W06-6
- // Example: 2008-053
- //
- // Group Optional Field Description
- // ----- -------- --------- ------------------------------------------
- // 1 no 2008 4 digit year as a number
- // 2 yes 02-16 or W06-6 or 053
- // 3 yes W06-6
- // 4 yes 06 2 digit week number (00-59)
- // 5 yes 6 1 digit day of week as a number (1-7)
- // 6 yes 02-16
- // 7 yes 02 2 digit month as a number (00-19)
- // 8 yes -16
- // 9 yes 16 2 digit day of month as a number (00-39)
- // 10 yes 02 2 digit month as a number (00-19)
- // 11 yes 16 2 digit day of month as a number (00-39)
- // 12 yes 234 3 digit day of year as a number (000-399)
- // 13 yes T12:30:45.123-0600
- // 14 yes 12 2 digit hour as a number (00-29)
- // 15 yes 30 2 digit minute as a number (00-59)
- // 16 yes :45.123
- // 17 yes 45 2 digit second as a number (00-59)
- // 18 yes .123
- // 19 yes 123 1, 2 or 3 digit milliseconds as a number (000-999)
- // 20 yes -0600
- // 21 yes Z The letter 'Z' if in UTC
- // 22 yes -06 1 or 2 digit time zone hour offset as a signed number
- // 23 yes + the plus or minus in the time zone offset
- // 24 yes 00 1 or 2 digit time zone hour offset as an unsigned number (00-29)
- // 25 yes 00 1 or 2 digit time zone minute offset as a number (00-59)
- final String regex =
- "^(\\d{4})-?(([wW]([012345]\\d)-?([1234567])?)|(([01]\\d)(-([0123]\\d))?)|([01]\\d)([0123]\\d)|([0123]\\d\\d))?(T([012]\\d):?([012345]\\d)(:?([012345]\\d)(.(\\d{1,3}))?)?((Z)|(([+-])(\\d{2})):?(\\d{2})?)?)?$";
- final Pattern pattern = Pattern.compile(regex);
- final Matcher matcher = pattern.matcher(dateString);
- if (!matcher.matches()) {
- throw new ParseException(CommonI18n.dateParsingFailure.text(dateString), 0);
- }
- String year = matcher.group(1);
- String week = matcher.group(4);
- String dayOfWeek = matcher.group(5);
- String month = matcher.group(7);
- if (month == null) month = matcher.group(10);
- String dayOfMonth = matcher.group(9);
- if (dayOfMonth == null) dayOfMonth = matcher.group(11);
- String dayOfYear = matcher.group(12);
- String hourOfDay = matcher.group(14);
- String minutesOfHour = matcher.group(15);
- String seconds = matcher.group(17);
- String milliseconds = matcher.group(19);
- String timeZoneSign = matcher.group(23);
- String timeZoneHour = matcher.group(24);
- String timeZoneMinutes = matcher.group(25);
- if (matcher.group(21) != null) {
- timeZoneHour = "00";
- timeZoneMinutes = "00";
- }
-
- // Create the calendar object and start setting the fields ...
- Calendar calendar = Calendar.getInstance();
- calendar.clear();
-
- // And start setting the fields. Note that Integer.parseInt should never fail, since we're checking for null and the
- // regular expression should only have digits in these strings!
- if (year != null) calendar.set(Calendar.YEAR, Integer.parseInt(year));
- if (month != null) {
- calendar.set(Calendar.MONTH, Integer.parseInt(month) - 1); // month is zero-based!
- if (dayOfMonth != null) calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dayOfMonth));
- } else if (week != null) {
- calendar.set(Calendar.WEEK_OF_YEAR, Integer.parseInt(week));
- if (dayOfWeek != null) calendar.set(Calendar.DAY_OF_WEEK, Integer.parseInt(dayOfWeek));
- } else if (dayOfYear != null) {
- calendar.set(Calendar.DAY_OF_YEAR, Integer.parseInt(dayOfYear));
- }
- if (hourOfDay != null) calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourOfDay));
- if (minutesOfHour != null) calendar.set(Calendar.MINUTE, Integer.parseInt(minutesOfHour));
- if (seconds != null) calendar.set(Calendar.SECOND, Integer.parseInt(seconds));
- if (milliseconds != null) calendar.set(Calendar.MILLISECOND, Integer.parseInt(milliseconds));
- if (timeZoneHour != null) {
- int zoneOffsetInMillis = Integer.parseInt(timeZoneHour) * 60 * 60 * 1000;
- if ("-".equals(timeZoneSign)) zoneOffsetInMillis *= -1;
- if (timeZoneMinutes != null) {
- int minuteOffsetInMillis = Integer.parseInt(timeZoneMinutes) * 60 * 1000;
- if (zoneOffsetInMillis < 0) {
- zoneOffsetInMillis -= minuteOffsetInMillis;
- } else {
- zoneOffsetInMillis += minuteOffsetInMillis;
- }
- }
- calendar.set(Calendar.ZONE_OFFSET, zoneOffsetInMillis);
- }
- return calendar;
- }
-
- /**
- * Parse the date contained in the supplied string. This method simply calls {@link Calendar#getTime()} on the result of
- * {@link #getCalendarFromStandardString(String)}.
- * @param dateString the string containing the date to be parsed
- * @return the parsed date as a {@link Calendar} object.
- * @throws ParseException if there is a problem parsing the string
- * @see #getCalendarFromStandardString(String)
- */
- public static Date getDateFromStandardString( String dateString ) throws ParseException {
- return getCalendarFromStandardString(dateString).getTime();
- }
-
- /**
- * Obtain an ISO 8601:2004 string representation of the date given the supplied milliseconds since the epoch.
- * @param millisecondsSinceEpoch the milliseconds for the date
- * @return the string in the {@link #ISO_8601_2004_FORMAT standard format}
- * @see #getDateAsStandardString(Date)
- * @see #getDateFromStandardString(String)
- * @see #getCalendarFromStandardString(String)
- */
- public static String getDateAsStandardString( final long millisecondsSinceEpoch ) {
- return getDateAsStandardString(new Date(millisecondsSinceEpoch));
- }
-
- /**
- * Obtain an ISO 8601:2004 string representation of the date given the supplied milliseconds since the epoch.
- * @param date the date in calendar form
- * @return the string in the {@link #ISO_8601_2004_FORMAT standard format}
- * @see #getDateAsStandardString(Date)
- * @see #getDateFromStandardString(String)
- * @see #getCalendarFromStandardString(String)
- */
- public static String getDateAsStandardString( final Calendar date ) {
- return getDateAsStandardString(date.getTime());
- }
-
- /**
- * Obtain an ISO 8601:2004 string representation of the supplied date.
- * @param date the date
- * @return the string in the {@link #ISO_8601_2004_FORMAT standard format}
- * @see #getDateAsStandardString(long)
- * @see #getDateFromStandardString(String)
- * @see #getCalendarFromStandardString(String)
- */
- public static String getDateAsStandardString( final java.util.Date date ) {
- return new SimpleDateFormat(ISO_8601_2004_FORMAT).format(date);
- }
-
- public static String getDateAsStringForCurrentLocale( final java.util.Date date ) {
- return getDateAsStringForLocale(date, Locale.getDefault());
- }
-
- public static String getDateAsStringForLocale( final java.util.Date date, Locale locale ) {
- return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG).format(date);
- }
-
- private DateUtil() {
- // Prevent instantiation
- }
-
-}
Modified: trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java
===================================================================
--- trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-common/src/main/java/org/jboss/dna/common/util/StringUtil.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -30,15 +30,11 @@
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Collection;
import java.util.Collections;
import java.util.List;
-import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jboss.dna.common.CommonI18n;
-import org.jboss.dna.common.SystemFailureException;
/**
* Utilities for string processing and manipulation.
@@ -376,252 +372,6 @@
}
/**
- * Create a human-readable form of the supplied object by choosing the representation format based upon the object type.
- * <p>
- * <ul>
- * <li>A null reference results in the "null" string.</li>
- * <li>A string is written wrapped by double quotes.</li>
- * <li>A boolean is written using {@link Boolean#toString()}.</li>
- * <li>A {@link Number number} is written using the standard {@link Number#toString() toString()} method.</li>
- * <li>A {@link java.util.Date date} is written using the the {@link DateUtil#getDateAsStandardString(java.util.Date)} utility
- * method.</li>
- * <li>A {@link java.sql.Date SQL date} is written using the the {@link DateUtil#getDateAsStandardString(java.util.Date)}
- * utility method.</li>
- * <li>A {@link Calendar Calendar instance} is written using the the {@link DateUtil#getDateAsStandardString(Calendar)}
- * utility method.</li>
- * <li>An array of bytes is written with a leading "[ " and trailing " ]" surrounding the bytes written as UTF-8.
- * <li>An array of objects is written with a leading "[ " and trailing " ]", and with all objects sent through
- * {@link #readableString(Object)} and separated by ", ".</li>
- * <li>A collection of objects (e.g, <code>Collection<?></code>) is written with a leading "[ " and trailing " ]", and with
- * all objects sent through {@link #readableString(Object)} and separated by ", ".</li>
- * <li>A map of objects (e.g, <code>Map<?></code>) is written with a leading "{ " and trailing " }", and with all map entries
- * written in the form "key => value" and separated by ", ". All key and value objects are sent through the
- * {@link #readableString(Object)} method.</li>
- * <li>Any other object is written using the object's {@link Object#toString() toString()} method.</li>
- * </ul>
- * </p>
- * <p>
- * This method is capable of generating strings for nested objects. For example, a <code>Map<Date,Object[]></code> would be
- * written in the form:
- *
- * <pre>
- * { 2008-02-03T14:22:49 => [ "description", 3, [ 003459de7389g23aef, true ] ] }
- * </pre>
- *
- * </p>
- *
- * @param obj the object that is to be converted to a string.
- * @return the string representation that is to be human readable
- */
- public static String readableString( Object obj ) {
- if (obj == null) return "null";
- if (obj instanceof Boolean) return ((Boolean)obj).toString();
- if (obj instanceof String) return "\"" + obj.toString() + "\"";
- if (obj instanceof Number) return obj.toString();
- if (obj instanceof Map<?, ?>) return readableString((Map<?, ?>)obj);
- if (obj instanceof Collection<?>) return readableString((Collection<?>)obj);
- if (obj instanceof byte[]) return readableString((byte[])obj);
- if (obj instanceof boolean[]) return readableString((boolean[])obj);
- if (obj instanceof short[]) return readableString((short[])obj);
- if (obj instanceof int[]) return readableString((int[])obj);
- if (obj instanceof long[]) return readableString((long[])obj);
- if (obj instanceof float[]) return readableString((float[])obj);
- if (obj instanceof double[]) return readableString((double[])obj);
- if (obj instanceof Object[]) return readableString((Object[])obj);
- if (obj instanceof Calendar) return DateUtil.getDateAsStandardString((Calendar)obj);
- if (obj instanceof java.util.Date) return DateUtil.getDateAsStandardString((java.util.Date)obj);
- if (obj instanceof java.sql.Date) return DateUtil.getDateAsStandardString((java.sql.Date)obj);
- return obj.toString();
- }
-
- protected static String readableEmptyArray( Class<?> arrayClass ) {
- assert arrayClass != null;
- Class<?> componentType = arrayClass.getComponentType();
- if (componentType.isArray()) return "[" + readableEmptyArray(componentType) + "]";
- return "[]";
- }
-
- protected static String readableString( Object[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (Object value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( int[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (int value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( short[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (short value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( long[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (long value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( boolean[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (boolean value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( float[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (float value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( double[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (double value : array) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( byte[] array ) {
- assert array != null;
- if (array.length == 0) return readableEmptyArray(array.getClass());
- StringBuilder sb = new StringBuilder();
- sb.append("[ ");
- try {
- sb.append(new String(array, "UTF-8"));
- } catch (UnsupportedEncodingException e) {
- throw new SystemFailureException(e);
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( Collection<?> collection ) {
- assert collection != null;
- if (collection.isEmpty()) return "[]";
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("[ ");
- for (Object value : collection) {
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(value));
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- protected static String readableString( Map<?, ?> map ) {
- assert map != null;
- if (map.isEmpty()) return "{}";
- StringBuilder sb = new StringBuilder();
- boolean first = true;
- sb.append("{ ");
- for (Map.Entry<?, ?> entry : map.entrySet()) {
- Object key = entry.getKey();
- Object value = entry.getValue();
- if (first) {
- first = false;
- } else {
- sb.append(", ");
- }
- sb.append(readableString(key));
- sb.append(" => ");
- sb.append(readableString(value));
- }
- sb.append(" }");
- return sb.toString();
- }
-
- /**
* Get the stack trace of the supplied exception.
*
* @param throwable the exception for which the stack trace is to be returned
Added: trunk/dna-common/src/test/java/org/jboss/dna/common/util/Base64Test.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/util/Base64Test.java (rev 0)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/util/Base64Test.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -0,0 +1,81 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.common.util;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import org.junit.Test;
+
+/**
+ * @author Randall Hauch
+ */
+public class Base64Test {
+
+ // =========================================================================
+ // H E L P E R M E T H O D S
+ // =========================================================================
+
+ // =========================================================================
+ // T E S T C A S E S
+ // =========================================================================
+
+ @Test
+ public void testBasicExamples() {
+ // Make up some source objects
+ byte[] originalBytes = {(byte)-2, (byte)-1, (byte)0, (byte)1, (byte)2};
+
+ // Display original array
+ System.out.println("\n\nOriginal array: ");
+ for (int i = 0; i < originalBytes.length; i++)
+ System.out.print(originalBytes[i] + " ");
+ System.out.println();
+
+ // Encode serialized bytes
+ String encBytes = Base64.encodeBytes(originalBytes);
+
+ // Print encoded bytes
+ System.out.println("Bytes, encoded ( " + encBytes.getBytes().length + " bytes):\n" + encBytes);
+
+ // Decode bytes
+ byte[] decBytes = Base64.decode(encBytes);
+
+ // Display decoded bytes
+ System.out.println("Encoded Bytes -> decoded: ");
+ for (int i = 0; i < decBytes.length; i++)
+ System.out.print(decBytes[i] + " ");
+ System.out.println();
+ }
+
+ @Test( expected = NullPointerException.class )
+ public void testEncodeNullByteArray() {
+ Base64.encodeBytes(null);
+ }
+
+ @Test
+ public void testEncodeEmptyByteArray() {
+ String result = Base64.encodeBytes(new byte[] {});
+ assertThat(result, is(notNullValue()));
+ assertThat(result.length(), is(0));
+ }
+
+}
Property changes on: trunk/dna-common/src/test/java/org/jboss/dna/common/util/Base64Test.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Deleted: trunk/dna-common/src/test/java/org/jboss/dna/common/util/DateUtilTest.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/util/DateUtilTest.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/util/DateUtilTest.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -1,208 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-package org.jboss.dna.common.util;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.containsString;
-import java.util.Calendar;
-import java.util.Date;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author Randall Hauch
- */
-public class DateUtilTest {
-
- private Calendar calendar;
- private Date validDate;
-
- @Before
- public void beforeEach() {
- this.calendar = Calendar.getInstance();
- this.calendar.set(2008, 1, 3, 14, 22, 49);
- this.validDate = this.calendar.getTime();
- }
-
- @Test
- public void shouldConvertDateToStringUsingStandardFormat() {
- assertThat(DateUtil.getDateAsStandardString(this.validDate), containsString("2008-02-03T14:22:49"));
- }
-
- @Test
- public void shouldConvertDateToStringAndBack() throws Exception {
- String str = DateUtil.getDateAsStandardString(this.validDate);
- Date output = DateUtil.getDateFromStandardString(str);
- assertThat(output, is(this.validDate));
- String outputStr = DateUtil.getDateAsStandardString(output);
- assertThat(outputStr, is(str));
- }
-
- // @Test
- // public void shouldConvertStringToCalendarAndBack() throws Exception {
- // String input = "2008-02";
- // Calendar cal = DateUtil.getCalendarFromStandardString(input);
- // String output = DateUtil.getDateAsStandardString(cal);
- // assertThat(output, is(input));
- // }
-
- @Test
- public void shouldConvertStringToDateWithDelimitersAndNoTimeZone() throws Exception {
- Calendar cal = DateUtil.getCalendarFromStandardString("2008-02-03T14:22:49.111");
- assertThat(cal.isSet(Calendar.ZONE_OFFSET), is(false));
- assertThat(cal.isSet(Calendar.WEEK_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_WEEK), is(false));
- assertThat(cal.get(Calendar.YEAR), is(2008));
- assertThat(cal.get(Calendar.MONTH), is(2 - 1)); // zero-based month!
- assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
- assertThat(cal.get(Calendar.HOUR_OF_DAY), is(14));
- assertThat(cal.get(Calendar.MINUTE), is(22));
- assertThat(cal.get(Calendar.SECOND), is(49));
- assertThat(cal.get(Calendar.MILLISECOND), is(111));
- }
-
- @Test
- public void shouldConvertStringToDateWithNoDelimitersAndNoTimeZone() throws Exception {
- Calendar cal = DateUtil.getCalendarFromStandardString("20080203T142249.111");
- assertThat(cal.isSet(Calendar.ZONE_OFFSET), is(false));
- assertThat(cal.isSet(Calendar.WEEK_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_WEEK), is(false));
- assertThat(cal.get(Calendar.YEAR), is(2008));
- assertThat(cal.get(Calendar.MONTH), is(2 - 1)); // zero-based month!
- assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
- assertThat(cal.get(Calendar.HOUR_OF_DAY), is(14));
- assertThat(cal.get(Calendar.MINUTE), is(22));
- assertThat(cal.get(Calendar.SECOND), is(49));
- assertThat(cal.get(Calendar.MILLISECOND), is(111));
- }
-
- @Test
- public void shouldConvertStringToDateWithDelimitersAndUtcTimeZone() throws Exception {
- Calendar cal = DateUtil.getCalendarFromStandardString("2008-02-03T14:22:49.111Z");
- assertThat(cal.isSet(Calendar.ZONE_OFFSET), is(true));
- assertThat(cal.isSet(Calendar.WEEK_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_WEEK), is(false));
- assertThat(cal.get(Calendar.YEAR), is(2008));
- assertThat(cal.get(Calendar.MONTH), is(2 - 1)); // zero-based month!
- assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
- assertThat(cal.get(Calendar.HOUR_OF_DAY), is(14));
- assertThat(cal.get(Calendar.MINUTE), is(22));
- assertThat(cal.get(Calendar.SECOND), is(49));
- assertThat(cal.get(Calendar.MILLISECOND), is(111));
- assertThat(cal.get(Calendar.ZONE_OFFSET), is(0)); // in milliseconds
- }
-
- @Test
- public void shouldConvertStringToDateWithDelimitersAndHourTimeZone() throws Exception {
- Calendar cal = DateUtil.getCalendarFromStandardString("2008-02-03T14:22:49.111-06");
- assertThat(cal.isSet(Calendar.ZONE_OFFSET), is(true));
- assertThat(cal.isSet(Calendar.WEEK_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_WEEK), is(false));
- assertThat(cal.get(Calendar.YEAR), is(2008));
- assertThat(cal.get(Calendar.MONTH), is(2 - 1)); // zero-based month!
- assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
- assertThat(cal.get(Calendar.HOUR_OF_DAY), is(14));
- assertThat(cal.get(Calendar.MINUTE), is(22));
- assertThat(cal.get(Calendar.SECOND), is(49));
- assertThat(cal.get(Calendar.MILLISECOND), is(111));
- assertThat(cal.get(Calendar.ZONE_OFFSET), is(-6 * 60 * 60 * 1000)); // in milliseconds
- }
-
- @Test
- public void shouldConvertStringToDateWithDelimitersAndHourAndMinuteTimeZone() throws Exception {
- Calendar cal = DateUtil.getCalendarFromStandardString("2008-02-03T14:22:49.111-0622");
- assertThat(cal.isSet(Calendar.ZONE_OFFSET), is(true));
- assertThat(cal.isSet(Calendar.WEEK_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_WEEK), is(false));
- assertThat(cal.get(Calendar.YEAR), is(2008));
- assertThat(cal.get(Calendar.MONTH), is(2 - 1)); // zero-based month!
- assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
- assertThat(cal.get(Calendar.HOUR_OF_DAY), is(14));
- assertThat(cal.get(Calendar.MINUTE), is(22));
- assertThat(cal.get(Calendar.SECOND), is(49));
- assertThat(cal.get(Calendar.MILLISECOND), is(111));
- assertThat(cal.get(Calendar.ZONE_OFFSET), is((-6 * 60 - 22) * 60 * 1000)); // in milliseconds
- }
-
- @Test
- public void shouldConvertStringToDateWithDelimitersAndPositiveHourAndMinuteTimeZone() throws Exception {
- Calendar cal = DateUtil.getCalendarFromStandardString("2008-02-03T14:22:49.111+0622");
- assertThat(cal.isSet(Calendar.ZONE_OFFSET), is(true));
- assertThat(cal.isSet(Calendar.WEEK_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_YEAR), is(false));
- assertThat(cal.isSet(Calendar.DAY_OF_WEEK), is(false));
- assertThat(cal.get(Calendar.YEAR), is(2008));
- assertThat(cal.get(Calendar.MONTH), is(2 - 1)); // zero-based month!
- assertThat(cal.get(Calendar.DAY_OF_MONTH), is(3));
- assertThat(cal.get(Calendar.HOUR_OF_DAY), is(14));
- assertThat(cal.get(Calendar.MINUTE), is(22));
- assertThat(cal.get(Calendar.SECOND), is(49));
- assertThat(cal.get(Calendar.MILLISECOND), is(111));
- assertThat(cal.get(Calendar.ZONE_OFFSET), is((+6 * 60 + 22) * 60 * 1000)); // in milliseconds
- }
-
- @Test
- public void shouldConvertDateStringsToCalendar() throws Exception {
- assertThat(DateUtil.getCalendarFromStandardString("2008").get(Calendar.YEAR), is(2008));
- assertThat(DateUtil.getCalendarFromStandardString("2008-02").get(Calendar.MONTH), is(2 - 1));
- assertThat(DateUtil.getCalendarFromStandardString("200802").get(Calendar.MONTH), is(2 - 1));
- assertThat(DateUtil.getCalendarFromStandardString("2008-02-16").get(Calendar.DAY_OF_MONTH), is(16));
- assertThat(DateUtil.getCalendarFromStandardString("20080216").get(Calendar.DAY_OF_MONTH), is(16));
- assertThat(DateUtil.getCalendarFromStandardString("2008216").get(Calendar.DAY_OF_YEAR), is(216));
- assertThat(DateUtil.getCalendarFromStandardString("2008-216").get(Calendar.DAY_OF_YEAR), is(216));
- assertThat(DateUtil.getCalendarFromStandardString("2008W216").get(Calendar.WEEK_OF_YEAR), is(21));
- assertThat(DateUtil.getCalendarFromStandardString("2008-W216").get(Calendar.WEEK_OF_YEAR), is(21));
- }
-
- @Test
- public void shouldConvertCalendarToStringAndBackMultipleTimes() throws Exception {
- Calendar cal1 = Calendar.getInstance();
- String cal1Str = DateUtil.getDateAsStandardString(cal1);
- Calendar cal2 = DateUtil.getCalendarFromStandardString(cal1Str);
- // Force the calculation of all fields for both calendars ...
- cal1.add(Calendar.DAY_OF_YEAR, 1);
- cal2.add(Calendar.DAY_OF_YEAR, 1);
- cal1.add(Calendar.DAY_OF_YEAR, -1);
- cal2.add(Calendar.DAY_OF_YEAR, -1);
- assertThat(cal1.getTimeInMillis(), is(cal2.getTimeInMillis()));
- assertThat(cal1.compareTo(cal2), is(0));
- assertThat(cal1, is(cal2));
- String cal2Str = DateUtil.getDateAsStandardString(cal2);
- assertThat(cal1Str, is(cal2Str));
- Calendar cal3 = DateUtil.getCalendarFromStandardString(cal2Str);
- cal3.add(Calendar.DAY_OF_YEAR, 1);
- cal3.add(Calendar.DAY_OF_YEAR, -1);
- assertThat(cal1, is(cal3));
- assertThat(cal3, is(cal3));
- String cal3Str = DateUtil.getDateAsStandardString(cal3);
- assertThat(cal1Str, is(cal3Str));
- assertThat(cal2Str, is(cal3Str));
- }
-
-}
Modified: trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java
===================================================================
--- trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-common/src/test/java/org/jboss/dna/common/util/StringUtilTest.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -34,7 +34,6 @@
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
-import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
@@ -351,65 +350,6 @@
assertThat(trace, containsString(this.getClass().getName()));
}
- @Test
- public void readableStringShouldReturnStringForNull() {
- assertThat(StringUtil.readableString((Object)null), is("null"));
- }
-
- @Test
- public void readableStringShouldReturnStringFormOfBoolean() {
- assertThat(StringUtil.readableString(true), is(Boolean.TRUE.toString()));
- assertThat(StringUtil.readableString(false), is(Boolean.FALSE.toString()));
- assertThat(StringUtil.readableString(Boolean.TRUE), is(Boolean.TRUE.toString()));
- assertThat(StringUtil.readableString(Boolean.FALSE), is(Boolean.FALSE.toString()));
- }
-
- @Test
- public void readableStringShouldReturnStringFormOfNumber() {
- assertThat(StringUtil.readableString(1), is("1"));
- assertThat(StringUtil.readableString(-513), is("-513"));
- assertThat(StringUtil.readableString(-513.3f), is("-513.3"));
- assertThat(StringUtil.readableString(-513.3d), is("-513.3"));
- assertThat(StringUtil.readableString(new Short((short)1)), is("1"));
- assertThat(StringUtil.readableString(new Integer(-513)), is("-513"));
- assertThat(StringUtil.readableString(new Float(-513.3f)), is("-513.3"));
- assertThat(StringUtil.readableString(new Double(-513.3d)), is("-513.3"));
- }
-
- @Test
- public void readableStringShouldWrapObjectArrayWithSquareBraces() {
- assertThat(StringUtil.readableString(new int[] {}), is("[]"));
- assertThat(StringUtil.readableString(new int[] {1}), is("[ 1 ]"));
- assertThat(StringUtil.readableString(new int[] {1, 2, 3, 4}), is("[ 1, 2, 3, 4 ]"));
- assertThat(StringUtil.readableString(new short[] {1, 2, 3, 4}), is("[ 1, 2, 3, 4 ]"));
- assertThat(StringUtil.readableString(new boolean[] {true, false}), is("[ true, false ]"));
- assertThat(StringUtil.readableString(new long[] {1, 2, 3, 4}), is("[ 1, 2, 3, 4 ]"));
- assertThat(StringUtil.readableString(new float[] {51.0f, 52.0f, 53.0f, 54.0f}), is("[ 51.0, 52.0, 53.0, 54.0 ]"));
- assertThat(StringUtil.readableString(new double[] {51.0d, 52.0d, 53.0d, 54.0d}), is("[ 51.0, 52.0, 53.0, 54.0 ]"));
- }
-
- @Test
- public void readableStringShouldHandleEmptyArraysOfArrays() {
- assertThat(StringUtil.readableString(new int[][] {}), is("[[]]"));
- assertThat(StringUtil.readableString(new boolean[][][][][][] {}), is("[[[[[[]]]]]]"));
- assertThat(StringUtil.readableString(new ArrayList<List<List<?>>>()), is("[]"));
- }
-
- @Test
- public void readableStringShouldHandleNestedObjects() {
- assertThat(StringUtil.readableString(new int[][] {new int[] {1, 2}, new int[] {3, 4}}), is("[ [ 1, 2 ], [ 3, 4 ] ]"));
- List<String> list1 = new ArrayList<String>();
- list1.add("a1");
- list1.add("a2");
- List<String> list2 = new ArrayList<String>();
- list2.add("b1");
- list2.add("b2");
- List<List<String>> list3 = new ArrayList<List<String>>();
- list3.add(list1);
- list3.add(list2);
- assertThat(StringUtil.readableString(list3), is("[ [ \"a1\", \"a2\" ], [ \"b1\", \"b2\" ] ]"));
- }
-
@Test( expected = IllegalArgumentException.class )
public void normalizeShouldFailIfTextNull() {
StringUtil.normalize(null);
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/Location.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/Location.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/Location.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -30,7 +30,6 @@
import net.jcip.annotations.Immutable;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.HashCode;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.properties.Path;
import org.jboss.dna.graph.properties.Property;
@@ -465,7 +464,7 @@
if (this.hasIdProperties()) sb.append(" && ");
}
if (this.hasIdProperties()) {
- sb.append(StringUtil.readableString(this.getIdProperties()));
+ sb.append(this.getIdProperties().toString());
if (this.hasPath()) sb.append(" ]");
}
return sb.toString();
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicProperty.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicProperty.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/BasicProperty.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -21,9 +21,9 @@
*/
package org.jboss.dna.graph.properties.basic;
+import java.util.Arrays;
import java.util.Iterator;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.properties.Property;
import org.jboss.dna.graph.properties.ValueComparators;
@@ -120,9 +120,9 @@
sb.append(getName());
sb.append(" = ");
if (isSingle()) {
- sb.append(StringUtil.readableString(getValues().next()));
+ sb.append(getValues().next());
} else {
- sb.append(StringUtil.readableString(getValuesAsArray()));
+ sb.append(Arrays.asList(getValuesAsArray()));
}
return sb.toString();
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/InMemoryBinary.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/InMemoryBinary.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/InMemoryBinary.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -28,6 +28,7 @@
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import net.jcip.annotations.Immutable;
+import org.jboss.dna.common.util.Base64;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.graph.GraphI18n;
@@ -156,11 +157,7 @@
public String toString() {
StringBuilder sb = new StringBuilder(super.toString());
sb.append(" len=").append(getSize()).append("; [");
- int len = (int)Math.min(getSize(), 20l);
- for (int i = 0; i != len; ++i) {
- if (i != 0) sb.append(',');
- sb.append(this.bytes[i]);
- }
+ sb.append(Base64.encodeBytes(this.bytes));
return sb.toString();
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/JodaDateTime.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/JodaDateTime.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/properties/basic/JodaDateTime.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -47,7 +47,6 @@
private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
private final DateTime instance;
- private transient String formattedString;
public JodaDateTime() {
this.instance = new DateTime();
@@ -231,12 +230,7 @@
* {@inheritDoc}
*/
public String getString() {
- if (this.formattedString == null) {
- // This is transient and can be done multiple times by concurrent threads (without locking),
- // since the object is immutable
- this.formattedString = this.instance.toString(org.joda.time.format.ISODateTimeFormat.dateTime());
- }
- return this.formattedString;
+ return this.instance.toString(org.joda.time.format.ISODateTimeFormat.dateTime());
}
/**
@@ -410,7 +404,7 @@
* @see org.jboss.dna.graph.properties.DateTime#minus(long, java.util.concurrent.TimeUnit)
*/
public org.jboss.dna.graph.properties.DateTime minus( long timeAmount,
- TimeUnit unit ) {
+ TimeUnit unit ) {
CheckArg.isNotNull(unit, "unit");
return new JodaDateTime(this.instance.minus(TimeUnit.MILLISECONDS.convert(timeAmount, unit)));
}
@@ -493,7 +487,7 @@
* @see org.jboss.dna.graph.properties.DateTime#plus(long, java.util.concurrent.TimeUnit)
*/
public org.jboss.dna.graph.properties.DateTime plus( long timeAmount,
- TimeUnit unit ) {
+ TimeUnit unit ) {
CheckArg.isNotNull(unit, "unit");
return new JodaDateTime(this.instance.plus(TimeUnit.MILLISECONDS.convert(timeAmount, unit)));
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CreateNodeRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CreateNodeRequest.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/CreateNodeRequest.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -28,7 +28,6 @@
import java.util.LinkedList;
import java.util.List;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.Location;
import org.jboss.dna.graph.NodeConflictBehavior;
@@ -280,7 +279,7 @@
*/
@Override
public String toString() {
- return "create node at " + at() + " with properties " + StringUtil.readableString(properties());
+ return "create node at " + at() + " with properties " + properties();
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/RemovePropertiesRequest.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -27,7 +27,6 @@
import java.util.Iterator;
import java.util.Set;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.Location;
import org.jboss.dna.graph.properties.Name;
@@ -191,7 +190,7 @@
*/
@Override
public String toString() {
- return "remove from " + from() + " properties named " + StringUtil.readableString(propertyNames());
+ return "remove from " + from() + " properties named " + propertyNames();
}
}
Modified: trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java
===================================================================
--- trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/main/java/org/jboss/dna/graph/requests/UpdatePropertiesRequest.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -28,7 +28,6 @@
import java.util.LinkedList;
import java.util.List;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.GraphI18n;
import org.jboss.dna.graph.Location;
import org.jboss.dna.graph.properties.Property;
@@ -188,7 +187,7 @@
*/
@Override
public String toString() {
- return "update properties on " + on() + " to " + StringUtil.readableString(properties());
+ return "update properties on " + on() + " to " + properties();
}
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphImporterTest.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphImporterTest.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/GraphImporterTest.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -34,7 +34,6 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.transaction.xa.XAResource;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.cache.CachePolicy;
import org.jboss.dna.graph.connectors.RepositoryConnection;
import org.jboss.dna.graph.connectors.RepositoryConnectionFactory;
@@ -137,7 +136,7 @@
assertThat("missing property " + propertyName, actual, is(expectedProperty));
}
if (!propertiesByName.isEmpty()) {
- System.out.println("Properties for " + path + "\n" + StringUtil.readableString(propertiesByName));
+ System.out.println("Properties for " + path + "\n" + propertiesByName);
}
assertThat(propertiesByName.isEmpty(), is(true));
}
Modified: trunk/dna-graph/src/test/java/org/jboss/dna/graph/connectors/SimpleRepository.java
===================================================================
--- trunk/dna-graph/src/test/java/org/jboss/dna/graph/connectors/SimpleRepository.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-graph/src/test/java/org/jboss/dna/graph/connectors/SimpleRepository.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -21,6 +21,7 @@
*/
package org.jboss.dna.graph.connectors;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@@ -30,7 +31,6 @@
import java.util.concurrent.ConcurrentMap;
import net.jcip.annotations.ThreadSafe;
import org.jboss.dna.common.util.Logger;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.properties.Name;
@@ -134,7 +134,7 @@
Object... values ) {
Logger logger = context.getLogger(getClass());
if (logger.isTraceEnabled()) {
- logger.trace("Setting property {0} on {1} to {2}", propertyName, path, StringUtil.readableString(values));
+ logger.trace("Setting property {0} on {1} to {2}", propertyName, path, Arrays.asList(values));
}
PathFactory pathFactory = context.getValueFactories().getPathFactory();
PropertyFactory propertyFactory = context.getPropertyFactory();
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/rules/RuleService.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/rules/RuleService.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/rules/RuleService.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -54,7 +54,6 @@
import org.jboss.dna.common.component.StandardClassLoaderFactory;
import org.jboss.dna.common.util.CheckArg;
import org.jboss.dna.common.util.Logger;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.repository.RepositoryI18n;
import org.jboss.dna.repository.services.AbstractServiceAdministrator;
import org.jboss.dna.repository.services.AdministeredService;
@@ -76,7 +75,8 @@
@ThreadSafe
public class RuleService implements AdministeredService {
- protected static final ClassLoaderFactory DEFAULT_CLASSLOADER_FACTORY = new StandardClassLoaderFactory(RuleService.class.getClassLoader());
+ protected static final ClassLoaderFactory DEFAULT_CLASSLOADER_FACTORY = new StandardClassLoaderFactory(
+ RuleService.class.getClassLoader());
/**
* The administrative component for this service.
@@ -110,7 +110,8 @@
/**
* {@inheritDoc}
*/
- public boolean awaitTermination( long timeout, TimeUnit unit ) throws InterruptedException {
+ public boolean awaitTermination( long timeout,
+ TimeUnit unit ) throws InterruptedException {
return doAwaitTermination(timeout, unit);
}
@@ -126,7 +127,8 @@
/**
* Create a new rule service, configured with no rule sets. Upon construction, the system is
- * {@link ServiceAdministrator#isPaused() paused} and must be configured and then {@link ServiceAdministrator#start() started}.
+ * {@link ServiceAdministrator#isPaused() paused} and must be configured and then {@link ServiceAdministrator#start() started}
+ * .
*/
public RuleService() {
this.logger = Logger.getLogger(this.getClass());
@@ -189,7 +191,7 @@
* @return true if the rule set was added, or false if the rule set was not added (because it wasn't necessary)
* @throws IllegalArgumentException if <code>ruleSet</code> is null
* @throws InvalidRuleSetException if the supplied rule set is invalid, incomplete, incorrectly defined, or uses a JSR-94
- * service provider that cannot be found
+ * service provider that cannot be found
* @see #updateRuleSet(RuleSet)
* @see #removeRuleSet(String)
*/
@@ -211,7 +213,10 @@
// Now register a new execution set ...
RuleAdministrator ruleAdmin = ruleServiceProvider.getRuleAdministrator();
if (ruleAdmin == null) {
- throw new InvalidRuleSetException(RepositoryI18n.unableToObtainJsr94RuleAdministrator.text(providerUri, ruleSet.getComponentClassname(), ruleSetName));
+ throw new InvalidRuleSetException(
+ RepositoryI18n.unableToObtainJsr94RuleAdministrator.text(providerUri,
+ ruleSet.getComponentClassname(),
+ ruleSetName));
}
// Is there is an existing rule set and, if so, whether it has changed ...
@@ -264,9 +269,15 @@
} catch (InvalidRuleSetException e) {
throw e;
} catch (ConfigurationException t) {
- throw new InvalidRuleSetException(RepositoryI18n.unableToObtainJsr94RuleAdministrator.text(providerUri, ruleSet.getComponentClassname(), ruleSetName));
+ throw new InvalidRuleSetException(
+ RepositoryI18n.unableToObtainJsr94RuleAdministrator.text(providerUri,
+ ruleSet.getComponentClassname(),
+ ruleSetName));
} catch (RemoteException t) {
- throw new InvalidRuleSetException(RepositoryI18n.errorUsingJsr94RuleAdministrator.text(providerUri, ruleSet.getComponentClassname(), ruleSetName));
+ throw new InvalidRuleSetException(
+ RepositoryI18n.errorUsingJsr94RuleAdministrator.text(providerUri,
+ ruleSet.getComponentClassname(),
+ ruleSetName));
} catch (IOException t) {
throw new InvalidRuleSetException(RepositoryI18n.errorReadingRulesAndProperties.text(ruleSetName));
} catch (RuleExecutionSetDeregistrationException t) {
@@ -285,7 +296,7 @@
* @param ruleSet the rule set to be updated
* @return true if the rule set was updated, or false if the rule set was not updated (because it wasn't necessary)
* @throws InvalidRuleSetException if the supplied rule set is invalid, incomplete, incorrectly defined, or uses a JSR-94
- * service provider that cannot be found
+ * service provider that cannot be found
* @see #addRuleSet(RuleSet)
* @see #removeRuleSet(String)
*/
@@ -345,19 +356,21 @@
/**
* Execute the set of rules defined by the supplied rule set name. This method is safe to be concurrently called by multiple
- * threads, and is properly synchronized with the methods to {@link #addRuleSet(RuleSet) add},
- * {@link #updateRuleSet(RuleSet) update}, and {@link #removeRuleSet(String) remove} rule sets.
+ * threads, and is properly synchronized with the methods to {@link #addRuleSet(RuleSet) add}, {@link #updateRuleSet(RuleSet)
+ * update}, and {@link #removeRuleSet(String) remove} rule sets.
*
* @param ruleSetName the {@link RuleSet#getName() name} of the {@link RuleSet} that should be used
* @param globals the global variables
* @param facts the facts
* @return the results of executing the rule set
* @throws IllegalArgumentException if the rule set name is null, empty or blank, or if there is no rule set with the given
- * name
- * @throws SystemFailureException if there is no JSR-94 rule service provider with the
- * {@link RuleSet#getProviderUri() RuleSet's provider URI}.
+ * name
+ * @throws SystemFailureException if there is no JSR-94 rule service provider with the {@link RuleSet#getProviderUri()
+ * RuleSet's provider URI}.
*/
- public List<?> executeRules( String ruleSetName, Map<String, Object> globals, Object... facts ) {
+ public List<?> executeRules( String ruleSetName,
+ Map<String, Object> globals,
+ Object... facts ) {
CheckArg.isNotEmpty(ruleSetName, "rule set name");
List<?> result = null;
List<?> factList = Arrays.asList(facts);
@@ -386,10 +399,11 @@
}
if (this.logger.isTraceEnabled()) {
String msg = "Executed rule set '{1}' with globals {2} and facts {3} resulting in {4}";
- this.logger.trace(msg, ruleSetName, StringUtil.readableString(globals), StringUtil.readableString(facts), StringUtil.readableString(result));
+ this.logger.trace(msg, ruleSetName, globals, Arrays.asList(facts), result);
}
} catch (Throwable t) {
- throw new SystemFailureException(RepositoryI18n.errorExecutingRuleSetWithGlobalsAndFacts.text(ruleSetName, StringUtil.readableString(globals), StringUtil.readableString(facts)), t);
+ String msg = RepositoryI18n.errorExecutingRuleSetWithGlobalsAndFacts.text(ruleSetName, globals, Arrays.asList(facts));
+ throw new SystemFailureException(msg, t);
} finally {
this.lock.readLock().unlock();
}
@@ -412,7 +426,8 @@
this.shutdownLatch.countDown();
}
- protected boolean doAwaitTermination( long timeout, TimeUnit unit ) throws InterruptedException {
+ protected boolean doAwaitTermination( long timeout,
+ TimeUnit unit ) throws InterruptedException {
return this.shutdownLatch.await(timeout, unit);
}
@@ -446,11 +461,16 @@
} catch (ConfigurationException ce) {
throw ce;
} catch (Throwable t) {
- throw new InvalidRuleSetException(RepositoryI18n.unableToObtainJsr94ServiceProvider.text(providerUri, ruleSet.getComponentClassname()), t);
+ throw new InvalidRuleSetException(
+ RepositoryI18n.unableToObtainJsr94ServiceProvider.text(providerUri,
+ ruleSet.getComponentClassname()),
+ t);
}
}
if (ruleServiceProvider == null) {
- throw new InvalidRuleSetException(RepositoryI18n.unableToObtainJsr94ServiceProvider.text(providerUri, ruleSet.getComponentClassname()));
+ throw new InvalidRuleSetException(
+ RepositoryI18n.unableToObtainJsr94ServiceProvider.text(providerUri,
+ ruleSet.getComponentClassname()));
}
return ruleServiceProvider;
}
@@ -465,7 +485,8 @@
* @throws RuleExecutionSetDeregistrationException
* @throws RemoteException
*/
- private RuleServiceProvider deregister( RuleSet ruleSet ) throws ConfigurationException, RuleExecutionSetDeregistrationException, RemoteException {
+ private RuleServiceProvider deregister( RuleSet ruleSet )
+ throws ConfigurationException, RuleExecutionSetDeregistrationException, RemoteException {
assert ruleSet != null;
// Look up the provider ...
String providerUri = ruleSet.getProviderUri();
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerOutputMap.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerOutputMap.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/sequencers/SequencerOutputMap.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -31,7 +31,6 @@
import net.jcip.annotations.Immutable;
import net.jcip.annotations.NotThreadSafe;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.JcrLexicon;
import org.jboss.dna.graph.properties.Name;
import org.jboss.dna.graph.properties.Path;
@@ -186,7 +185,7 @@
*/
@Override
public String toString() {
- return StringUtil.readableString(this.data);
+ return this.data.toString();
}
/**
@@ -262,7 +261,7 @@
*/
@Override
public String toString() {
- return "[" + this.name + "=" + StringUtil.readableString(value) + "]";
+ return "[" + this.name + "=" + value + "]";
}
}
Modified: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/ConsoleInput.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -26,6 +26,7 @@
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -260,8 +261,7 @@
for (Map.Entry<String, Object[]> property : properties.entrySet()) {
String name = StringUtil.justifyLeft(property.getKey(), maxLength, ' ');
Object[] values = property.getValue();
- String valueStr = StringUtil.readableString(values);
- if (values.length == 1) valueStr = StringUtil.readableString(values[0]);
+ String valueStr = values.length == 1 ? values[0].toString() : Arrays.asList(values).toString();
System.out.println(" " + name + " = " + valueStr);
}
}
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/contribution/Contribution.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -28,7 +28,6 @@
import java.util.List;
import java.util.NoSuchElementException;
import net.jcip.annotations.Immutable;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.Location;
import org.jboss.dna.graph.properties.DateTime;
import org.jboss.dna.graph.properties.Name;
@@ -383,10 +382,7 @@
while (propIter.hasNext()) {
if (!first) sb.append(", ");
else first = false;
- Property property = propIter.next();
- sb.append(property.getName());
- sb.append('=');
- sb.append(StringUtil.readableString(property.getValuesAsArray()));
+ sb.append(propIter.next());
}
sb.append(" }");
}
Modified: trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/merge/MergePlan.java
===================================================================
--- trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/merge/MergePlan.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/extensions/dna-connector-federation/src/main/java/org/jboss/dna/connector/federation/merge/MergePlan.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -36,7 +36,6 @@
import net.jcip.annotations.ThreadSafe;
import org.jboss.dna.common.CommonI18n;
import org.jboss.dna.common.util.CheckArg;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.connector.federation.contribution.Contribution;
import org.jboss.dna.connector.federation.contribution.EmptyContribution;
import org.jboss.dna.graph.properties.DateTime;
@@ -361,7 +360,7 @@
}
sb.append(contribution);
}
- sb.append(StringUtil.readableString(getAnnotations()));
+ sb.append(getAnnotations());
return sb.toString();
}
Modified: trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheConnection.java
===================================================================
--- trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheConnection.java 2008-11-04 18:00:14 UTC (rev 615)
+++ trunk/extensions/dna-connector-jbosscache/src/main/java/org/jboss/dna/connector/jbosscache/JBossCacheConnection.java 2008-11-05 18:14:32 UTC (rev 616)
@@ -22,6 +22,7 @@
package org.jboss.dna.connector.jbosscache;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@@ -34,7 +35,6 @@
import org.jboss.cache.Cache;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
-import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.graph.DnaLexicon;
import org.jboss.dna.graph.ExecutionContext;
import org.jboss.dna.graph.Location;
@@ -482,9 +482,7 @@
// Record the list of children as a property on the parent ...
// (Do this last, as it doesn't need to be done if there's an exception in the above logic)
- context.getLogger(getClass()).trace("Updating child list of {0} to: {1}",
- parent.getFqn(),
- StringUtil.readableString(childNames));
+ context.getLogger(getClass()).trace("Updating child list of {0} to: {1}", parent.getFqn(), Arrays.asList(childNames));
parent.put(JBossCacheLexicon.CHILD_PATH_SEGMENT_LIST, childNames); // replaces any existing value
if (addChildWithName) {
17 years, 2 months
DNA SVN: r615 - trunk/docs/presentations.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-04 13:00:14 -0500 (Tue, 04 Nov 2008)
New Revision: 615
Added:
trunk/docs/presentations/JBoss DNA 2008-10.pdf
Log:
Updated JBoss DNA presentation zip file
Added: trunk/docs/presentations/JBoss DNA 2008-10.pdf
===================================================================
(Binary files differ)
Property changes on: trunk/docs/presentations/JBoss DNA 2008-10.pdf
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
17 years, 2 months
DNA SVN: r614 - trunk/docs/presentations.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-04 12:53:38 -0500 (Tue, 04 Nov 2008)
New Revision: 614
Modified:
trunk/docs/presentations/JBoss DNA 2008-10.keynote.zip
Log:
Updated JBoss DNA presentation zip file
Modified: trunk/docs/presentations/JBoss DNA 2008-10.keynote.zip
===================================================================
(Binary files differ)
17 years, 2 months
DNA SVN: r613 - trunk/docs/presentations.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-04 12:47:44 -0500 (Tue, 04 Nov 2008)
New Revision: 613
Modified:
trunk/docs/presentations/JBoss DNA 2008-10.keynote.zip
Log:
Updated JBoss DNA presentation zip file
Modified: trunk/docs/presentations/JBoss DNA 2008-10.keynote.zip
===================================================================
(Binary files differ)
17 years, 2 months
DNA SVN: r612 - trunk/docs/presentations.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-11-03 15:51:43 -0500 (Mon, 03 Nov 2008)
New Revision: 612
Modified:
trunk/docs/presentations/JBoss DNA 2008-10.keynote.zip
Log:
Updated JBoss DNA presentation zip file
Modified: trunk/docs/presentations/JBoss DNA 2008-10.keynote.zip
===================================================================
(Binary files differ)
17 years, 2 months