DNA SVN: r512 - in trunk/dna-jcr/src: test/java/org/jboss/dna/jcr and 1 other directory.
by dna-commits@lists.jboss.org
Author: jverhaeg(a)redhat.com
Date: 2008-09-09 14:56:21 -0400 (Tue, 09 Sep 2008)
New Revision: 512
Added:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNodeIterator.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeIteratorTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java
Modified:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java
Log:
DNA-178: Extracted node and property iterators out to top-level classes so that we can document implementation.
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java 2008-09-09 16:06:09 UTC (rev 511)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java 2008-09-09 18:56:21 UTC (rev 512)
@@ -24,9 +24,7 @@
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
-import java.util.Iterator;
import java.util.List;
-import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Item;
@@ -250,63 +248,7 @@
* @see javax.jcr.Node#getNodes()
*/
public final NodeIterator getNodes() {
- return new NodeIterator() {
-
- private final Iterator<Name> childIterator = (children == null ? null : children.iterator());
- private final Iterator<Integer> childNameCountIterator = (childNameCounts == null ? null : childNameCounts.iterator());
- private Name child;
- private int childNameCount;
- private int childNdx = 1;
- private int ndx;
- private Node node;
-
- public long getPosition() {
- return ndx;
- }
-
- public long getSize() {
- return -1;
- }
-
- public boolean hasNext() {
- return ((childIterator != null && childIterator.hasNext()) || (child != null && childNdx <= childNameCount));
- }
-
- public Object next() {
- return nextNode();
- }
-
- public Node nextNode() {
- if (childIterator == null) {
- throw new NoSuchElementException();
- }
- if (child == null || childNdx > childNameCount) {
- child = childIterator.next();
- childNameCount = childNameCountIterator.next();
- childNdx = 1;
- }
- try {
- node = getNode(child.getString() + '[' + childNdx + ']');
- childNdx++;
- ndx++;
- return node;
- } catch (RepositoryException error) {
- // TODO: Change to DnaException once DNA-180 is addressed
- throw new RuntimeException(error);
- }
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- public void skip( long count ) {
- ArgCheck.isNonNegative(count, "count");
- while (--count >= 0) {
- nextNode();
- }
- }
- };
+ return new JcrNodeIterator(this, children, childNameCounts);
}
/**
@@ -374,45 +316,7 @@
* @see javax.jcr.Node#getProperties()
*/
public final PropertyIterator getProperties() {
- assert properties != null;
- return new PropertyIterator() {
-
- private final Iterator<Property> iterator = properties.iterator();
- private int ndx;
-
- public long getPosition() {
- return ndx;
- }
-
- public long getSize() {
- return -1;
- }
-
- public boolean hasNext() {
- return iterator.hasNext();
- }
-
- public Object next() {
- return nextProperty();
- }
-
- public Property nextProperty() {
- Property property = iterator.next();
- ndx++;
- return property;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- public void skip( long count ) {
- ArgCheck.isNonNegative(count, "count");
- while (--count >= 0) {
- nextProperty();
- }
- }
- };
+ return new JcrPropertyIterator(properties);
}
/**
Added: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNodeIterator.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNodeIterator.java (rev 0)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNodeIterator.java 2008-09-09 18:56:21 UTC (rev 512)
@@ -0,0 +1,140 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.NoSuchElementException;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.RepositoryException;
+import org.jboss.dna.common.util.ArgCheck;
+import org.jboss.dna.spi.graph.Name;
+
+/**
+ * @author jverhaeg
+ */
+final class JcrNodeIterator implements NodeIterator {
+
+ private final Node parent;
+ private final Iterator<Name> childIterator;
+ private final Iterator<Integer> childNameCountIterator;
+ private transient Name child;
+ private transient int childNameCount;
+ private transient int childNdx = 1;
+ private transient int ndx;
+ private transient Node node;
+
+ JcrNodeIterator( Node parent,
+ List<Name> children,
+ List<Integer> childNameCounts ) {
+ assert parent != null;
+ this.parent = parent;
+ childIterator = (children == null ? null : children.iterator());
+ childNameCountIterator = (childNameCounts == null ? null : childNameCounts.iterator());
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.RangeIterator#getPosition()
+ */
+ public long getPosition() {
+ return ndx;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return -1L
+ * @see javax.jcr.RangeIterator#getSize()
+ */
+ public long getSize() {
+ return -1L;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.util.Iterator#hasNext()
+ */
+ public boolean hasNext() {
+ return ((childIterator != null && childIterator.hasNext()) || (child != null && childNdx <= childNameCount));
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.util.Iterator#next()
+ */
+ public Object next() {
+ return nextNode();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.NodeIterator#nextNode()
+ */
+ public Node nextNode() {
+ if (childIterator == null) {
+ throw new NoSuchElementException();
+ }
+ if (child == null || childNdx > childNameCount) {
+ child = childIterator.next();
+ childNameCount = childNameCountIterator.next();
+ childNdx = 1;
+ }
+ try {
+ node = parent.getNode(child.getString() + '[' + childNdx + ']');
+ childNdx++;
+ ndx++;
+ return node;
+ } catch (RepositoryException error) {
+ // TODO: Change to DnaException once DNA-180 is addressed
+ throw new RuntimeException(error);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws UnsupportedOperationException always
+ * @see java.util.Iterator#remove()
+ */
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalArgumentException if <code>count</code> is negative.
+ * @see javax.jcr.RangeIterator#skip(long)
+ */
+ public void skip( long count ) {
+ ArgCheck.isNonNegative(count, "count");
+ while (--count >= 0) {
+ nextNode();
+ }
+ }
+}
Property changes on: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNodeIterator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java (rev 0)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java 2008-09-09 18:56:21 UTC (rev 512)
@@ -0,0 +1,113 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import java.util.Iterator;
+import java.util.Set;
+import javax.jcr.Property;
+import javax.jcr.PropertyIterator;
+import org.jboss.dna.common.util.ArgCheck;
+
+/**
+ * @author jverhaeg
+ */
+final class JcrPropertyIterator implements PropertyIterator {
+
+ private final Iterator<Property> iterator;
+ private int ndx;
+
+ JcrPropertyIterator( Set<Property> properties ) {
+ assert properties != null;
+ iterator = properties.iterator();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.RangeIterator#getPosition()
+ */
+ public long getPosition() {
+ return ndx;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return -1L
+ * @see javax.jcr.RangeIterator#getSize()
+ */
+ public long getSize() {
+ return -1L;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.util.Iterator#hasNext()
+ */
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see java.util.Iterator#next()
+ */
+ public Object next() {
+ return nextProperty();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.PropertyIterator#nextProperty()
+ */
+ public Property nextProperty() {
+ Property property = iterator.next();
+ ndx++;
+ return property;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws UnsupportedOperationException always
+ * @see java.util.Iterator#remove()
+ */
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws IllegalArgumentException if <code>count</code> is negative.
+ * @see javax.jcr.RangeIterator#skip(long)
+ */
+ public void skip( long count ) {
+ ArgCheck.isNonNegative(count, "count");
+ while (--count >= 0) {
+ nextProperty();
+ }
+ }
+}
Property changes on: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java 2008-09-09 16:06:09 UTC (rev 511)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java 2008-09-09 18:56:21 UTC (rev 512)
@@ -36,10 +36,8 @@
import javax.jcr.ItemNotFoundException;
import javax.jcr.ItemVisitor;
import javax.jcr.Node;
-import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.UnsupportedRepositoryOperationException;
@@ -59,6 +57,53 @@
*/
public class AbstractJcrNodeTest {
+ static MockAbstractJcrNode createChild( Session session,
+ String name,
+ int index,
+ List<Segment> children,
+ Node parent ) throws Exception {
+ MockAbstractJcrNode child = new MockAbstractJcrNode(session, name, parent);
+ Segment seg = Mockito.mock(Segment.class);
+ stub(seg.getName()).toReturn(new BasicName(null, name));
+ children.add(seg);
+ stub(session.getItem(parent.getPath() + "/{}" + name + '[' + index + ']')).toReturn(child);
+ return child;
+ }
+
+ static class MockAbstractJcrNode extends AbstractJcrNode {
+
+ String name;
+ Node parent;
+
+ MockAbstractJcrNode( Session session,
+ String name,
+ Node parent ) {
+ super(session);
+ this.name = name;
+ this.parent = parent;
+ }
+
+ public int getDepth() {
+ return 0;
+ }
+
+ public int getIndex() {
+ return 0;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Node getParent() {
+ return parent;
+ }
+
+ public String getPath() throws RepositoryException {
+ return (parent == null ? '/' + getName() : parent.getPath() + '/' + getName());
+ }
+ }
+
private AbstractJcrNode node;
@Mock
private Session session;
@@ -173,7 +218,7 @@
@Test
public void shouldProvideNode() throws Exception {
- Node child = createChild("child", 1, children, node);
+ Node child = createChild(session, "child", 1, children, node);
node.setChildren(children);
stub(session.getItem("/node/child")).toReturn(child);
assertThat(node.getNode("child"), is(child));
@@ -198,45 +243,9 @@
@Test
public void shouldProvideNodeIterator() throws Exception {
- Node child1 = createChild("child1", 1, children, node);
- Node child2_1 = createChild("child2", 1, children, node);
- Node child2_2 = createChild("child2", 2, children, node);
- createChild("child3", 1, children, node);
- createChild("child4", 1, children, node);
- Node child5 = createChild("child5", 1, children, node);
- node.setChildren(children);
- NodeIterator iter = node.getNodes();
- assertThat(iter, notNullValue());
- assertThat(iter.getSize(), is(-1L));
- assertThat(iter.getPosition(), is(0L));
- assertThat(iter.hasNext(), is(true));
- assertThat((Node)iter.next(), is(child1));
- assertThat(iter.getPosition(), is(1L));
- assertThat(iter.hasNext(), is(true));
- assertThat(iter.nextNode(), is(child2_1));
- assertThat(iter.getPosition(), is(2L));
- assertThat(iter.hasNext(), is(true));
- assertThat(iter.nextNode(), is(child2_2));
- assertThat(iter.getPosition(), is(3L));
- assertThat(iter.hasNext(), is(true));
- iter.skip(2);
- assertThat(iter.getPosition(), is(5L));
- assertThat(iter.hasNext(), is(true));
- assertThat(iter.nextNode(), is(child5));
- assertThat(iter.getPosition(), is(6L));
- assertThat(iter.hasNext(), is(false));
+ assertThat(node.getNodes(), notNullValue());
}
- @Test( expected = UnsupportedOperationException.class )
- public void shouldNotAllowNodeIteratorRemove() throws Exception {
- node.getNodes().remove();
- }
-
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNodeIteratorNegativeSkip() throws Exception {
- node.getNodes().skip(-1);
- }
-
@Test
public void shoudProvidePrimaryItem() throws Exception {
Property property = Mockito.mock(Property.class);
@@ -254,51 +263,19 @@
}
@Test
- public void shouldProvidePropertyIterator() throws Exception {
- properties.add(Mockito.mock(Property.class));
- properties.add(Mockito.mock(Property.class));
- properties.add(Mockito.mock(Property.class));
- properties.add(Mockito.mock(Property.class));
- PropertyIterator iter = node.getProperties();
- assertThat(iter, notNullValue());
- assertThat(iter.getSize(), is(-1L));
- assertThat(iter.getPosition(), is(0L));
- assertThat(iter.hasNext(), is(true));
- assertThat(iter.next(), notNullValue());
- assertThat(iter.getPosition(), is(1L));
- assertThat(iter.hasNext(), is(true));
- iter.skip(2);
- assertThat(iter.getPosition(), is(3L));
- assertThat(iter.hasNext(), is(true));
- assertThat(iter.nextProperty(), notNullValue());
- assertThat(iter.getPosition(), is(4L));
- assertThat(iter.hasNext(), is(false));
- }
-
- @Test( expected = UnsupportedOperationException.class )
- public void shouldNotAllowPropertyIteratorRemove() throws Exception {
- node.getProperties().remove();
- }
-
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowPropertyIteratorNegativeSkip() throws Exception {
- node.getProperties().skip(-1);
- }
-
- @Test
public void shouldProvideProperty() throws Exception {
Property prop1 = Mockito.mock(Property.class);
stub(prop1.getName()).toReturn("prop1");
properties.add(prop1);
assertThat(node.getProperty("prop1"), is(prop1));
- MockAbstractJcrNode child = createChild("child", 1, children, node);
+ MockAbstractJcrNode child = createChild(session, "child", 1, children, node);
Set<Property> properties = new HashSet<Property>();
child.setProperties(properties);
Property prop2 = Mockito.mock(Property.class);
stub(prop2.getName()).toReturn("prop2");
stub(session.getItem("/node/child/prop2")).toReturn(prop2);
properties.add(prop2);
- MockAbstractJcrNode prop3Node = createChild("prop3", 1, children, child);
+ MockAbstractJcrNode prop3Node = createChild(session, "prop3", 1, children, child);
node.setChildren(children);
assertThat(node.getProperty("child/prop2"), is(prop2));
// Ensure we return a property even when a child exists with the same name
@@ -326,10 +303,10 @@
@Test( expected = PathNotFoundException.class )
public void shouldNotProvideDescendentPropertyIfNotAvailable() throws Exception {
- MockAbstractJcrNode child = createChild("child", 1, children, node);
+ MockAbstractJcrNode child = createChild(session, "child", 1, children, node);
Set<Property> properties = new HashSet<Property>();
child.setProperties(properties);
- MockAbstractJcrNode propNode = createChild("prop", 1, children, child);
+ MockAbstractJcrNode propNode = createChild(session, "prop", 1, children, child);
node.setChildren(children);
stub(session.getItem("/node/child/prop")).toReturn(propNode);
node.getProperty("child/prop");
@@ -398,18 +375,14 @@
stub(prop.getName()).toReturn("prop");
properties.add(prop);
assertThat(node.hasNode("prop"), is(false));
- Node child = createChild("child", 1, children, node);
- Node child2 = createChild("child2", 1, children, child);
+ Node child = createChild(session, "child", 1, children, node);
+ Node child2 = createChild(session, "child2", 1, children, child);
node.setChildren(children);
assertThat(node.hasNode("{}child"), is(true));
stub(session.getItem("/node/child/{}child2")).toReturn(child2);
assertThat(node.hasNode("child/{}child2"), is(true));
}
- @Test
- public void shouldNotIndicateHasNodeIfPathIsChildProperty() throws Exception {
- }
-
@Test( expected = IllegalArgumentException.class )
public void shouldNotAllowHasNodeWithNoPath() throws Exception {
node.hasNode(null);
@@ -423,7 +396,7 @@
@Test
public void shouldProvideHasNodes() throws Exception {
assertThat(node.hasNodes(), is(false));
- createChild("child", 1, children, node);
+ createChild(session, "child", 1, children, node);
node.setChildren(children);
assertThat(node.hasNodes(), is(true));
}
@@ -438,7 +411,7 @@
@Test
public void shouldIndicateHasProperty() throws Exception {
assertThat(node.hasProperty("prop"), is(false));
- MockAbstractJcrNode child = createChild("child", 1, children, node);
+ MockAbstractJcrNode child = createChild(session, "child", 1, children, node);
node.setChildren(children);
assertThat(node.hasProperty("child"), is(false));
Property prop = Mockito.mock(Property.class);
@@ -629,50 +602,4 @@
public void shouldNotAllowUpdate() throws Exception {
node.update(null);
}
-
- private MockAbstractJcrNode createChild( String name,
- int index,
- List<Segment> children,
- Node parent ) throws Exception {
- MockAbstractJcrNode child = new MockAbstractJcrNode(session, name, parent);
- Segment seg = Mockito.mock(Segment.class);
- stub(seg.getName()).toReturn(new BasicName(null, name));
- children.add(seg);
- stub(session.getItem(parent.getPath() + "/{}" + name + '[' + index + ']')).toReturn(child);
- return child;
- }
-
- private class MockAbstractJcrNode extends AbstractJcrNode {
-
- String name;
- Node parent;
-
- MockAbstractJcrNode( Session session,
- String name,
- Node parent ) {
- super(session);
- this.name = name;
- this.parent = parent;
- }
-
- public int getDepth() {
- return 0;
- }
-
- public int getIndex() {
- return 0;
- }
-
- public String getName() {
- return name;
- }
-
- public Node getParent() {
- return parent;
- }
-
- public String getPath() throws RepositoryException {
- return (parent == null ? '/' + getName() : parent.getPath() + '/' + getName());
- }
- }
}
Added: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeIteratorTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeIteratorTest.java (rev 0)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeIteratorTest.java 2008-09-09 18:56:21 UTC (rev 512)
@@ -0,0 +1,96 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import java.util.ArrayList;
+import java.util.List;
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Session;
+import org.jboss.dna.jcr.AbstractJcrNodeTest.MockAbstractJcrNode;
+import org.jboss.dna.spi.graph.Path.Segment;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoAnnotations.Mock;
+
+/**
+ * @author jverhaeg
+ */
+public class JcrNodeIteratorTest {
+
+ private AbstractJcrNode node;
+ @Mock
+ private Session session;
+ private List<Segment> children;
+
+ @Before
+ public void before() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ children = new ArrayList<Segment>();
+ node = new MockAbstractJcrNode(session, "node", null);
+ }
+
+ @Test
+ public void shouldProvideNodeIterator() throws Exception {
+ Node child1 = AbstractJcrNodeTest.createChild(session, "child1", 1, children, node);
+ Node child2_1 = AbstractJcrNodeTest.createChild(session, "child2", 1, children, node);
+ Node child2_2 = AbstractJcrNodeTest.createChild(session, "child2", 2, children, node);
+ AbstractJcrNodeTest.createChild(session, "child3", 1, children, node);
+ AbstractJcrNodeTest.createChild(session, "child4", 1, children, node);
+ Node child5 = AbstractJcrNodeTest.createChild(session, "child5", 1, children, node);
+ node.setChildren(children);
+ NodeIterator iter = node.getNodes();
+ assertThat(iter, notNullValue());
+ assertThat(iter.getSize(), is(-1L));
+ assertThat(iter.getPosition(), is(0L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat((Node)iter.next(), is(child1));
+ assertThat(iter.getPosition(), is(1L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextNode(), is(child2_1));
+ assertThat(iter.getPosition(), is(2L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextNode(), is(child2_2));
+ assertThat(iter.getPosition(), is(3L));
+ assertThat(iter.hasNext(), is(true));
+ iter.skip(2);
+ assertThat(iter.getPosition(), is(5L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextNode(), is(child5));
+ assertThat(iter.getPosition(), is(6L));
+ assertThat(iter.hasNext(), is(false));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowNodeIteratorRemove() throws Exception {
+ node.getNodes().remove();
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNodeIteratorNegativeSkip() throws Exception {
+ node.getNodes().skip(-1);
+ }
+}
Property changes on: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeIteratorTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Added: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java (rev 0)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java 2008-09-09 18:56:21 UTC (rev 512)
@@ -0,0 +1,88 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import java.util.HashSet;
+import java.util.Set;
+import javax.jcr.Property;
+import javax.jcr.PropertyIterator;
+import javax.jcr.Session;
+import org.jboss.dna.jcr.AbstractJcrNodeTest.MockAbstractJcrNode;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoAnnotations.Mock;
+
+/**
+ * @author jverhaeg
+ */
+public class JcrPropertyIteratorTest {
+
+ private AbstractJcrNode node;
+ @Mock
+ private Session session;
+ private Set<Property> properties;
+
+ @Before
+ public void before() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ properties = new HashSet<Property>();
+ node = new MockAbstractJcrNode(session, "node", null);
+ node.setProperties(properties);
+ }
+
+ @Test
+ public void shouldProvidePropertyIterator() throws Exception {
+ properties.add(Mockito.mock(Property.class));
+ properties.add(Mockito.mock(Property.class));
+ properties.add(Mockito.mock(Property.class));
+ properties.add(Mockito.mock(Property.class));
+ PropertyIterator iter = node.getProperties();
+ assertThat(iter, notNullValue());
+ assertThat(iter.getSize(), is(-1L));
+ assertThat(iter.getPosition(), is(0L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.next(), notNullValue());
+ assertThat(iter.getPosition(), is(1L));
+ assertThat(iter.hasNext(), is(true));
+ iter.skip(2);
+ assertThat(iter.getPosition(), is(3L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextProperty(), notNullValue());
+ assertThat(iter.getPosition(), is(4L));
+ assertThat(iter.hasNext(), is(false));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowPropertyIteratorRemove() throws Exception {
+ node.getProperties().remove();
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowPropertyIteratorNegativeSkip() throws Exception {
+ node.getProperties().skip(-1);
+ }
+}
Property changes on: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
15 years, 7 months
DNA SVN: r511 - in trunk: dna-repository/src/test/java/org/jboss/dna/repository and 3 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-09 12:06:09 -0400 (Tue, 09 Sep 2008)
New Revision: 511
Added:
trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/commands/executor/SingleSourceCommandExecutor.java
Modified:
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java
trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java
trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java
trunk/dna-spi/src/main/java/org/jboss/dna/spi/DnaLexicon.java
trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepository.java
Log:
Removed some dependencies on the federation connector in the RepositoryService.
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java 2008-09-09 15:58:30 UTC (rev 510)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositoryService.java 2008-09-09 16:06:09 UTC (rev 511)
@@ -22,11 +22,8 @@
package org.jboss.dna.repository;
import java.lang.reflect.InvocationTargetException;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import net.jcip.annotations.ThreadSafe;
@@ -36,14 +33,11 @@
import org.jboss.dna.common.component.StandardClassLoaderFactory;
import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.common.util.Reflection;
-import org.jboss.dna.connector.federation.FederatedRepositorySource;
import org.jboss.dna.connector.federation.FederationException;
-import org.jboss.dna.connector.federation.Projection;
-import org.jboss.dna.connector.federation.executor.FederatingCommandExecutor;
-import org.jboss.dna.connector.federation.executor.SingleProjectionCommandExecutor;
import org.jboss.dna.repository.services.AbstractServiceAdministrator;
import org.jboss.dna.repository.services.AdministeredService;
import org.jboss.dna.repository.services.ServiceAdministrator;
+import org.jboss.dna.spi.DnaLexicon;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.graph.Name;
@@ -55,7 +49,7 @@
import org.jboss.dna.spi.graph.ValueFactory;
import org.jboss.dna.spi.graph.commands.GraphCommand;
import org.jboss.dna.spi.graph.commands.executor.CommandExecutor;
-import org.jboss.dna.spi.graph.commands.executor.NoOpCommandExecutor;
+import org.jboss.dna.spi.graph.commands.executor.SingleSourceCommandExecutor;
import org.jboss.dna.spi.graph.commands.impl.BasicCompositeCommand;
import org.jboss.dna.spi.graph.commands.impl.BasicGetChildrenCommand;
import org.jboss.dna.spi.graph.commands.impl.BasicGetNodeCommand;
@@ -66,12 +60,6 @@
@ThreadSafe
public class RepositoryService implements AdministeredService {
- protected static final String CLASSNAME_PROPERTY_NAME = "dna:classname";
- protected static final String CLASSPATH_PROPERTY_NAME = "dna:classpath";
- protected static final String PROJECTION_RULES_PROPERTY_NAME = "dna:projectionRules";
- protected static final String CACHE_POLICY_TIME_TO_EXPIRE = "dna:timeToExpire";
- protected static final String CACHE_POLICY_TIME_TO_CACHE = "dna:timeToCache";
-
/**
* The administrative component for this service.
*
@@ -114,16 +102,17 @@
private final ClassLoaderFactory classLoaderFactory;
private final ExecutionContext context;
private final RepositorySourceManager sources;
- private final Projection configurationProjection;
+ private final String configurationSourceName;
+ private final Path pathToConfigurationRoot;
private final Administrator administrator = new Administrator();
private final AtomicBoolean started = new AtomicBoolean(false);
/**
- * Create a federation service instance
+ * Create a service instance, reading the configuration describing new {@link RepositorySource} instances from the source with
+ * the supplied name.
*
* @param sources the source manager
- * @param configurationProjection the projection defining where the service can find configuration information for the
- * different repositories that it is to manage
+ * @param configurationSourceName the name of the {@link RepositorySource} that is the configuration repository
* @param context the execution context in which this service should run
* @param classLoaderFactory the class loader factory used to instantiate {@link RepositorySource} instances; may be null if
* this instance should use a default factory that attempts to load classes first from the
@@ -132,14 +121,39 @@
* @throws IllegalArgumentException if the bootstrap source is null or the execution context is null
*/
public RepositoryService( RepositorySourceManager sources,
- Projection configurationProjection,
+ String configurationSourceName,
ExecutionContext context,
ClassLoaderFactory classLoaderFactory ) {
- ArgCheck.isNotNull(configurationProjection, "configurationProjection");
+ this(sources, configurationSourceName, null, context, classLoaderFactory);
+ }
+
+ /**
+ * Create a service instance, reading the configuration describing new {@link RepositorySource} instances from the source with
+ * the supplied name and path within the repository.
+ *
+ * @param sources the source manager
+ * @param configurationSourceName the name of the {@link RepositorySource} that is the configuration repository
+ * @param pathToConfigurationRoot the path of the node in the configuration source repository that should be treated by this
+ * service as the root of the service's configuration; if null, then "/" is used
+ * @param context the execution context in which this service should run
+ * @param classLoaderFactory the class loader factory used to instantiate {@link RepositorySource} instances; may be null if
+ * this instance should use a default factory that attempts to load classes first from the
+ * {@link Thread#getContextClassLoader() thread's current context class loader} and then from the class loader that
+ * loaded this class.
+ * @throws IllegalArgumentException if the bootstrap source is null or the execution context is null
+ */
+ public RepositoryService( RepositorySourceManager sources,
+ String configurationSourceName,
+ Path pathToConfigurationRoot,
+ ExecutionContext context,
+ ClassLoaderFactory classLoaderFactory ) {
+ ArgCheck.isNotNull(configurationSourceName, "configurationSourceName");
ArgCheck.isNotNull(sources, "sources");
ArgCheck.isNotNull(context, "context");
+ if (pathToConfigurationRoot == null) pathToConfigurationRoot = context.getValueFactories().getPathFactory().createRootPath();
this.sources = sources;
- this.configurationProjection = configurationProjection;
+ this.pathToConfigurationRoot = pathToConfigurationRoot;
+ this.configurationSourceName = configurationSourceName;
this.context = context;
this.classLoaderFactory = classLoaderFactory != null ? classLoaderFactory : new StandardClassLoaderFactory();
}
@@ -152,10 +166,10 @@
}
/**
- * @return configurationProjection
+ * @return configurationSourceName
*/
- public Projection getConfigurationProjection() {
- return configurationProjection;
+ public String getConfigurationSourceName() {
+ return configurationSourceName;
}
/**
@@ -195,27 +209,12 @@
PathFactory pathFactory = valueFactories.getPathFactory();
NameFactory nameFactory = valueFactories.getNameFactory();
- final String configurationSourceName = configurationProjection.getSourceName();
+ // Create a command executor to execute the commands.
+ CommandExecutor executor = new SingleSourceCommandExecutor(context, configurationSourceName, sources);
- // Create a federating command executor to execute the commands and merge the results into a single set of
- // commands.
- List<Projection> projections = Collections.singletonList(configurationProjection);
- CommandExecutor executor = null;
- if (configurationProjection.getRules().size() == 0) {
- // There is no projection for the configuration repository, so just use a no-op executor
- executor = new NoOpCommandExecutor(context, configurationSourceName);
- } else if (configurationProjection.isSimple()) {
- // There is just a single projection for the configuration repository, so just use an executor that
- // translates the paths using the projection
- executor = new SingleProjectionCommandExecutor(context, configurationSourceName, configurationProjection, sources);
- } else {
- // The configuration repository has more than one projection, so we need to merge the results
- executor = new FederatingCommandExecutor(context, configurationSourceName, projections, sources);
- }
-
// Read the configuration and the repository sources, located as child nodes/branches under "/dna:sources",
// and then instantiate and register each in the "sources" manager
- Path configurationRoot = pathFactory.create("/");
+ Path configurationRoot = this.pathToConfigurationRoot;
try {
Path sourcesNode = pathFactory.create(configurationRoot, nameFactory.create("dna:sources"));
BasicGetChildrenCommand getSources = new BasicGetChildrenCommand(sourcesNode);
@@ -264,14 +263,13 @@
Map<Name, Property> properties,
Problems problems ) {
ValueFactories valueFactories = context.getValueFactories();
- NameFactory nameFactory = valueFactories.getNameFactory();
ValueFactory<String> stringFactory = valueFactories.getStringFactory();
// Get the classname and classpath ...
- Property classnameProperty = properties.get(nameFactory.create(CLASSNAME_PROPERTY_NAME));
- Property classpathProperty = properties.get(nameFactory.create(CLASSPATH_PROPERTY_NAME));
+ Property classnameProperty = properties.get(DnaLexicon.CLASSNAME);
+ Property classpathProperty = properties.get(DnaLexicon.CLASSPATH);
if (classnameProperty == null) {
- problems.addError(RepositoryI18n.requiredPropertyIsMissingFromNode, CLASSNAME_PROPERTY_NAME, path);
+ problems.addError(RepositoryI18n.requiredPropertyIsMissingFromNode, DnaLexicon.CLASSNAME, path);
}
// If the classpath property is null or empty, the default classpath will be used
if (problems.hasErrors()) return null;
@@ -338,21 +336,6 @@
}
/**
- * Get the current set of federated repository names.
- *
- * @return the names of the repository, which is a mutable copy of the names that is not backed by the actual sources
- */
- public Set<String> getFederatedRepositoryNames() {
- Set<String> repositoryNames = new HashSet<String>();
- for (RepositorySource source : sources.getSources()) {
- if (source instanceof FederatedRepositorySource) {
- repositoryNames.add(source.getName());
- }
- }
- return repositoryNames;
- }
-
- /**
* {@inheritDoc}
*/
@Override
Modified: trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java
===================================================================
--- trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java 2008-09-09 15:58:30 UTC (rev 510)
+++ trunk/dna-repository/src/main/java/org/jboss/dna/repository/RepositorySourceManager.java 2008-09-09 16:06:09 UTC (rev 511)
@@ -102,6 +102,13 @@
/**
* Create a new manager instance.
+ */
+ public RepositorySourceManager() {
+ this(null);
+ }
+
+ /**
+ * Create a new manager instance.
*
* @param delegate the connection factory to which this instance should delegate in the event that a source is not found in
* this manager; may be null if there is no delegate
Modified: trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java
===================================================================
--- trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java 2008-09-09 15:58:30 UTC (rev 510)
+++ trunk/dna-repository/src/test/java/org/jboss/dna/repository/RepositoryServiceTest.java 2008-09-09 16:06:09 UTC (rev 511)
@@ -37,7 +37,6 @@
import org.jboss.dna.common.component.ClassLoaderFactory;
import org.jboss.dna.common.util.Logger;
import org.jboss.dna.connector.federation.FederationException;
-import org.jboss.dna.connector.federation.Projection;
import org.jboss.dna.repository.services.ServiceAdministrator;
import org.jboss.dna.spi.DnaLexicon;
import org.jboss.dna.spi.ExecutionContext;
@@ -46,8 +45,6 @@
import org.jboss.dna.spi.connector.RepositorySource;
import org.jboss.dna.spi.connector.SimpleRepository;
import org.jboss.dna.spi.connector.SimpleRepositorySource;
-import org.jboss.dna.spi.graph.Path;
-import org.jboss.dna.spi.graph.PathFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -59,15 +56,7 @@
*/
public class RepositoryServiceTest {
- public static final String CLASSNAME = RepositoryService.CLASSNAME_PROPERTY_NAME;
- public static final String CLASSPATH = RepositoryService.CLASSPATH_PROPERTY_NAME;
- public static final String PROJECTION_RULES = RepositoryService.PROJECTION_RULES_PROPERTY_NAME;
- public static final String TIME_TO_EXPIRE = RepositoryService.CACHE_POLICY_TIME_TO_EXPIRE;
- public static final String TIME_TO_CACHE = RepositoryService.CACHE_POLICY_TIME_TO_CACHE;
-
private RepositoryService service;
- private Projection configProjection;
- private PathFactory pathFactory;
private String configSourceName;
private SimpleRepository configRepository;
private SimpleRepositorySource configRepositorySource;
@@ -81,19 +70,14 @@
MockitoAnnotations.initMocks(this);
context = new BasicExecutionContext();
context.getNamespaceRegistry().register(DnaLexicon.Namespace.PREFIX, DnaLexicon.Namespace.URI);
- pathFactory = context.getValueFactories().getPathFactory();
- Path pathInRepository = pathFactory.create("/");
- Path pathInSource = pathFactory.create("/reposX");
configSourceName = "configSource";
- Projection.Rule configProjectionRule = new Projection.PathRule(pathInRepository, pathInSource);
- configProjection = new Projection(configSourceName, configProjectionRule);
configRepository = SimpleRepository.get("Configuration Repository");
configRepositorySource = new SimpleRepositorySource();
configRepositorySource.setRepositoryName(configRepository.getRepositoryName());
configRepositorySource.setName(configSourceName);
configRepositoryConnection = configRepositorySource.getConnection();
stub(sources.createConnection(configSourceName)).toReturn(configRepositoryConnection);
- service = new RepositoryService(sources, configProjection, context, null);
+ service = new RepositoryService(sources, configSourceName, context, null);
}
@After
@@ -110,9 +94,9 @@
}
@Test
- public void shouldHaveConfigurationRegionAfterInstantiation() {
- assertThat(service.getConfigurationProjection(), is(notNullValue()));
- assertThat(service.getConfigurationProjection(), is(sameInstance(configProjection)));
+ public void shouldHaveConfigurationSourceAfterInstantiation() {
+ assertThat(service.getConfigurationSourceName(), is(notNullValue()));
+ assertThat(service.getConfigurationSourceName(), is(configSourceName));
}
@Test
@@ -129,7 +113,7 @@
@Test
public void shouldHaveNonNullClassLoaderFactoryAfterInstantiatingWithClassLoaderFactoryReference() {
ClassLoaderFactory classLoaderFactory = mock(ClassLoaderFactory.class);
- service = new RepositoryService(sources, configProjection, context, classLoaderFactory);
+ service = new RepositoryService(sources, configSourceName, context, classLoaderFactory);
assertThat(service.getClassLoaderFactory(), is(notNullValue()));
assertThat(service.getClassLoaderFactory(), is(sameInstance(classLoaderFactory)));
}
@@ -166,22 +150,23 @@
sources.addSource(configRepositorySource);
assertThat(sources.getSources(), hasItems((RepositorySource)configRepositorySource));
assertThat(sources.getSources().size(), is(1));
- service = new RepositoryService(sources, configProjection, context, null);
+ service = new RepositoryService(sources, configSourceName, context, null);
// Set up the configuration repository to contain 3 sources ...
- configRepository.create(context, "/reposX/dna:sources");
- configRepository.setProperty(context, "/reposX/dna:sources/source A", CLASSNAME, SimpleRepositorySource.class.getName());
- configRepository.setProperty(context, "/reposX/dna:sources/source A", CLASSPATH, "");
- configRepository.setProperty(context, "/reposX/dna:sources/source A", "repositoryName", "sourceReposA");
- configRepository.setProperty(context, "/reposX/dna:sources/source A", "retryLimit", 3);
+ final String className = SimpleRepositorySource.class.getName();
+ configRepository.create(context, "/dna:sources");
+ configRepository.setProperty(context, "/dna:sources/source A", DnaLexicon.CLASSNAME, className);
+ configRepository.setProperty(context, "/dna:sources/source A", DnaLexicon.CLASSPATH, "");
+ configRepository.setProperty(context, "/dna:sources/source A", "repositoryName", "sourceReposA");
+ configRepository.setProperty(context, "/dna:sources/source A", "retryLimit", 3);
- configRepository.setProperty(context, "/reposX/dna:sources/source B", CLASSNAME, SimpleRepositorySource.class.getName());
- configRepository.setProperty(context, "/reposX/dna:sources/source B", CLASSPATH, "");
- configRepository.setProperty(context, "/reposX/dna:sources/source B", "repositoryName", "sourceReposB");
+ configRepository.setProperty(context, "/dna:sources/source B", DnaLexicon.CLASSNAME, className);
+ configRepository.setProperty(context, "/dna:sources/source B", DnaLexicon.CLASSPATH, "");
+ configRepository.setProperty(context, "/dna:sources/source B", "repositoryName", "sourceReposB");
- configRepository.setProperty(context, "/reposX/dna:sources/source C", CLASSNAME, SimpleRepositorySource.class.getName());
- configRepository.setProperty(context, "/reposX/dna:sources/source C", CLASSPATH, "");
- configRepository.setProperty(context, "/reposX/dna:sources/source C", "repositoryName", "sourceReposC");
+ configRepository.setProperty(context, "/dna:sources/source C", DnaLexicon.CLASSNAME, className);
+ configRepository.setProperty(context, "/dna:sources/source C", DnaLexicon.CLASSPATH, "");
+ configRepository.setProperty(context, "/dna:sources/source C", "repositoryName", "sourceReposC");
// Now, start up the service ...
service.getAdministrator().start();
@@ -211,7 +196,7 @@
@Test
public void shouldStartUpUsingConfigurationRepositoryThatContainsNoSources() throws Exception {
// Set up the configuration repository to contain NO sources ...
- configRepository.create(context, "/reposX/dna:sources");
+ configRepository.create(context, "/dna:sources");
// Now, start up the service ...
service.getAdministrator().start();
@@ -226,19 +211,24 @@
@Test
public void shouldStartUpAndCreateRepositoryUsingConfigurationRepositoryThatContainsNoSources() {
// Set up the configuration repository ...
- configRepository.create(context, "/reposX/dna:sources");
- configRepository.setProperty(context, "/reposX/dna:sources/source A", CLASSNAME, SimpleRepositorySource.class.getName());
- configRepository.setProperty(context, "/reposX/dna:sources/source A", CLASSPATH, "");
- configRepository.setProperty(context, "/reposX/dna:sources/source A", "repositoryName", "sourceReposA");
- configRepository.setProperty(context, "/reposX/dna:sources/source A", "retryLimit", 3);
+ configRepository.create(context, "/dna:sources");
+ configRepository.setProperty(context,
+ "/dna:sources/source A",
+ DnaLexicon.CLASSNAME,
+ SimpleRepositorySource.class.getName());
+ configRepository.setProperty(context, "/dna:sources/source A", DnaLexicon.CLASSPATH, "");
+ configRepository.setProperty(context, "/dna:sources/source A", "repositoryName", "sourceReposA");
+ configRepository.setProperty(context, "/dna:sources/source A", "retryLimit", 3);
- String fedReposPath = "/reposX/dna:repositories/fed repos/";
- configRepository.setProperty(context, fedReposPath, TIME_TO_CACHE, "10000");
- configRepository.setProperty(context, fedReposPath, TIME_TO_EXPIRE, "20000");
- configRepository.setProperty(context, fedReposPath + "dna:regions/source A", PROJECTION_RULES, "/a/b/c => /sx/sy");
- configRepository.setProperty(context, fedReposPath + "dna:regions/source B", PROJECTION_RULES, "/ => /");
- configRepository.setProperty(context, fedReposPath + "dna:regions/source C", PROJECTION_RULES, "/d/e/f => /");
- configRepository.setProperty(context, fedReposPath + "dna:regions/source D", PROJECTION_RULES, "/ => /x/y/z");
+ String fedReposPath = "/dna:repositories/fed repos/";
+ configRepository.setProperty(context, fedReposPath, DnaLexicon.TIME_TO_EXPIRE, "20000");
+ configRepository.setProperty(context,
+ fedReposPath + "dna:regions/source A",
+ DnaLexicon.PROJECTION_RULES,
+ "/a/b/c => /sx/sy");
+ configRepository.setProperty(context, fedReposPath + "dna:regions/source B", DnaLexicon.PROJECTION_RULES, "/ => /");
+ configRepository.setProperty(context, fedReposPath + "dna:regions/source C", DnaLexicon.PROJECTION_RULES, "/d/e/f => /");
+ configRepository.setProperty(context, fedReposPath + "dna:regions/source D", DnaLexicon.PROJECTION_RULES, "/ => /x/y/z");
// Now, start up the service ...
service.getAdministrator().start();
Modified: trunk/dna-spi/src/main/java/org/jboss/dna/spi/DnaLexicon.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/DnaLexicon.java 2008-09-09 15:58:30 UTC (rev 510)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/DnaLexicon.java 2008-09-09 16:06:09 UTC (rev 511)
@@ -36,4 +36,8 @@
public static final Name UUID = new BasicName(Namespace.URI, "uuid");
public static final Name MERGE_PLAN = new BasicName(Namespace.URI, "mergePlan");
+ public static final Name CLASSNAME = new BasicName(Namespace.URI, "classname");
+ public static final Name CLASSPATH = new BasicName(Namespace.URI, "classpath");
+ public static final Name PROJECTION_RULES = new BasicName(Namespace.URI, "projectionRules");
+ public static final Name TIME_TO_EXPIRE = new BasicName(Namespace.URI, "timeToExpire");
}
Added: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/commands/executor/SingleSourceCommandExecutor.java
===================================================================
--- trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/commands/executor/SingleSourceCommandExecutor.java (rev 0)
+++ trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/commands/executor/SingleSourceCommandExecutor.java 2008-09-09 16:06:09 UTC (rev 511)
@@ -0,0 +1,193 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.spi.graph.commands.executor;
+
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.connector.RepositoryConnection;
+import org.jboss.dna.spi.connector.RepositoryConnectionFactory;
+import org.jboss.dna.spi.connector.RepositorySource;
+import org.jboss.dna.spi.connector.RepositorySourceException;
+import org.jboss.dna.spi.graph.DateTime;
+import org.jboss.dna.spi.graph.commands.CopyBranchCommand;
+import org.jboss.dna.spi.graph.commands.CopyNodeCommand;
+import org.jboss.dna.spi.graph.commands.CreateNodeCommand;
+import org.jboss.dna.spi.graph.commands.DeleteBranchCommand;
+import org.jboss.dna.spi.graph.commands.GetChildrenCommand;
+import org.jboss.dna.spi.graph.commands.GetPropertiesCommand;
+import org.jboss.dna.spi.graph.commands.MoveBranchCommand;
+import org.jboss.dna.spi.graph.commands.RecordBranchCommand;
+import org.jboss.dna.spi.graph.commands.SetPropertiesCommand;
+
+/**
+ * @author Randall Hauch
+ */
+public class SingleSourceCommandExecutor extends AbstractCommandExecutor {
+
+ private RepositoryConnection connection;
+ private final RepositoryConnectionFactory connectionFactory;
+
+ /**
+ * Create a command executor that does nothing.
+ *
+ * @param context the execution context in which the executor will be run; may not be null
+ * @param sourceName the name of the {@link RepositorySource} that is making use of this executor; may not be null or empty
+ * @param connectionFactory the factory for {@link RepositoryConnection} instances
+ */
+ public SingleSourceCommandExecutor( ExecutionContext context,
+
+ String sourceName,
+ RepositoryConnectionFactory connectionFactory ) {
+ this(context, sourceName, null, connectionFactory);
+ }
+
+ /**
+ * Create a command executor that does nothing.
+ *
+ * @param context the execution context in which the executor will be run; may not be null
+ * @param sourceName the name of the {@link RepositorySource} that is making use of this executor; may not be null or empty
+ * @param now the current time; may be null if the system time is to be used
+ * @param connectionFactory the factory for {@link RepositoryConnection} instances
+ */
+ public SingleSourceCommandExecutor( ExecutionContext context,
+ String sourceName,
+ DateTime now,
+ RepositoryConnectionFactory connectionFactory ) {
+ super(context, sourceName, now);
+ assert connectionFactory != null;
+ this.connectionFactory = connectionFactory;
+ }
+
+ protected RepositoryConnection getConnection() throws RepositorySourceException {
+ if (connection == null) {
+ // Create a connection ...
+ connection = this.connectionFactory.createConnection(getSourceName());
+ }
+ return connection;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#close()
+ */
+ @Override
+ public void close() {
+ if (this.connection != null) {
+ try {
+ this.connection.close();
+ } finally {
+ this.connection = null;
+ }
+ }
+ super.close();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.CopyBranchCommand)
+ */
+ @Override
+ public void execute( CopyBranchCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.CopyNodeCommand)
+ */
+ @Override
+ public void execute( CopyNodeCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.CreateNodeCommand)
+ */
+ @Override
+ public void execute( CreateNodeCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.DeleteBranchCommand)
+ */
+ @Override
+ public void execute( DeleteBranchCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.GetChildrenCommand)
+ */
+ @Override
+ public void execute( GetChildrenCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.GetPropertiesCommand)
+ */
+ @Override
+ public void execute( GetPropertiesCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.MoveBranchCommand)
+ */
+ @Override
+ public void execute( MoveBranchCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.RecordBranchCommand)
+ */
+ @Override
+ public void execute( RecordBranchCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see org.jboss.dna.spi.graph.commands.executor.AbstractCommandExecutor#execute(org.jboss.dna.spi.graph.commands.SetPropertiesCommand)
+ */
+ @Override
+ public void execute( SetPropertiesCommand command ) throws RepositorySourceException {
+ getConnection().execute(this.getExecutionContext(), command);
+ }
+}
Property changes on: trunk/dna-spi/src/main/java/org/jboss/dna/spi/graph/commands/executor/SingleSourceCommandExecutor.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepository.java
===================================================================
--- trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepository.java 2008-09-09 15:58:30 UTC (rev 510)
+++ trunk/dna-spi/src/test/java/org/jboss/dna/spi/connector/SimpleRepository.java 2008-09-09 16:06:09 UTC (rev 511)
@@ -130,18 +130,35 @@
String path,
String propertyName,
Object... values ) {
+ NameFactory nameFactory = context.getValueFactories().getNameFactory();
+ return setProperty(context, path, nameFactory.create(propertyName), values);
+ }
+
+ /**
+ * Utility method to help set the property on the node given by the supplied path. If the node does not exist, it will be
+ * created.
+ *
+ * @param context the execution context; may not be null
+ * @param path the path to the node; may not be null
+ * @param propertyName the property name; may not be null
+ * @param values the values of the property
+ * @return this repository, for method chaining
+ */
+ public SimpleRepository setProperty( ExecutionContext context,
+ String path,
+ Name propertyName,
+ Object... values ) {
Logger logger = context.getLogger(getClass());
if (logger.isTraceEnabled()) {
logger.trace("Setting property {0} on {1} to {2}", propertyName, path, StringUtil.readableString(values));
}
PathFactory pathFactory = context.getValueFactories().getPathFactory();
- NameFactory nameFactory = context.getValueFactories().getNameFactory();
PropertyFactory propertyFactory = context.getPropertyFactory();
Path pathObj = pathFactory.create(path);
if (!pathObj.isRoot()) {
create(context, pathObj.getParent().getString(context.getNamespaceRegistry()));
}
- Property property = propertyFactory.create(nameFactory.create(propertyName), values);
+ Property property = propertyFactory.create(propertyName, values);
Map<Name, Property> properties = new HashMap<Name, Property>();
Map<Name, Property> existingProperties = data.putIfAbsent(pathObj, properties);
if (existingProperties == null) existingProperties = properties;
15 years, 7 months
DNA SVN: r510 - in trunk/dna-jcr/src: test/java/org/jboss/dna/jcr and 1 other directory.
by dna-commits@lists.jboss.org
Author: jverhaeg(a)redhat.com
Date: 2008-09-09 11:58:30 -0400 (Tue, 09 Sep 2008)
New Revision: 510
Modified:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
Log:
DNA-178: Lost some code when I updated before my last commit.
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-09 15:18:27 UTC (rev 509)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-09 15:58:30 UTC (rev 510)
@@ -470,7 +470,11 @@
* @see javax.jcr.Session#itemExists(java.lang.String)
*/
public boolean itemExists( String absolutePath ) throws RepositoryException {
- return (getItem(absolutePath) != null);
+ try {
+ return (getItem(absolutePath) != null);
+ } catch (PathNotFoundException error) {
+ return false;
+ }
}
/**
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2008-09-09 15:18:27 UTC (rev 509)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2008-09-09 15:58:30 UTC (rev 510)
@@ -274,6 +274,17 @@
@Test
public void shouldProvideItemExists() throws Exception {
- assertThat(session.itemExists(""), is(false));
+ assertThat(session.itemExists("/a/b"), is(true));
+ assertThat(session.itemExists("/a/c"), is(false));
}
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowItemExistsWithNoPath() throws Exception {
+ session.itemExists(null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowItemExistsWithEmptyPath() throws Exception {
+ session.itemExists("");
+ }
}
15 years, 7 months
DNA SVN: r509 - in trunk/dna-jcr/src: main/resources/org/jboss/dna/jcr and 1 other directories.
by dna-commits@lists.jboss.org
Author: jverhaeg(a)redhat.com
Date: 2008-09-09 11:18:27 -0400 (Tue, 09 Sep 2008)
New Revision: 509
Added:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrMultiValueProperty.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrMultiValuePropertyTest.java
Removed:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java
Modified:
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrItem.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrProperty.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNode.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrProperty.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRootNode.java
trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrItemTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrPropertyTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRootNodeTest.java
trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
Log:
DNA-178: Completed implementing a read-only version of JCR over DNA.
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrItem.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrItem.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrItem.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -22,59 +22,80 @@
package org.jboss.dna.jcr;
import javax.jcr.Item;
+import javax.jcr.RepositoryException;
/**
* @author jverhaeg
*/
abstract class AbstractJcrItem implements Item {
+ protected final String getPath( String absolutePath,
+ String relativePath ) {
+ assert absolutePath != null;
+ assert absolutePath.length() > 0;
+ assert relativePath != null;
+ if (absolutePath.charAt(absolutePath.length() - 1) == '/') {
+ return absolutePath + relativePath;
+ }
+ return absolutePath + '/' + relativePath;
+ }
+
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Item#isModified()
*/
public final boolean isModified() {
- // TODO: Update when level 2
return false;
}
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Item#isNew()
*/
public final boolean isNew() {
- // TODO: Update when level 2
return false;
}
/**
* {@inheritDoc}
*
+ * @see javax.jcr.Item#isSame(javax.jcr.Item)
+ */
+ public boolean isSame( Item otherItem ) throws RepositoryException {
+ return (getSession().getWorkspace() == otherItem.getSession().getWorkspace());
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Item#refresh(boolean)
*/
public void refresh( boolean keepChanges ) {
- // TODO: Update when level 2
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Item#remove()
*/
public void remove() {
- // TODO: Update when level 2
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Item#save()
*/
public void save() {
- // TODO: Update when level 2
throw new UnsupportedOperationException();
}
}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrNode.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -24,16 +24,17 @@
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
-import java.util.HashMap;
+import java.util.Iterator;
import java.util.List;
-import java.util.Map;
+import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
-import java.util.Map.Entry;
import javax.jcr.Item;
+import javax.jcr.ItemNotFoundException;
import javax.jcr.ItemVisitor;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
+import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
@@ -49,7 +50,6 @@
import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.spi.graph.Name;
import org.jboss.dna.spi.graph.Path.Segment;
-import org.jboss.dna.spi.graph.impl.BasicPathSegment;
/**
* @author jverhaeg
@@ -58,8 +58,9 @@
abstract class AbstractJcrNode extends AbstractJcrItem implements Node {
private final Session session;
- private Set<Property> properties;
- private Map<Name, Integer> childCountsByName;
+ Set<Property> properties;
+ List<Name> children;
+ List<Integer> childNameCounts;
private UUID uuid;
AbstractJcrNode( Session session ) {
@@ -70,82 +71,92 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>visitor</code> is <code>null</code>.
* @see javax.jcr.Item#accept(javax.jcr.ItemVisitor)
*/
- public void accept( ItemVisitor visitor ) throws RepositoryException {
+ public final void accept( ItemVisitor visitor ) throws RepositoryException {
+ ArgCheck.isNotNull(visitor, "visitor");
visitor.visit(this);
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#addMixin(java.lang.String)
*/
- public void addMixin( String mixinName ) {
+ public final void addMixin( String mixinName ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#addNode(java.lang.String)
*/
- public Node addNode( String relPath ) {
+ public final Node addNode( String relPath ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#addNode(java.lang.String, java.lang.String)
*/
- public Node addNode( String relPath,
- String primaryNodeTypeName ) {
+ public final Node addNode( String relPath,
+ String primaryNodeTypeName ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Node#canAddMixin(java.lang.String)
*/
- public boolean canAddMixin( String mixinName ) {
- throw new UnsupportedOperationException();
+ public final boolean canAddMixin( String mixinName ) {
+ return false;
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#cancelMerge(javax.jcr.version.Version)
*/
- public void cancelMerge( Version version ) {
+ public final void cancelMerge( Version version ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#checkin()
*/
- public Version checkin() {
+ public final Version checkin() {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#checkout()
*/
- public void checkout() {
+ public final void checkout() {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#doneMerge(javax.jcr.version.Version)
*/
- public void doneMerge( Version version ) {
+ public final void doneMerge( Version version ) {
throw new UnsupportedOperationException();
}
@@ -167,46 +178,33 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#getBaseVersion()
*/
- public Version getBaseVersion() {
- throw new UnsupportedOperationException();
+ public final Version getBaseVersion() throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
- private Map<Name, Integer> getChildCountsByName() {
- if (childCountsByName == null) {
- childCountsByName = new HashMap<Name, Integer>();
- }
- return childCountsByName;
- }
-
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getCorrespondingNodePath(java.lang.String)
*/
- public String getCorrespondingNodePath( String workspaceName ) {
+ public final String getCorrespondingNodePath( String workspaceName ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getDefinition()
*/
public NodeDefinition getDefinition() {
throw new UnsupportedOperationException();
}
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.Node#getIndex()
- */
- public int getIndex() {
- throw new UnsupportedOperationException();
- }
-
final UUID getInternalUuid() {
return uuid;
}
@@ -214,15 +212,17 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#getLock()
*/
- public Lock getLock() {
- throw new UnsupportedOperationException();
+ public final Lock getLock() throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getMixinNodeTypes()
*/
public NodeType[] getMixinNodeTypes() {
@@ -232,10 +232,16 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>relativePath</code> is empty or <code>null</code>.
* @see javax.jcr.Node#getNode(java.lang.String)
*/
- public final Node getNode( String relativePath ) {
- throw new UnsupportedOperationException();
+ public final Node getNode( String relativePath ) throws RepositoryException {
+ ArgCheck.isNotEmpty(relativePath, "relativePath");
+ Item item = getSession().getItem(getPath(getPath(), relativePath));
+ if (item instanceof Node) {
+ return (Node)item;
+ }
+ throw new PathNotFoundException();
}
/**
@@ -243,16 +249,76 @@
*
* @see javax.jcr.Node#getNodes()
*/
- public NodeIterator getNodes() {
- throw new UnsupportedOperationException();
+ public final NodeIterator getNodes() {
+ return new NodeIterator() {
+
+ private final Iterator<Name> childIterator = (children == null ? null : children.iterator());
+ private final Iterator<Integer> childNameCountIterator = (childNameCounts == null ? null : childNameCounts.iterator());
+ private Name child;
+ private int childNameCount;
+ private int childNdx = 1;
+ private int ndx;
+ private Node node;
+
+ public long getPosition() {
+ return ndx;
+ }
+
+ public long getSize() {
+ return -1;
+ }
+
+ public boolean hasNext() {
+ return ((childIterator != null && childIterator.hasNext()) || (child != null && childNdx <= childNameCount));
+ }
+
+ public Object next() {
+ return nextNode();
+ }
+
+ public Node nextNode() {
+ if (childIterator == null) {
+ throw new NoSuchElementException();
+ }
+ if (child == null || childNdx > childNameCount) {
+ child = childIterator.next();
+ childNameCount = childNameCountIterator.next();
+ childNdx = 1;
+ }
+ try {
+ node = getNode(child.getString() + '[' + childNdx + ']');
+ childNdx++;
+ ndx++;
+ return node;
+ } catch (RepositoryException error) {
+ // TODO: Change to DnaException once DNA-180 is addressed
+ throw new RuntimeException(error);
+ }
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ public void skip( long count ) {
+ ArgCheck.isNonNegative(count, "count");
+ while (--count >= 0) {
+ nextNode();
+ }
+ }
+ };
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getNodes(java.lang.String)
*/
public NodeIterator getNodes( String namePattern ) {
+ // TODO: Implement after changing impl to delegate to Graph API
+ throw new UnsupportedOperationException();
+ /*
ArgCheck.isNotEmpty(namePattern, "namePattern");
String[] disjuncts = namePattern.split("\\|");
List<Segment> nodes = new ArrayList<Segment>();
@@ -266,42 +332,15 @@
ndxPattern = pattern.substring(ndx + 1, endNdx);
pattern = pattern.substring(0, ndx);
} else ndxPattern = null;
- for (Entry<Name, Integer> entry : getChildCountsByName().entrySet()) {
- if (entry.getKey().getString().matches(pattern)) {
- if (ndxPattern != null && !entry.getValue().toString().matches(ndxPattern)) continue;
- if (entry.getValue() > 1) nodes.add(new BasicPathSegment(entry.getKey(), entry.getValue()));
- else nodes.add(new BasicPathSegment(entry.getKey()));
+ for (Entry<Name, Integer> child : getChildCountsByName().entrySet()) {
+ if (child.getKey().getLocalName().matches(pattern)) {
+ if (ndxPattern != null && !child.getValue().toString().matches(ndxPattern)) continue;
+ if (child.getValue() > 1) nodes.add(new BasicPathSegment(child.getKey(), child.getValue()));
+ else nodes.add(new BasicPathSegment(child.getKey()));
}
}
}
- return new NodeIterator() {
-
- public Node nextNode() {
- return null;
- }
-
- public long getPosition() {
- return 0;
- }
-
- public long getSize() {
- return 0;
- }
-
- public void skip( long skipNum ) {
- }
-
- public boolean hasNext() {
- return false;
- }
-
- public Object next() {
- return null;
- }
-
- public void remove() {
- }
- };
+ */
}
/**
@@ -309,13 +348,20 @@
*
* @see javax.jcr.Node#getPrimaryItem()
*/
- public Item getPrimaryItem() {
- throw new UnsupportedOperationException();
+ public final Item getPrimaryItem() throws RepositoryException {
+ // TODO: Check if declared in the node type first
+ try {
+ Property primaryItemProp = getProperty("jcr:primaryItemName");
+ return session.getItem(getPath(getPath(), primaryItemProp.getString()));
+ } catch (PathNotFoundException error) {
+ throw new ItemNotFoundException(error);
+ }
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getPrimaryNodeType()
*/
public NodeType getPrimaryNodeType() {
@@ -327,39 +373,93 @@
*
* @see javax.jcr.Node#getProperties()
*/
- public PropertyIterator getProperties() {
- throw new UnsupportedOperationException();
+ public final PropertyIterator getProperties() {
+ assert properties != null;
+ return new PropertyIterator() {
+
+ private final Iterator<Property> iterator = properties.iterator();
+ private int ndx;
+
+ public long getPosition() {
+ return ndx;
+ }
+
+ public long getSize() {
+ return -1;
+ }
+
+ public boolean hasNext() {
+ return iterator.hasNext();
+ }
+
+ public Object next() {
+ return nextProperty();
+ }
+
+ public Property nextProperty() {
+ Property property = iterator.next();
+ ndx++;
+ return property;
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+
+ public void skip( long count ) {
+ ArgCheck.isNonNegative(count, "count");
+ while (--count >= 0) {
+ nextProperty();
+ }
+ }
+ };
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getProperties(java.lang.String)
*/
public PropertyIterator getProperties( String namePattern ) {
+ // TODO: Implement after changing impl to delegate to Graph API
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>relativePath</code> is empty or <code>null</code>.
* @see javax.jcr.Node#getProperty(java.lang.String)
*/
public final Property getProperty( String relativePath ) throws RepositoryException {
ArgCheck.isNotEmpty(relativePath, "relativePath");
- // TODO: Handle multi-segment paths
+ if (relativePath.indexOf('/') >= 0) {
+ Item item = session.getItem(getPath(getPath(), relativePath));
+ if (item instanceof Property) {
+ return (Property)item;
+ }
+ // The item must be a node.
+ assert item instanceof Node;
+ // Since session.getItem() gives precedence to nodes over properties, try explicitly looking for the property with the
+ // same name as the found node using the returned node's parent.
+ return ((Node)item).getParent().getProperty(item.getName());
+ }
+ assert properties != null;
for (Property property : properties) {
if (relativePath.equals(property.getName())) return property;
}
- return null;
+ throw new PathNotFoundException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#getReferences()
*/
- public PropertyIterator getReferences() {
+ public final PropertyIterator getReferences() {
+ // TODO: Need to provide this at the DNA layer first (probably via a connector query)
throw new UnsupportedOperationException();
}
@@ -378,12 +478,16 @@
* @see javax.jcr.Node#getUUID()
*/
public final String getUUID() throws RepositoryException {
- // Check if node is referenceable
- Property mixinsProp = getProperty("jcr:mixinTypes");
- if (mixinsProp != null) {
- for (Value value : mixinsProp.getValues()) {
- if ("mix:referenceable".equals(value.getString())) return getProperty("jcr:uuid").getString();
+ // Return JCR UUID only if node is referenceable
+ try {
+ Property mixinsProp = getProperty("jcr:mixinTypes");
+ if (mixinsProp != null) {
+ for (Value value : mixinsProp.getValues()) {
+ if ("mix:referenceable".equals(value.getString())) return getProperty("jcr:uuid").getString();
+ }
}
+ } catch (PathNotFoundException error) {
+ throw new UnsupportedRepositoryOperationException(error);
}
throw new UnsupportedRepositoryOperationException();
}
@@ -391,19 +495,40 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#getVersionHistory()
*/
- public VersionHistory getVersionHistory() {
- throw new UnsupportedOperationException();
+ public final VersionHistory getVersionHistory() throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>relativePath</code> is empty or <code>null</code>.
* @see javax.jcr.Node#hasNode(java.lang.String)
*/
- public boolean hasNode( String relPath ) {
- throw new UnsupportedOperationException();
+ public final boolean hasNode( String relativePath ) throws RepositoryException {
+ ArgCheck.isNotEmpty(relativePath, "relativePath");
+ if (relativePath.indexOf('/') >= 0) {
+ return (getNode(relativePath) != null);
+ }
+ int ndxNdx = relativePath.indexOf('[');
+ String name = (ndxNdx < 0 ? relativePath : relativePath.substring(0, ndxNdx));
+ ArgCheck.isNotEmpty(name, "relativePath");
+ int childNdx = 0;
+ if (children != null) {
+ for (Name child : children) {
+ if (name.equals(child.getString())) {
+ if (ndxNdx >= 0) {
+ return (Integer.parseInt(relativePath.substring(ndxNdx + 1, relativePath.length() - 1)) <= childNameCounts.get(childNdx));
+ }
+ return true;
+ }
+ childNdx++;
+ }
+ }
+ return false;
}
/**
@@ -411,8 +536,8 @@
*
* @see javax.jcr.Node#hasNodes()
*/
- public boolean hasNodes() {
- throw new UnsupportedOperationException();
+ public final boolean hasNodes() {
+ return (children != null && !children.isEmpty());
}
/**
@@ -420,49 +545,65 @@
*
* @see javax.jcr.Node#hasProperties()
*/
- public boolean hasProperties() {
- throw new UnsupportedOperationException();
+ public final boolean hasProperties() {
+ assert properties != null;
+ return !properties.isEmpty();
}
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>relativePath</code> is empty or <code>null</code>.
* @see javax.jcr.Node#hasProperty(java.lang.String)
*/
- public boolean hasProperty( String relPath ) {
- throw new UnsupportedOperationException();
+ public final boolean hasProperty( String relativePath ) throws RepositoryException {
+ ArgCheck.isNotEmpty(relativePath, "relativePath");
+ if (relativePath.indexOf('/') >= 0) {
+ return (getProperty(relativePath) != null);
+ }
+ assert properties != null;
+ for (Property property : properties) {
+ if (relativePath.equals(property.getName())) {
+ return true;
+ }
+ }
+ return false;
}
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Node#holdsLock()
*/
- public boolean holdsLock() {
- throw new UnsupportedOperationException();
+ public final boolean holdsLock() {
+ return false;
}
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Node#isCheckedOut()
*/
- public boolean isCheckedOut() {
- throw new UnsupportedOperationException();
+ public final boolean isCheckedOut() {
+ return false;
}
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Node#isLocked()
*/
- public boolean isLocked() {
- throw new UnsupportedOperationException();
+ public final boolean isLocked() {
+ return false;
}
/**
* {@inheritDoc}
*
+ * @return <code>true</code>
* @see javax.jcr.Item#isNode()
*/
public final boolean isNode() {
@@ -472,109 +613,137 @@
/**
* {@inheritDoc}
*
+ * @return <code>false</code>
* @see javax.jcr.Node#isNodeType(java.lang.String)
*/
public boolean isNodeType( String nodeTypeName ) {
- throw new UnsupportedOperationException();
+ return false;
}
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>otherItem</code> is <code>null</code>.
* @see javax.jcr.Item#isSame(javax.jcr.Item)
*/
- public boolean isSame( Item otherItem ) {
+ @Override
+ public final boolean isSame( Item otherItem ) throws RepositoryException {
+ ArgCheck.isNotNull(otherItem, "otherItem");
+ if (super.isSame(otherItem) && otherItem instanceof Node) {
+ if (otherItem instanceof AbstractJcrNode) {
+ return getInternalUuid().equals(((AbstractJcrNode)otherItem).getInternalUuid());
+ }
+ // If not our implementation, let the other item figure out whether we are the same.
+ return otherItem.isSame(this);
+ }
return false;
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#lock(boolean, boolean)
*/
- public Lock lock( boolean isDeep,
- boolean isSessionScoped ) {
- throw new UnsupportedOperationException();
+ public final Lock lock( boolean isDeep,
+ boolean isSessionScoped ) throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#merge(java.lang.String, boolean)
*/
- public NodeIterator merge( String srcWorkspace,
- boolean bestEffort ) {
+ public final NodeIterator merge( String srcWorkspace,
+ boolean bestEffort ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#orderBefore(java.lang.String, java.lang.String)
*/
- public void orderBefore( String srcChildRelPath,
- String destChildRelPath ) {
- throw new UnsupportedOperationException();
+ public final void orderBefore( String srcChildRelPath,
+ String destChildRelPath ) throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#removeMixin(java.lang.String)
*/
- public void removeMixin( String mixinName ) {
+ public final void removeMixin( String mixinName ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#restore(java.lang.String, boolean)
*/
- public void restore( String versionName,
- boolean removeExisting ) {
- throw new UnsupportedOperationException();
+ public final void restore( String versionName,
+ boolean removeExisting ) throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#restore(javax.jcr.version.Version, boolean)
*/
- public void restore( Version version,
- boolean removeExisting ) {
- throw new UnsupportedOperationException();
+ public final void restore( Version version,
+ boolean removeExisting ) throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#restore(javax.jcr.version.Version, java.lang.String, boolean)
*/
- public void restore( Version version,
- String relPath,
- boolean removeExisting ) {
- throw new UnsupportedOperationException();
+ public final void restore( Version version,
+ String relPath,
+ boolean removeExisting ) throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#restoreByLabel(java.lang.String, boolean)
*/
- public void restoreByLabel( String versionLabel,
- boolean removeExisting ) {
- throw new UnsupportedOperationException();
+ public final void restoreByLabel( String versionLabel,
+ boolean removeExisting ) throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
final void setChildren( List<Segment> children ) {
assert children != null;
+ if (this.children == null) {
+ this.children = new ArrayList<Name>(children.size());
+ childNameCounts = new ArrayList<Integer>(children.size());
+ }
for (Segment seg : children) {
Name name = seg.getName();
- Integer count = getChildCountsByName().get(name);
- if (count == null) getChildCountsByName().put(name, 1);
- else getChildCountsByName().put(name, count + 1);
+ int ndx = this.children.indexOf(name);
+ if (ndx >= 0) {
+ childNameCounts.set(ndx, childNameCounts.get(ndx) + 1);
+ } else {
+ this.children.add(name);
+ childNameCounts.add(1);
+ }
}
+ assert this.children.size() == childNameCounts.size();
}
final void setInternalUuid( UUID uuid ) {
@@ -590,162 +759,178 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, boolean)
*/
- public Property setProperty( String name,
- boolean value ) {
+ public final Property setProperty( String name,
+ boolean value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, java.util.Calendar)
*/
- public Property setProperty( String name,
- Calendar value ) {
+ public final Property setProperty( String name,
+ Calendar value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, double)
*/
- public Property setProperty( String name,
- double value ) {
+ public final Property setProperty( String name,
+ double value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, java.io.InputStream)
*/
- public Property setProperty( String name,
- InputStream value ) {
+ public final Property setProperty( String name,
+ InputStream value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, long)
*/
- public Property setProperty( String name,
- long value ) {
+ public final Property setProperty( String name,
+ long value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, javax.jcr.Node)
*/
- public Property setProperty( String name,
- Node value ) {
+ public final Property setProperty( String name,
+ Node value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, java.lang.String)
*/
- public Property setProperty( String name,
- String value ) {
+ public final Property setProperty( String name,
+ String value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, java.lang.String, int)
*/
- public Property setProperty( String name,
- String value,
- int type ) {
+ public final Property setProperty( String name,
+ String value,
+ int type ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, java.lang.String[])
*/
- public Property setProperty( String name,
- String[] values ) {
+ public final Property setProperty( String name,
+ String[] values ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, java.lang.String[], int)
*/
- public Property setProperty( String name,
- String[] values,
- int type ) {
+ public final Property setProperty( String name,
+ String[] values,
+ int type ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, javax.jcr.Value)
*/
- public Property setProperty( String name,
- Value value ) {
+ public final Property setProperty( String name,
+ Value value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, javax.jcr.Value, int)
*/
- public Property setProperty( String name,
- Value value,
- int type ) {
+ public final Property setProperty( String name,
+ Value value,
+ int type ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, javax.jcr.Value[])
*/
- public Property setProperty( String name,
- Value[] values ) {
+ public final Property setProperty( String name,
+ Value[] values ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#setProperty(java.lang.String, javax.jcr.Value[], int)
*/
- public Property setProperty( String name,
- Value[] values,
- int type ) {
+ public final Property setProperty( String name,
+ Value[] values,
+ int type ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedRepositoryOperationException always
* @see javax.jcr.Node#unlock()
*/
- public void unlock() {
- throw new UnsupportedOperationException();
+ public final void unlock() throws UnsupportedRepositoryOperationException {
+ throw new UnsupportedRepositoryOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Node#update(java.lang.String)
*/
- public void update( String srcWorkspaceName ) {
+ public final void update( String srcWorkspaceName ) {
throw new UnsupportedOperationException();
}
}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrProperty.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrProperty.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/AbstractJcrProperty.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -22,18 +22,25 @@
package org.jboss.dna.jcr;
import java.io.InputStream;
+import java.io.Reader;
import java.util.Calendar;
+import java.util.Date;
+import java.util.UUID;
import javax.jcr.Item;
import javax.jcr.ItemVisitor;
import javax.jcr.Node;
import javax.jcr.Property;
+import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.nodetype.PropertyDefinition;
import net.jcip.annotations.NotThreadSafe;
+import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.Path;
+import org.jboss.dna.spi.graph.ValueFactories;
/**
* @author jverhaeg
@@ -59,12 +66,27 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>visitor</code> is <code>null</code>.
* @see javax.jcr.Item#accept(javax.jcr.ItemVisitor)
*/
- public void accept( ItemVisitor visitor ) throws RepositoryException {
+ public final void accept( ItemVisitor visitor ) throws RepositoryException {
+ ArgCheck.isNotNull(visitor, "visitor");
visitor.visit(this);
}
+ JcrValue<?> createValue( ValueFactories valueFactories,
+ ValueInfo valueInfo,
+ Object value ) {
+ return createValue(valueFactories, valueInfo.valueClass, valueInfo.propertyType, value);
+ }
+
+ private <T> JcrValue<T> createValue( ValueFactories valueFactories,
+ Class<T> valueClass,
+ int propertyType,
+ Object value ) {
+ return new JcrValue<T>(valueFactories, propertyType, valueClass.cast(value));
+ }
+
/**
* {@inheritDoc}
*
@@ -78,12 +100,22 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#getDefinition()
*/
public PropertyDefinition getDefinition() {
throw new UnsupportedOperationException();
}
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Item#getDepth()
+ */
+ public int getDepth() throws RepositoryException {
+ return getParent().getDepth() + 1;
+ }
+
final ExecutionContext getExecutionContext() {
return executionContext;
}
@@ -93,7 +125,7 @@
*
* @see javax.jcr.Property#getNode()
*/
- final public Node getNode() {
+ public final Node getNode() {
return node;
}
@@ -120,8 +152,8 @@
*
* @see javax.jcr.Item#getPath()
*/
- public String getPath() throws RepositoryException {
- return node.getPath() + '/' + getName();
+ public final String getPath() throws RepositoryException {
+ return getPath(node.getPath(), getName());
}
/**
@@ -136,6 +168,7 @@
/**
* {@inheritDoc}
*
+ * @return false
* @see javax.jcr.Item#isNode()
*/
public final boolean isNode() {
@@ -147,8 +180,9 @@
*
* @see javax.jcr.Item#isSame(javax.jcr.Item)
*/
- public boolean isSame( Item otherItem ) throws RepositoryException {
- if (otherItem instanceof Property) {
+ @Override
+ public final boolean isSame( Item otherItem ) throws RepositoryException {
+ if (super.isSame(otherItem) && otherItem instanceof Property) {
Property otherProp = (Property)otherItem;
return (getName().equals(otherProp.getName()) && getNode().isSame(otherProp.getNode()));
}
@@ -158,90 +192,152 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(javax.jcr.Value)
*/
- public void setValue( Value value ) {
+ public final void setValue( Value value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(javax.jcr.Value[])
*/
- public void setValue( Value[] values ) {
+ public final void setValue( Value[] values ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(java.lang.String)
*/
- public void setValue( String value ) {
+ public final void setValue( String value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(java.lang.String[])
*/
- public void setValue( String[] values ) {
+ public final void setValue( String[] values ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(java.io.InputStream)
*/
- public void setValue( InputStream value ) {
+ public final void setValue( InputStream value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(long)
*/
- public void setValue( long value ) {
+ public final void setValue( long value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(double)
*/
- public void setValue( double value ) {
+ public final void setValue( double value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(java.util.Calendar)
*/
- public void setValue( Calendar value ) {
+ public final void setValue( Calendar value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(boolean)
*/
- public void setValue( boolean value ) {
+ public final void setValue( boolean value ) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Property#setValue(javax.jcr.Node)
*/
- public void setValue( Node value ) {
+ public final void setValue( Node value ) {
throw new UnsupportedOperationException();
}
+
+ final class ValueInfo {
+
+ final Class<?> valueClass;
+ final int propertyType;
+
+ ValueInfo( Object value ) {
+ if (value instanceof Boolean) {
+ valueClass = Boolean.class;
+ propertyType = PropertyType.BOOLEAN;
+ } else if (value instanceof Date) {
+ valueClass = Date.class;
+ propertyType = PropertyType.DATE;
+ } else if (value instanceof Calendar) {
+ valueClass = Calendar.class;
+ propertyType = PropertyType.DATE;
+ } else if (value instanceof Double) {
+ valueClass = Double.class;
+ propertyType = PropertyType.DOUBLE;
+ } else if (value instanceof Float) {
+ valueClass = Float.class;
+ propertyType = PropertyType.DOUBLE;
+ } else if (value instanceof Integer) {
+ valueClass = Integer.class;
+ propertyType = PropertyType.LONG;
+ } else if (value instanceof Long) {
+ valueClass = Long.class;
+ propertyType = PropertyType.LONG;
+ } else if (value instanceof UUID) {
+ valueClass = UUID.class;
+ propertyType = PropertyType.REFERENCE;
+ } else if (value instanceof String) {
+ valueClass = String.class;
+ propertyType = PropertyType.STRING;
+ } else if (value instanceof Name) {
+ valueClass = Name.class;
+ propertyType = PropertyType.NAME;
+ } else if (value instanceof Path) {
+ valueClass = Path.class;
+ propertyType = PropertyType.PATH;
+ } else if (value instanceof InputStream) {
+ valueClass = InputStream.class;
+ propertyType = PropertyType.BINARY;
+ } else if (value instanceof Reader) {
+ valueClass = Reader.class;
+ propertyType = PropertyType.BINARY;
+ } else {
+ valueClass = Object.class;
+ propertyType = PropertyType.BINARY;
+ }
+ }
+ }
}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrI18n.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -37,6 +37,7 @@
public static I18n inputStreamConsumed;
public static I18n nonInputStreamConsumed;
public static I18n pathNotFound;
+ public static I18n permissionDenied;
public static I18n repositoryMustBeConfigured;
public static I18n sourceInUse;
Added: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrMultiValueProperty.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrMultiValueProperty.java (rev 0)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrMultiValueProperty.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -0,0 +1,173 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Iterator;
+import java.util.List;
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Value;
+import javax.jcr.ValueFormatException;
+import net.jcip.annotations.NotThreadSafe;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.ValueFactories;
+
+/**
+ * @author jverhaeg
+ */
+@NotThreadSafe
+final class JcrMultiValueProperty extends AbstractJcrProperty {
+
+ private List<JcrValue<?>> jcrValues = new ArrayList<JcrValue<?>>();
+
+ JcrMultiValueProperty( Node node,
+ ExecutionContext executionContext,
+ Name name,
+ Iterable<?> values ) {
+ super(node, executionContext, name);
+ assert values != null;
+ ValueFactories valueFactories = executionContext.getValueFactories();
+ ValueInfo valueInfo = null;
+ for (Object value : values) {
+ if (valueInfo == null) {
+ valueInfo = new ValueInfo(value);
+ }
+ jcrValues.add(createValue(valueFactories, valueInfo, value));
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getBoolean()
+ */
+ public boolean getBoolean() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getDate()
+ */
+ public Calendar getDate() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getDouble()
+ */
+ public double getDouble() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getLength()
+ */
+ public long getLength() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Property#getLengths()
+ */
+ public long[] getLengths() throws RepositoryException {
+ long[] lengths = new long[jcrValues.size()];
+ Iterator<JcrValue<?>> iter = jcrValues.iterator();
+ for (int ndx = 0; iter.hasNext(); ndx++) {
+ lengths[ndx] = iter.next().getLength();
+ }
+ return lengths;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getLong()
+ */
+ public long getLong() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getStream()
+ */
+ public InputStream getStream() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getString()
+ */
+ public String getString() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Property#getType()
+ */
+ public int getType() {
+ return jcrValues.get(0).getType();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @throws ValueFormatException always
+ * @see javax.jcr.Property#getValue()
+ */
+ public Value getValue() throws ValueFormatException {
+ throw new ValueFormatException();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @see javax.jcr.Property#getValues()
+ */
+ public Value[] getValues() {
+ return jcrValues.toArray(new Value[jcrValues.size()]);
+ }
+}
Property changes on: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrMultiValueProperty.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNode.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNode.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrNode.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -23,11 +23,10 @@
import java.util.UUID;
import javax.jcr.Node;
-import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import net.jcip.annotations.NotThreadSafe;
-import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.Path.Segment;
/**
* @author jverhaeg
@@ -36,16 +35,16 @@
final class JcrNode extends AbstractJcrNode {
private final UUID parentUuid;
- private final Name name;
+ private final Segment segment;
JcrNode( Session session,
UUID parentUuid,
- Name name ) {
+ Segment segment ) {
super(session);
assert parentUuid != null;
- assert name != null;
+ assert segment != null;
this.parentUuid = parentUuid;
- this.name = name;
+ this.segment = segment;
}
/**
@@ -60,10 +59,19 @@
/**
* {@inheritDoc}
*
+ * @see javax.jcr.Node#getIndex()
+ */
+ public int getIndex() {
+ return segment.getIndex();
+ }
+
+ /**
+ * {@inheritDoc}
+ *
* @see javax.jcr.Item#getName()
*/
public String getName() {
- return name.getString();
+ return segment.getName().getString();
}
/**
@@ -89,10 +97,10 @@
}
String name = getName();
builder.append(name);
- NodeIterator iter = parent.getNodes(name);
- if (iter.getSize() > 1) {
+ int ndx = getIndex();
+ if (ndx > 1) {
builder.append('[');
- builder.append(getIndex());
+ builder.append(ndx);
builder.append(']');
}
return builder.toString();
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrProperty.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrProperty.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrProperty.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -22,18 +22,13 @@
package org.jboss.dna.jcr;
import java.io.InputStream;
-import java.io.Reader;
import java.util.Calendar;
-import java.util.Date;
-import java.util.UUID;
import javax.jcr.Node;
-import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFormatException;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.graph.Name;
-import org.jboss.dna.spi.graph.Path;
import org.jboss.dna.spi.graph.ValueFactories;
/**
@@ -50,35 +45,7 @@
super(node, executionContext, name);
assert value != null;
ValueFactories valueFactories = executionContext.getValueFactories();
- if (value instanceof Boolean) {
- jcrValue = new JcrValue<Boolean>(valueFactories, PropertyType.BOOLEAN, (Boolean)value);
- } else if (value instanceof Date) {
- jcrValue = new JcrValue<Date>(valueFactories, PropertyType.DATE, (Date)value);
- } else if (value instanceof Calendar) {
- jcrValue = new JcrValue<Calendar>(valueFactories, PropertyType.DATE, (Calendar)value);
- } else if (value instanceof Double) {
- jcrValue = new JcrValue<Double>(valueFactories, PropertyType.DOUBLE, (Double)value);
- } else if (value instanceof Float) {
- jcrValue = new JcrValue<Float>(valueFactories, PropertyType.DOUBLE, (Float)value);
- } else if (value instanceof Integer) {
- jcrValue = new JcrValue<Integer>(valueFactories, PropertyType.LONG, (Integer)value);
- } else if (value instanceof Long) {
- jcrValue = new JcrValue<Long>(valueFactories, PropertyType.LONG, (Long)value);
- } else if (value instanceof UUID) {
- jcrValue = new JcrValue<UUID>(valueFactories, PropertyType.REFERENCE, (UUID)value);
- } else if (value instanceof String) {
- jcrValue = new JcrValue<String>(valueFactories, PropertyType.STRING, (String)value);
- } else if (value instanceof Name) {
- jcrValue = new JcrValue<Name>(valueFactories, PropertyType.NAME, (Name)value);
- } else if (value instanceof Path) {
- jcrValue = new JcrValue<Path>(valueFactories, PropertyType.PATH, (Path)value);
- } else if (value instanceof InputStream) {
- jcrValue = new JcrValue<InputStream>(valueFactories, PropertyType.BINARY, (InputStream)value);
- } else if (value instanceof Reader) {
- jcrValue = new JcrValue<Reader>(valueFactories, PropertyType.BINARY, (Reader)value);
- } else {
- jcrValue = new JcrValue<Object>(getExecutionContext().getValueFactories(), PropertyType.BINARY, value);
- }
+ jcrValue = createValue(valueFactories, new ValueInfo(value), value);
}
/**
@@ -102,15 +69,6 @@
/**
* {@inheritDoc}
*
- * @see javax.jcr.Item#getDepth()
- */
- public int getDepth() throws RepositoryException {
- return getParent().getDepth() + 1;
- }
-
- /**
- * {@inheritDoc}
- *
* @see javax.jcr.Property#getDouble()
*/
public double getDouble() throws RepositoryException {
@@ -129,6 +87,7 @@
/**
* {@inheritDoc}
*
+ * @throws ValueFormatException always
* @see javax.jcr.Property#getLengths()
*/
public long[] getLengths() throws ValueFormatException {
@@ -183,65 +142,67 @@
/**
* {@inheritDoc}
*
+ * @throws ValueFormatException always
* @see javax.jcr.Property#getValues()
*/
public Value[] getValues() throws ValueFormatException {
throw new ValueFormatException();
}
- //
- // /**
- // * {@inheritDoc}
- // *
- // * @throws IllegalArgumentException if <code>value</code> is <code>null</code>.
- // * @see javax.jcr.Property#setValue(javax.jcr.Value)
- // */
- // @SuppressWarnings( "fallthrough" )
- // public void setValue( Value value ) throws RepositoryException {
- // ArgCheck.isNotNull(value, "value");
- // // TODOx: Check node type constraint
- // try {
- // jcrValue = JcrValue.class.cast(value);
- // } catch (ClassCastException error) {
- // // TODOx: not sure if this is even possible
- // ValueFactories valueFactories = getExecutionContext().getValueFactories();
- // int type = value.getType();
- // switch (type) {
- // case PropertyType.BINARY: {
- // jcrValue = new JcrValue<InputStream>(valueFactories, type, value.getStream());
- // break;
- // }
- // case PropertyType.BOOLEAN: {
- // jcrValue = new JcrValue<Boolean>(valueFactories, type, value.getBoolean());
- // break;
- // }
- // case PropertyType.DATE: {
- // jcrValue = new JcrValue<Calendar>(valueFactories, type, value.getDate());
- // break;
- // }
- // case PropertyType.DOUBLE: {
- // jcrValue = new JcrValue<Double>(valueFactories, type, value.getDouble());
- // break;
- // }
- // case PropertyType.LONG: {
- // jcrValue = new JcrValue<Long>(valueFactories, type, value.getLong());
- // break;
- // }
- // case PropertyType.REFERENCE: {
- // try {
- // jcrValue = new JcrValue<UUID>(valueFactories, type, UUID.fromString(value.getString()));
- // } catch (IllegalArgumentException fallsThroughToString) {
- // }
- // }
- // case PropertyType.NAME:
- // case PropertyType.PATH:
- // case PropertyType.STRING: {
- // jcrValue = new JcrValue<String>(valueFactories, type, value.getString());
- // break;
- // }
- // default: {
- // throw new AssertionError("Unsupported PropertyType: " + value.getType());
- // }
- // }
- // }
- // }
+
+ /*
+ * {@inheritDoc}
+ *
+ * @throws IllegalArgumentException if <code>value</code> is <code>null</code>.
+ * @see javax.jcr.Property#setValue(javax.jcr.Value)
+ *
+ @SuppressWarnings( "fallthrough" )
+ public void setValue( Value value ) throws RepositoryException {
+ ArgCheck.isNotNull(value, "value");
+ // TODOx: Check node type constraint
+ try {
+ jcrValue = JcrValue.class.cast(value);
+ } catch (ClassCastException error) {
+ // TODOx: not sure if this is even possible
+ ValueFactories valueFactories = getExecutionContext().getValueFactories();
+ int type = value.getType();
+ switch (type) {
+ case PropertyType.BINARY: {
+ jcrValue = new JcrValue<InputStream>(valueFactories, type, value.getStream());
+ break;
+ }
+ case PropertyType.BOOLEAN: {
+ jcrValue = new JcrValue<Boolean>(valueFactories, type, value.getBoolean());
+ break;
+ }
+ case PropertyType.DATE: {
+ jcrValue = new JcrValue<Calendar>(valueFactories, type, value.getDate());
+ break;
+ }
+ case PropertyType.DOUBLE: {
+ jcrValue = new JcrValue<Double>(valueFactories, type, value.getDouble());
+ break;
+ }
+ case PropertyType.LONG: {
+ jcrValue = new JcrValue<Long>(valueFactories, type, value.getLong());
+ break;
+ }
+ case PropertyType.REFERENCE: {
+ try {
+ jcrValue = new JcrValue<UUID>(valueFactories, type, UUID.fromString(value.getString()));
+ } catch (IllegalArgumentException fallsThroughToString) {
+ }
+ }
+ case PropertyType.NAME:
+ case PropertyType.PATH:
+ case PropertyType.STRING: {
+ jcrValue = new JcrValue<String>(valueFactories, type, value.getString());
+ break;
+ }
+ default: {
+ throw new AssertionError("Unsupported PropertyType: " + value.getType());
+ }
+ }
+ }
+ }
+ */
}
Deleted: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrPropertyIterator.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -1,114 +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.jcr;
-
-import java.util.Iterator;
-import java.util.Set;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import net.jcip.annotations.NotThreadSafe;
-import org.jboss.dna.common.util.ArgCheck;
-
-/**
- * @author jverhaeg
- */
-@NotThreadSafe
-class JcrPropertyIterator implements PropertyIterator {
-
- private final Set<Property> properties;
- private final Iterator<Property> iterator;
- private long index = 0L;
-
- JcrPropertyIterator( Set<Property> properties ) {
- assert properties != null;
- this.properties = properties;
- iterator = properties.iterator();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.PropertyIterator#nextProperty()
- */
- public Property nextProperty() {
- Property property = iterator.next();
- index++;
- return property;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.RangeIterator#getPosition()
- */
- public long getPosition() {
- return index;
- }
-
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.RangeIterator#getSize()
- */
- public long getSize() {
- return properties.size();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see javax.jcr.RangeIterator#skip(long)
- */
- public void skip( long count ) {
- ArgCheck.isNonNegative(count, "count");
- while (--count >= 0) {
- iterator.next();
- }
- }
-
- /**
- * {@inheritDoc}
- *
- * @see java.util.Iterator#hasNext()
- */
- public boolean hasNext() {
- return iterator.hasNext();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see java.util.Iterator#next()
- */
- public Object next() {
- return nextProperty();
- }
-
- /**
- * {@inheritDoc}
- *
- * @see java.util.Iterator#remove()
- */
- public void remove() {
- iterator.remove();
- }
-}
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRepository.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -113,22 +113,15 @@
}
// Initialize required JCR descriptors.
modifiableDescriptors.put(Repository.LEVEL_1_SUPPORTED, "true");
- // TODO: Change to true once level 2 supported
modifiableDescriptors.put(Repository.LEVEL_2_SUPPORTED, "false");
- // TODO: Change to true once locking supported
modifiableDescriptors.put(Repository.OPTION_LOCKING_SUPPORTED, "false");
- // TODO: Change to true once observation supported
modifiableDescriptors.put(Repository.OPTION_OBSERVATION_SUPPORTED, "false");
- // TODO: Change to true once query SQL supported
modifiableDescriptors.put(Repository.OPTION_QUERY_SQL_SUPPORTED, "false");
- // TODO: Change to true once transactions supported
modifiableDescriptors.put(Repository.OPTION_TRANSACTIONS_SUPPORTED, "false");
- // TODO: Change to true once versioning supported
modifiableDescriptors.put(Repository.OPTION_VERSIONING_SUPPORTED, "false");
modifiableDescriptors.put(Repository.QUERY_XPATH_DOC_ORDER, "true");
modifiableDescriptors.put(Repository.QUERY_XPATH_POS_INDEX, "true");
// Vendor-specific descriptors (REP_XXX) will only be initialized if not already present, allowing for customer branding.
- // TODO: Should allow for branding via configuration
if (!modifiableDescriptors.containsKey(Repository.REP_NAME_DESC)) {
modifiableDescriptors.put(Repository.REP_NAME_DESC, JcrI18n.REP_NAME_DESC.text());
}
@@ -139,7 +132,6 @@
modifiableDescriptors.put(Repository.REP_VENDOR_URL_DESC, "http://www.jboss.org/dna");
}
if (!modifiableDescriptors.containsKey(Repository.REP_VERSION_DESC)) {
- // TODO: Permanent to-do to update the version for each release
modifiableDescriptors.put(Repository.REP_VERSION_DESC, "0.2");
}
modifiableDescriptors.put(Repository.SPEC_NAME_DESC, JcrI18n.SPEC_NAME_DESC.text());
@@ -150,9 +142,11 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>key</code> is <code>null</code>.
* @see javax.jcr.Repository#getDescriptor(java.lang.String)
*/
public String getDescriptor( String key ) {
+ ArgCheck.isNotEmpty(key, "key");
return descriptors.get(key);
}
@@ -195,6 +189,16 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>credentials</code> is not <code>null</code> but:
+ * <ul>
+ * <li>provides neither a <code>getLoginContext()</code> nor a <code>getAccessControlContext()</code> method.</li>
+ * <li>provides a <code>getLoginContext()</code> method that doesn't return a {@link LoginContext}.
+ * <li>provides a <code>getLoginContext()</code> method that returns a <code>null</code> {@link LoginContext}.
+ * <li>does not provide a <code>getLoginContext()</code> method, but provides a <code>getAccessControlContext()</code>
+ * method that doesn't return an {@link AccessControlContext}.
+ * <li>does not provide a <code>getLoginContext()</code> method, but provides a <code>getAccessControlContext()</code>
+ * method that returns a <code>null</code> {@link AccessControlContext}.
+ * </ul>
* @see javax.jcr.Repository#login(javax.jcr.Credentials, java.lang.String)
*/
public synchronized Session login( Credentials credentials,
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRootNode.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRootNode.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrRootNode.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -39,6 +39,7 @@
/**
* {@inheritDoc}
*
+ * @return 0;
* @see javax.jcr.Item#getDepth()
*/
public int getDepth() {
@@ -48,6 +49,17 @@
/**
* {@inheritDoc}
*
+ * @return 1;
+ * @see javax.jcr.Node#getIndex()
+ */
+ public int getIndex() {
+ return 1;
+ }
+
+ /**
+ * {@inheritDoc}
+ *
+ * @return "";
* @see javax.jcr.Item#getName()
*/
public String getName() {
@@ -57,6 +69,7 @@
/**
* {@inheritDoc}
*
+ * @throws ItemNotFoundException always
* @see javax.jcr.Item#getParent()
*/
public Node getParent() throws ItemNotFoundException {
@@ -66,6 +79,7 @@
/**
* {@inheritDoc}
*
+ * @return "/";
* @see javax.jcr.Item#getPath()
*/
public String getPath() {
Modified: trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java
===================================================================
--- trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/java/org/jboss/dna/jcr/JcrSession.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -24,19 +24,24 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
+import java.security.AccessControlException;
import java.security.Principal;
+import java.util.Calendar;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
+import java.util.WeakHashMap;
import javax.jcr.Credentials;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
+import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.security.auth.Subject;
@@ -50,6 +55,7 @@
import org.jboss.dna.spi.graph.Name;
import org.jboss.dna.spi.graph.Path;
import org.jboss.dna.spi.graph.UuidFactory;
+import org.jboss.dna.spi.graph.ValueFactories;
import org.jboss.dna.spi.graph.Path.Segment;
import org.jboss.dna.spi.graph.commands.GraphCommand;
import org.jboss.dna.spi.graph.commands.impl.BasicGetNodeCommand;
@@ -66,6 +72,7 @@
private final ExecutionContext executionContext;
private RepositoryConnection connection;
private final Map<UUID, WeakReference<Node>> nodesByUuid;
+ private final Map<String, WeakReference<Node>> nodesByJcrUuid;
private boolean isLive;
private Workspace workspace;
private JcrRootNode rootNode;
@@ -84,6 +91,7 @@
this.executionContext = executionContext;
this.connection = connection;
this.nodesByUuid = nodesByUuid;
+ this.nodesByJcrUuid = new WeakHashMap<String, WeakReference<Node>>();
this.isLive = true;
// Following must be initialized after session's state is initialized
this.workspace = new JcrWorkspace(this, workspaceName);
@@ -92,6 +100,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#addLockToken(java.lang.String)
*/
public void addLockToken( String lt ) {
@@ -101,11 +110,16 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if either <code>path</code> or <code>actions</code> is empty or <code>null</code>.
* @see javax.jcr.Session#checkPermission(java.lang.String, java.lang.String)
*/
- public void checkPermission( String absPath,
+ public void checkPermission( String path,
String actions ) {
- throw new UnsupportedOperationException();
+ ArgCheck.isNotEmpty(path, "path");
+ ArgCheck.isNotEmpty(actions, "actions");
+ if (!"read".equals(actions)) {
+ throw new AccessControlException(JcrI18n.permissionDenied.text(path, actions));
+ }
}
private void execute( GraphCommand... commands ) throws RepositoryException {
@@ -121,6 +135,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#exportDocumentView(java.lang.String, org.xml.sax.ContentHandler, boolean, boolean)
*/
public void exportDocumentView( String absPath,
@@ -133,6 +148,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#exportDocumentView(java.lang.String, java.io.OutputStream, boolean, boolean)
*/
public void exportDocumentView( String absPath,
@@ -145,6 +161,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#exportSystemView(java.lang.String, org.xml.sax.ContentHandler, boolean, boolean)
*/
public void exportSystemView( String absPath,
@@ -157,6 +174,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#exportSystemView(java.lang.String, java.io.OutputStream, boolean, boolean)
*/
public void exportSystemView( String absPath,
@@ -169,6 +187,7 @@
/**
* {@inheritDoc}
*
+ * @return <code>null</code>
* @see javax.jcr.Session#getAttribute(java.lang.String)
*/
public Object getAttribute( String name ) {
@@ -178,6 +197,7 @@
/**
* {@inheritDoc}
*
+ * @return An empty array
* @see javax.jcr.Session#getAttributeNames()
*/
public String[] getAttributeNames() {
@@ -187,6 +207,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getImportContentHandler(java.lang.String, int)
*/
public ContentHandler getImportContentHandler( String parentAbsPath,
@@ -197,6 +218,7 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>absolutePath</code> is empty or <code>null</code>.
* @see javax.jcr.Session#getItem(java.lang.String)
*/
public Item getItem( String absolutePath ) throws RepositoryException {
@@ -230,6 +252,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getLockTokens()
*/
public String[] getLockTokens() {
@@ -239,6 +262,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNamespacePrefix(java.lang.String)
*/
public String getNamespacePrefix( String uri ) {
@@ -248,6 +272,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNamespacePrefixes()
*/
public String[] getNamespacePrefixes() {
@@ -257,6 +282,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNamespaceURI(java.lang.String)
*/
public String getNamespaceURI( String prefix ) {
@@ -283,9 +309,8 @@
// If not create a new one & populate it
JcrNode node;
Path parentPath = path.getParent();
- if (parentPath.isRoot()) node = new JcrNode(this, ((JcrRootNode)getRootNode()).getInternalUuid(),
- path.getLastSegment().getName());
- else node = new JcrNode(this, ((JcrNode)getNode(parentPath)).getInternalUuid(), path.getLastSegment().getName());
+ if (parentPath.isRoot()) node = new JcrNode(this, ((JcrRootNode)getRootNode()).getInternalUuid(), path.getLastSegment());
+ else node = new JcrNode(this, ((JcrNode)getNode(parentPath)).getInternalUuid(), path.getLastSegment());
populateNode(node, command);
return node;
}
@@ -293,9 +318,11 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#getNodeByUUID(java.lang.String)
*/
public Node getNodeByUUID( String uuid ) {
+ // TODO: Need DNA command to get node by UUID before implementing
throw new UnsupportedOperationException();
}
@@ -349,7 +376,42 @@
* @see javax.jcr.Session#getValueFactory()
*/
public ValueFactory getValueFactory() {
- throw new UnsupportedOperationException();
+ final ValueFactories valueFactories = executionContext.getValueFactories();
+ return new ValueFactory() {
+
+ public Value createValue( String value,
+ int propertyType ) {
+ return new JcrValue<String>(valueFactories, propertyType, value);
+ }
+
+ public Value createValue( Node value ) throws RepositoryException {
+ return new JcrValue<UUID>(valueFactories, PropertyType.REFERENCE, UUID.fromString(value.getUUID()));
+ }
+
+ public Value createValue( InputStream value ) {
+ return new JcrValue<InputStream>(valueFactories, PropertyType.BINARY, value);
+ }
+
+ public Value createValue( Calendar value ) {
+ return new JcrValue<Calendar>(valueFactories, PropertyType.DATE, value);
+ }
+
+ public Value createValue( boolean value ) {
+ return new JcrValue<Boolean>(valueFactories, PropertyType.BOOLEAN, value);
+ }
+
+ public Value createValue( double value ) {
+ return new JcrValue<Double>(valueFactories, PropertyType.DOUBLE, value);
+ }
+
+ public Value createValue( long value ) {
+ return new JcrValue<Long>(valueFactories, PropertyType.LONG, value);
+ }
+
+ public Value createValue( String value ) {
+ return new JcrValue<String>(valueFactories, PropertyType.STRING, value);
+ }
+ };
}
/**
@@ -364,10 +426,11 @@
/**
* {@inheritDoc}
*
+ * @return false
* @see javax.jcr.Session#hasPendingChanges()
*/
public boolean hasPendingChanges() {
- throw new UnsupportedOperationException();
+ return false;
}
/**
@@ -375,13 +438,14 @@
*
* @see javax.jcr.Session#impersonate(javax.jcr.Credentials)
*/
- public Session impersonate( Credentials credentials ) {
- throw new UnsupportedOperationException();
+ public Session impersonate( Credentials credentials ) throws RepositoryException {
+ return repository.login(credentials);
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#importXML(java.lang.String, java.io.InputStream, int)
*/
public void importXML( String parentAbsPath,
@@ -402,10 +466,11 @@
/**
* {@inheritDoc}
*
+ * @throws IllegalArgumentException if <code>absolutePath</code> is empty or <code>null</code>.
* @see javax.jcr.Session#itemExists(java.lang.String)
*/
- public boolean itemExists( String absPath ) {
- throw new UnsupportedOperationException();
+ public boolean itemExists( String absolutePath ) throws RepositoryException {
+ return (getItem(absolutePath) != null);
}
/**
@@ -426,12 +491,14 @@
executionContext.getLoginContext().logout();
isLive = false;
} catch (LoginException error) {
+ // TODO; Log error
}
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#move(java.lang.String, java.lang.String)
*/
public void move( String srcAbsPath,
@@ -454,22 +521,27 @@
for (org.jboss.dna.spi.graph.Property dnaProp : getNodeCommand.getProperties()) {
Name name = dnaProp.getName();
if (uuid == null && DnaLexicon.UUID.equals(name)) uuid = uuidFactory.create(dnaProp.getValues()).next();
+ else if (dnaProp.isMultiple()) properties.add(new JcrMultiValueProperty(node, executionContext, name, dnaProp));
else {
- if (jcrUuidName.equals(name)) uuid = uuidFactory.create(dnaProp.getValues()).next();
- properties.add(new JcrProperty(node, executionContext, name, dnaProp.getValues().next()));
+ if (jcrUuidName.equals(name)) {
+ uuid = uuidFactory.create(dnaProp.getValues()).next();
+ nodesByJcrUuid.put(uuid.toString(), new WeakReference<Node>(node));
+ } else properties.add(new JcrProperty(node, executionContext, name, dnaProp.getValues().next()));
}
+
}
node.setProperties(properties);
// Set node's UUID, creating one if necessary
if (uuid == null) uuid = UUID.randomUUID();
node.setInternalUuid(uuid);
// Setup node to be retrieved by DNA UUID
- nodesByUuid.put(node.getInternalUuid(), new WeakReference<Node>(node));
+ nodesByUuid.put(new UUID(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()), new WeakReference<Node>(node));
}
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#refresh(boolean)
*/
public void refresh( boolean keepChanges ) {
@@ -479,6 +551,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#removeLockToken(java.lang.String)
*/
public void removeLockToken( String lt ) {
@@ -488,6 +561,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#save()
*/
public void save() {
@@ -497,6 +571,7 @@
/**
* {@inheritDoc}
*
+ * @throws UnsupportedOperationException always
* @see javax.jcr.Session#setNamespacePrefix(java.lang.String, java.lang.String)
*/
public void setNamespacePrefix( String newPrefix,
Modified: trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties
===================================================================
--- trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/main/resources/org/jboss/dna/jcr/JcrI18n.properties 2008-09-09 15:18:27 UTC (rev 509)
@@ -27,6 +27,7 @@
inputStreamConsumed = This value was already consumed as an input stream.
nonInputStreamConsumed = This value was already consumed as a non-input stream.
pathNotFound = No item exists at path {0}
+permissionDenied = Permission denied to perform actions "{1}" on path {0}.
repositoryMustBeConfigured = DNA repositories must be configured with either a repository source factory or a repository source.
sourceInUse = All sessions must end before a new repository source can be set.
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrItemTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrItemTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrItemTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -71,10 +71,6 @@
public boolean isNode() {
return false;
}
-
- public boolean isSame( Item otherItem ) {
- return false;
- }
};
}
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrNodeTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -22,16 +22,32 @@
package org.jboss.dna.jcr;
import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.stub;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Calendar;
import java.util.HashSet;
+import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Item;
+import javax.jcr.ItemNotFoundException;
import javax.jcr.ItemVisitor;
import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
+import javax.jcr.PropertyIterator;
+import javax.jcr.RepositoryException;
import javax.jcr.Session;
+import javax.jcr.UnsupportedRepositoryOperationException;
+import javax.jcr.Value;
+import javax.jcr.Workspace;
+import javax.jcr.version.Version;
+import org.jboss.dna.spi.graph.Path.Segment;
+import org.jboss.dna.spi.graph.impl.BasicName;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -46,30 +62,15 @@
private AbstractJcrNode node;
@Mock
private Session session;
+ private List<Segment> children;
private Set<Property> properties;
@Before
- public void before() {
+ public void before() throws Exception {
MockitoAnnotations.initMocks(this);
+ children = new ArrayList<Segment>();
properties = new HashSet<Property>();
- node = new AbstractJcrNode(session) {
-
- public int getDepth() {
- return 0;
- }
-
- public String getName() {
- return null;
- }
-
- public Node getParent() {
- return null;
- }
-
- public String getPath() {
- return null;
- }
- };
+ node = new MockAbstractJcrNode(session, "node", null);
node.setProperties(properties);
}
@@ -80,26 +81,14 @@
Mockito.verify(visitor).visit(node);
}
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowVisitationIfNoVisitor() throws Exception {
+ node.accept(null);
+ }
+
@Test( expected = AssertionError.class )
public void shouldNotAllowNoSession() throws Exception {
- new AbstractJcrNode(null) {
-
- public int getDepth() {
- return 0;
- }
-
- public String getName() {
- return null;
- }
-
- public Node getParent() {
- return null;
- }
-
- public String getPath() {
- return null;
- }
- };
+ new MockAbstractJcrNode(null, null, null);
}
@Test( expected = IllegalArgumentException.class )
@@ -113,11 +102,6 @@
}
@Test
- public void shouldProvideSession() throws Exception {
- assertThat(node.getSession(), is(session));
- }
-
- @Test
public void shouldProvideInternalUuid() throws Exception {
UUID uuid = UUID.randomUUID();
node.setInternalUuid(uuid);
@@ -132,8 +116,563 @@
assertThat(node.getProperty("test"), is(property));
}
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowAddMixin() throws Exception {
+ node.addMixin(null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowAddNode() throws Exception {
+ node.addNode(null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowAddNodeWithType() throws Exception {
+ node.addNode(null, null);
+ }
+
@Test
- public void shouldBeANode() {
+ public void shoudNotAllowCanAddMixin() throws Exception {
+ assertThat(node.canAddMixin(null), is(false));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowCancelMerge() throws Exception {
+ node.cancelMerge(null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowCheckin() throws Exception {
+ node.checkin();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowCheckout() throws Exception {
+ node.checkout();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shoudNotAllowDoneMerge() throws Exception {
+ node.doneMerge(null);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shoudNotAllowGetBaseVersion() throws Exception {
+ node.getBaseVersion();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowGetCorrespondingNodePath() throws Exception {
+ node.getCorrespondingNodePath(null);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shoudNotAllowGetLock() throws Exception {
+ node.getLock();
+ }
+
+ @Test
+ public void shouldProvideNode() throws Exception {
+ Node child = createChild("child", 1, children, node);
+ node.setChildren(children);
+ stub(session.getItem("/node/child")).toReturn(child);
+ assertThat(node.getNode("child"), is(child));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowGetNodeWithNoPath() throws Exception {
+ node.getNode(null);
+ }
+
+ @Test( expected = PathNotFoundException.class )
+ public void shouldNotProvideNodeIfPathNotFound() throws Exception {
+ node.getNode("bogus");
+ }
+
+ @Test( expected = PathNotFoundException.class )
+ public void shouldNotProvideNodeIfPathIsProperty() throws Exception {
+ Property property = Mockito.mock(Property.class);
+ stub(session.getItem("/property")).toReturn(property);
+ node.getNode("property");
+ }
+
+ @Test
+ public void shouldProvideNodeIterator() throws Exception {
+ Node child1 = createChild("child1", 1, children, node);
+ Node child2_1 = createChild("child2", 1, children, node);
+ Node child2_2 = createChild("child2", 2, children, node);
+ createChild("child3", 1, children, node);
+ createChild("child4", 1, children, node);
+ Node child5 = createChild("child5", 1, children, node);
+ node.setChildren(children);
+ NodeIterator iter = node.getNodes();
+ assertThat(iter, notNullValue());
+ assertThat(iter.getSize(), is(-1L));
+ assertThat(iter.getPosition(), is(0L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat((Node)iter.next(), is(child1));
+ assertThat(iter.getPosition(), is(1L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextNode(), is(child2_1));
+ assertThat(iter.getPosition(), is(2L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextNode(), is(child2_2));
+ assertThat(iter.getPosition(), is(3L));
+ assertThat(iter.hasNext(), is(true));
+ iter.skip(2);
+ assertThat(iter.getPosition(), is(5L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextNode(), is(child5));
+ assertThat(iter.getPosition(), is(6L));
+ assertThat(iter.hasNext(), is(false));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowNodeIteratorRemove() throws Exception {
+ node.getNodes().remove();
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNodeIteratorNegativeSkip() throws Exception {
+ node.getNodes().skip(-1);
+ }
+
+ @Test
+ public void shoudProvidePrimaryItem() throws Exception {
+ Property property = Mockito.mock(Property.class);
+ stub(property.getName()).toReturn("jcr:primaryItemName");
+ stub(property.getString()).toReturn("primaryItem");
+ properties.add(property);
+ Item primaryItem = Mockito.mock(Item.class);
+ stub(session.getItem("/node/primaryItem")).toReturn(primaryItem);
+ assertThat(node.getPrimaryItem(), is(primaryItem));
+ }
+
+ @Test( expected = ItemNotFoundException.class )
+ public void shoudNotProvidePrimaryItemIfUnavailable() throws Exception {
+ node.getPrimaryItem();
+ }
+
+ @Test
+ public void shouldProvidePropertyIterator() throws Exception {
+ properties.add(Mockito.mock(Property.class));
+ properties.add(Mockito.mock(Property.class));
+ properties.add(Mockito.mock(Property.class));
+ properties.add(Mockito.mock(Property.class));
+ PropertyIterator iter = node.getProperties();
+ assertThat(iter, notNullValue());
+ assertThat(iter.getSize(), is(-1L));
+ assertThat(iter.getPosition(), is(0L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.next(), notNullValue());
+ assertThat(iter.getPosition(), is(1L));
+ assertThat(iter.hasNext(), is(true));
+ iter.skip(2);
+ assertThat(iter.getPosition(), is(3L));
+ assertThat(iter.hasNext(), is(true));
+ assertThat(iter.nextProperty(), notNullValue());
+ assertThat(iter.getPosition(), is(4L));
+ assertThat(iter.hasNext(), is(false));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowPropertyIteratorRemove() throws Exception {
+ node.getProperties().remove();
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowPropertyIteratorNegativeSkip() throws Exception {
+ node.getProperties().skip(-1);
+ }
+
+ @Test
+ public void shouldProvideProperty() throws Exception {
+ Property prop1 = Mockito.mock(Property.class);
+ stub(prop1.getName()).toReturn("prop1");
+ properties.add(prop1);
+ assertThat(node.getProperty("prop1"), is(prop1));
+ MockAbstractJcrNode child = createChild("child", 1, children, node);
+ Set<Property> properties = new HashSet<Property>();
+ child.setProperties(properties);
+ Property prop2 = Mockito.mock(Property.class);
+ stub(prop2.getName()).toReturn("prop2");
+ stub(session.getItem("/node/child/prop2")).toReturn(prop2);
+ properties.add(prop2);
+ MockAbstractJcrNode prop3Node = createChild("prop3", 1, children, child);
+ node.setChildren(children);
+ assertThat(node.getProperty("child/prop2"), is(prop2));
+ // Ensure we return a property even when a child exists with the same name
+ Property prop3 = Mockito.mock(Property.class);
+ stub(prop3.getName()).toReturn("prop3");
+ properties.add(prop3);
+ stub(session.getItem("/node/child/prop3")).toReturn(prop3Node);
+ assertThat(node.getProperty("child/prop3"), is(prop3));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowGetPropertyWithNullPath() throws Exception {
+ node.getProperty(null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowGetPropertyWithEmptyPath() throws Exception {
+ node.getProperty("");
+ }
+
+ @Test( expected = PathNotFoundException.class )
+ public void shouldNotProvideChildPropertyIfNotAvailable() throws Exception {
+ node.getProperty("prop1");
+ }
+
+ @Test( expected = PathNotFoundException.class )
+ public void shouldNotProvideDescendentPropertyIfNotAvailable() throws Exception {
+ MockAbstractJcrNode child = createChild("child", 1, children, node);
+ Set<Property> properties = new HashSet<Property>();
+ child.setProperties(properties);
+ MockAbstractJcrNode propNode = createChild("prop", 1, children, child);
+ node.setChildren(children);
+ stub(session.getItem("/node/child/prop")).toReturn(propNode);
+ node.getProperty("child/prop");
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowGetReferences() throws Exception {
+ node.getReferences();
+ }
+
+ @Test
+ public void shouldProvideSession() throws Exception {
+ assertThat(node.getSession(), is(session));
+ }
+
+ @Test
+ public void shouldProvideUuidIfReferenceable() throws Exception {
+ String uuid = "uuid";
+ Property mixinProp = Mockito.mock(Property.class);
+ stub(mixinProp.getName()).toReturn("jcr:mixinTypes");
+ Value value = Mockito.mock(Value.class);
+ stub(value.getString()).toReturn("mix:referenceable");
+ stub(mixinProp.getValues()).toReturn(new Value[] {value});
+ properties.add(mixinProp);
+ Property uuidProp = Mockito.mock(Property.class);
+ stub(uuidProp.getName()).toReturn("jcr:uuid");
+ stub(uuidProp.getString()).toReturn(uuid);
+ properties.add(uuidProp);
+ assertThat(node.getUUID(), is(uuid));
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotProvideUuidIfNotReferenceable() throws Exception {
+ String uuid = "uuid";
+ Property mixinProp = Mockito.mock(Property.class);
+ stub(mixinProp.getName()).toReturn("jcr:mixinTypes");
+ Value value = Mockito.mock(Value.class);
+ stub(mixinProp.getValues()).toReturn(new Value[] {value});
+ properties.add(mixinProp);
+ Property uuidProp = Mockito.mock(Property.class);
+ stub(uuidProp.getName()).toReturn("jcr:uuid");
+ stub(uuidProp.getString()).toReturn(uuid);
+ properties.add(uuidProp);
+ node.getUUID();
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotProvideUuidIfNoMixinTypes() throws Exception {
+ String uuid = "uuid";
+ Property uuidProp = Mockito.mock(Property.class);
+ stub(uuidProp.getName()).toReturn("jcr:uuid");
+ stub(uuidProp.getString()).toReturn(uuid);
+ properties.add(uuidProp);
+ node.getUUID();
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowGetVersionHistory() throws Exception {
+ node.getVersionHistory();
+ }
+
+ @Test
+ public void shouldProvideHasNode() throws Exception {
+ assertThat(node.hasNode("{}child"), is(false));
+ Property prop = Mockito.mock(Property.class);
+ stub(prop.getName()).toReturn("prop");
+ properties.add(prop);
+ assertThat(node.hasNode("prop"), is(false));
+ Node child = createChild("child", 1, children, node);
+ Node child2 = createChild("child2", 1, children, child);
+ node.setChildren(children);
+ assertThat(node.hasNode("{}child"), is(true));
+ stub(session.getItem("/node/child/{}child2")).toReturn(child2);
+ assertThat(node.hasNode("child/{}child2"), is(true));
+ }
+
+ @Test
+ public void shouldNotIndicateHasNodeIfPathIsChildProperty() throws Exception {
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowHasNodeWithNoPath() throws Exception {
+ node.hasNode(null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowHasNodeWithEmptyPath() throws Exception {
+ node.hasNode("");
+ }
+
+ @Test
+ public void shouldProvideHasNodes() throws Exception {
+ assertThat(node.hasNodes(), is(false));
+ createChild("child", 1, children, node);
+ node.setChildren(children);
+ assertThat(node.hasNodes(), is(true));
+ }
+
+ @Test
+ public void shouldProvideHasProperties() throws Exception {
+ assertThat(node.hasProperties(), is(false));
+ properties.add(Mockito.mock(Property.class));
+ assertThat(node.hasProperties(), is(true));
+ }
+
+ @Test
+ public void shouldIndicateHasProperty() throws Exception {
+ assertThat(node.hasProperty("prop"), is(false));
+ MockAbstractJcrNode child = createChild("child", 1, children, node);
+ node.setChildren(children);
+ assertThat(node.hasProperty("child"), is(false));
+ Property prop = Mockito.mock(Property.class);
+ stub(prop.getName()).toReturn("prop");
+ properties.add(prop);
+ assertThat(node.hasProperty("prop"), is(true));
+ Set<Property> properties = new HashSet<Property>();
+ child.setProperties(properties);
+ Property prop2 = Mockito.mock(Property.class);
+ stub(prop2.getName()).toReturn("prop2");
+ properties.add(prop2);
+ stub(session.getItem("/node/child/prop2")).toReturn(prop2);
+ assertThat(node.hasProperty("child/prop2"), is(true));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowHasPropertyWithNoPath() throws Exception {
+ node.hasProperty(null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowHasPropertyWithEmptyPath() throws Exception {
+ node.hasProperty("");
+ }
+
+ @Test
+ public void shouldNotAllowHoldsLock() throws Exception {
+ assertThat(node.holdsLock(), is(false));
+ }
+
+ @Test
+ public void shouldNotAllowIsCheckedOut() throws Exception {
+ assertThat(node.isCheckedOut(), is(false));
+ }
+
+ @Test
+ public void shouldNotAllowIsLocked() throws Exception {
+ assertThat(node.isLocked(), is(false));
+ }
+
+ @Test
+ public void shouldIndicateIsNode() {
assertThat(node.isNode(), is(true));
}
+
+ @Test
+ public void shouldProvideIsSame() throws Exception {
+ stub(session.getWorkspace()).toReturn(Mockito.mock(Workspace.class));
+ Session session2 = Mockito.mock(Session.class);
+ Node node2 = new MockAbstractJcrNode(session2, node.getName(), node.getParent());
+ assertThat(node.isSame(node2), is(false));
+ Property prop = Mockito.mock(Property.class);
+ stub(prop.getSession()).toReturn(session);
+ assertThat(node.isSame(prop), is(false));
+ node2 = Mockito.mock(Node.class);
+ stub(node2.getSession()).toReturn(session);
+ assertThat(node.isSame(node2), is(false));
+ node2 = new MockAbstractJcrNode(session, node.getName(), node.getParent());
+ UUID uuid = UUID.randomUUID();
+ node.setInternalUuid(uuid);
+ ((MockAbstractJcrNode)node2).setInternalUuid(UUID.randomUUID());
+ assertThat(node.isSame(node2), is(false));
+ ((MockAbstractJcrNode)node2).setInternalUuid(uuid);
+ assertThat(node.isSame(node2), is(true));
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowIsSameWithNoItem() throws Exception {
+ node.isSame(null);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowLock() throws Exception {
+ node.lock(false, false);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowMerge() throws Exception {
+ node.merge(null, false);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowOrderBefore() throws Exception {
+ node.orderBefore(null, null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowRemoveMixin() throws Exception {
+ node.removeMixin(null);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowRestoreVersionName() throws Exception {
+ node.restore((String)null, false);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowRestoreVersion() throws Exception {
+ node.restore((Version)null, false);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowRestoreVersionAtPath() throws Exception {
+ node.restore(null, null, false);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowRestoreByLabel() throws Exception {
+ node.restoreByLabel(null, false);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetBooleanProperty() throws Exception {
+ node.setProperty(null, false);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetCalendarProperty() throws Exception {
+ node.setProperty(null, (Calendar)null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetDoubleProperty() throws Exception {
+ node.setProperty(null, 0.0);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetInputStreamProperty() throws Exception {
+ node.setProperty(null, (InputStream)null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetLongProperty() throws Exception {
+ node.setProperty(null, 0L);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetNodeProperty() throws Exception {
+ node.setProperty(null, (Node)null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetStringProperty() throws Exception {
+ node.setProperty(null, (String)null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetStringsProperty() throws Exception {
+ node.setProperty(null, (String[])null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetValueProperty() throws Exception {
+ node.setProperty(null, (Value)null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetValuesProperty() throws Exception {
+ node.setProperty(null, (Value[])null);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetStringPropertyWithType() throws Exception {
+ node.setProperty(null, (String)null, 0);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetStringsPropertyWithType() throws Exception {
+ node.setProperty(null, (String[])null, 0);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetValuePropertyWithType() throws Exception {
+ node.setProperty(null, (Value)null, 0);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetValuesPropertyWithType() throws Exception {
+ node.setProperty(null, (Value[])null, 0);
+ }
+
+ @Test( expected = UnsupportedRepositoryOperationException.class )
+ public void shouldNotAllowUnlock() throws Exception {
+ node.unlock();
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowUpdate() throws Exception {
+ node.update(null);
+ }
+
+ private MockAbstractJcrNode createChild( String name,
+ int index,
+ List<Segment> children,
+ Node parent ) throws Exception {
+ MockAbstractJcrNode child = new MockAbstractJcrNode(session, name, parent);
+ Segment seg = Mockito.mock(Segment.class);
+ stub(seg.getName()).toReturn(new BasicName(null, name));
+ children.add(seg);
+ stub(session.getItem(parent.getPath() + "/{}" + name + '[' + index + ']')).toReturn(child);
+ return child;
+ }
+
+ private class MockAbstractJcrNode extends AbstractJcrNode {
+
+ String name;
+ Node parent;
+
+ MockAbstractJcrNode( Session session,
+ String name,
+ Node parent ) {
+ super(session);
+ this.name = name;
+ this.parent = parent;
+ }
+
+ public int getDepth() {
+ return 0;
+ }
+
+ public int getIndex() {
+ return 0;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Node getParent() {
+ return parent;
+ }
+
+ public String getPath() throws RepositoryException {
+ return (parent == null ? '/' + getName() : parent.getPath() + '/' + getName());
+ }
+ }
}
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrPropertyTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrPropertyTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/AbstractJcrPropertyTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -33,6 +33,7 @@
import javax.jcr.Property;
import javax.jcr.Session;
import javax.jcr.Value;
+import org.jboss.dna.common.util.StringUtil;
import org.jboss.dna.spi.ExecutionContext;
import org.jboss.dna.spi.graph.Name;
import org.junit.Before;
@@ -48,6 +49,8 @@
private AbstractJcrProperty prop;
@Mock
+ private Session session;
+ @Mock
private Node node;
@Mock
private ExecutionContext executionContext;
@@ -55,8 +58,9 @@
private Name name;
@Before
- public void before() {
+ public void before() throws Exception {
MockitoAnnotations.initMocks(this);
+ stub(node.getSession()).toReturn(session);
prop = new MockAbstractJcrProperty(node, executionContext, name);
}
@@ -67,6 +71,11 @@
Mockito.verify(visitor).visit(prop);
}
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowVisitationIfNoVisitor() throws Exception {
+ prop.accept(null);
+ }
+
@Test( expected = AssertionError.class )
public void shouldNotAllowNoSession() throws Exception {
new MockAbstractJcrProperty(null, executionContext, name);
@@ -102,10 +111,8 @@
}
@Test
- public void shouldProvideSession() throws Exception {
- Session session = Mockito.mock(Session.class);
- stub(node.getSession()).toReturn(session);
- assertThat(prop.getSession(), is(session));
+ public void shouldProvideDepth() throws Exception {
+ assertThat(prop.getDepth(), is(1));
}
@Test
@@ -137,7 +144,14 @@
}
@Test
- public void shouldNotBeANode() {
+ public void shouldProvideSession() throws Exception {
+ Session session = Mockito.mock(Session.class);
+ stub(node.getSession()).toReturn(session);
+ assertThat(prop.getSession(), is(session));
+ }
+
+ @Test
+ public void shouldIndicateIsNotANode() {
assertThat(prop.isNode(), is(false));
}
@@ -145,6 +159,7 @@
public void shouldIndicateSameAsNodeWithSameParentAndName() throws Exception {
stub(name.getString()).toReturn("propertyName");
Node otherNode = Mockito.mock(Node.class);
+ stub(otherNode.getSession()).toReturn(session);
Name otherName = Mockito.mock(Name.class);
stub(otherName.getString()).toReturn("propertyName");
stub(node.isSame(otherNode)).toReturn(true);
@@ -156,6 +171,7 @@
public void shouldIndicateDifferentThanNodeWithDifferentParent() throws Exception {
stub(name.getString()).toReturn("propertyName");
Node otherNode = Mockito.mock(Node.class);
+ stub(otherNode.getSession()).toReturn(session);
Name otherName = Mockito.mock(Name.class);
stub(otherName.getString()).toReturn("propertyName");
stub(node.isSame(otherNode)).toReturn(false);
@@ -167,6 +183,7 @@
public void shouldIndicateDifferentThanNodeWithDifferentName() throws Exception {
stub(name.getString()).toReturn("propertyName");
Node otherNode = Mockito.mock(Node.class);
+ stub(otherNode.getSession()).toReturn(session);
Name otherName = Mockito.mock(Name.class);
stub(otherName.getString()).toReturn("propertyName2");
stub(node.isSame(otherNode)).toReturn(true);
@@ -174,6 +191,56 @@
assertThat(prop.isSame(otherProp), is(false));
}
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetBooleanValue() {
+ prop.setValue(false);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetCalendarValue() {
+ prop.setValue(Calendar.getInstance());
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetDoubleValue() {
+ prop.setValue(0.0);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetInputStreamValue() {
+ prop.setValue(Mockito.mock(InputStream.class));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetLongValue() {
+ prop.setValue(0L);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetNodeValue() {
+ prop.setValue(Mockito.mock(Node.class));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetStringValue() {
+ prop.setValue("");
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetStringArrayValue() {
+ prop.setValue(StringUtil.EMPTY_STRING_ARRAY);
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetValueValue() {
+ prop.setValue(Mockito.mock(Value.class));
+ }
+
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowSetValueArrayValue() {
+ prop.setValue(new Value[0]);
+ }
+
private class MockAbstractJcrProperty extends AbstractJcrProperty {
MockAbstractJcrProperty( Node node,
@@ -203,15 +270,6 @@
/**
* {@inheritDoc}
*
- * @see javax.jcr.Item#getDepth()
- */
- public int getDepth() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- *
* @see javax.jcr.Property#getDouble()
*/
public double getDouble() {
Added: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrMultiValuePropertyTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrMultiValuePropertyTest.java (rev 0)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrMultiValuePropertyTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -0,0 +1,179 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.dna.jcr;
+
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.IsNull.notNullValue;
+import static org.junit.Assert.assertThat;
+import java.io.InputStream;
+import java.io.Reader;
+import java.util.Arrays;
+import java.util.Calendar;
+import java.util.UUID;
+import javax.jcr.Node;
+import javax.jcr.Property;
+import javax.jcr.PropertyType;
+import javax.jcr.Value;
+import javax.jcr.ValueFormatException;
+import org.jboss.dna.spi.ExecutionContext;
+import org.jboss.dna.spi.connector.BasicExecutionContext;
+import org.jboss.dna.spi.graph.Name;
+import org.jboss.dna.spi.graph.Path;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoAnnotations.Mock;
+
+/**
+ * @author jverhaeg
+ */
+public class JcrMultiValuePropertyTest {
+
+ @Mock
+ private Node node;
+ private ExecutionContext executionContext = new BasicExecutionContext();
+ @Mock
+ Name name;
+
+ @Before
+ public void before() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test( expected = AssertionError.class )
+ public void shouldNotAllowNoValue() {
+ new JcrMultiValueProperty(node, executionContext, name, null);
+ }
+
+ @Test
+ public void shouldProvideAppropriateType() throws Exception {
+ Property prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(true));
+ assertThat(prop.getType(), is(PropertyType.BOOLEAN));
+ Calendar cal = Calendar.getInstance();
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(cal));
+ assertThat(prop.getType(), is(PropertyType.DATE));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(cal.getTime()));
+ assertThat(prop.getType(), is(PropertyType.DATE));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1.0));
+ assertThat(prop.getType(), is(PropertyType.DOUBLE));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1.0F));
+ assertThat(prop.getType(), is(PropertyType.DOUBLE));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1));
+ assertThat(prop.getType(), is(PropertyType.LONG));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1L));
+ assertThat(prop.getType(), is(PropertyType.LONG));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(new Object()));
+ assertThat(prop.getType(), is(PropertyType.BINARY));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList("value"));
+ assertThat(prop.getType(), is(PropertyType.STRING));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(UUID.randomUUID()));
+ assertThat(prop.getType(), is(PropertyType.REFERENCE));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(Mockito.mock(Reader.class)));
+ assertThat(prop.getType(), is(PropertyType.BINARY));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(Mockito.mock(InputStream.class)));
+ assertThat(prop.getType(), is(PropertyType.BINARY));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(new Object()));
+ assertThat(prop.getType(), is(PropertyType.BINARY));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(name));
+ assertThat(prop.getType(), is(PropertyType.NAME));
+ prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(Mockito.mock(Path.class)));
+ assertThat(prop.getType(), is(PropertyType.PATH));
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideBoolean() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(true)).getBoolean();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideDateForCalendar() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(Calendar.getInstance())).getDate();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideDateForDate() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(Calendar.getInstance().getTime())).getDate();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideDoubleForDouble() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1.0)).getDouble();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideDoubleForFloat() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1.0F)).getDouble();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideLongForInteger() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1)).getLong();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideLongForLong() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(1L)).getLong();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideStream() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(new Object())).getStream();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideString() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList("value")).getString();
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideValue() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(true)).getValue();
+ }
+
+ @Test
+ public void shouldProvideValues() throws Exception {
+ Property prop = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(true));
+ Value[] vals = prop.getValues();
+ assertThat(vals, notNullValue());
+ assertThat(vals.length, is(1));
+ assertThat(vals[0].getBoolean(), is(true));
+ }
+
+ @Test( expected = ValueFormatException.class )
+ public void shouldNotProvideLength() throws Exception {
+ new JcrMultiValueProperty(node, executionContext, name, Arrays.asList("value")).getLength();
+ }
+
+ @Test
+ public void shouldProvideLengths() throws Exception {
+ long[] lengths = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList("value")).getLengths();
+ assertThat(lengths, notNullValue());
+ assertThat(lengths.length, is(1));
+ assertThat(lengths[0], is(5L));
+ Object obj = new Object();
+ lengths = new JcrMultiValueProperty(node, executionContext, name, Arrays.asList(obj)).getLengths();
+ assertThat(lengths, notNullValue());
+ assertThat(lengths.length, is(1));
+ assertThat(lengths[0], is((long)obj.toString().length()));
+ }
+}
Property changes on: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrMultiValuePropertyTest.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrNodeTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -53,10 +53,13 @@
public void before() throws Exception {
MockitoAnnotations.initMocks(this);
root = new JcrRootNode(session);
+ Segment segment = Mockito.mock(Segment.class);
Name name = Mockito.mock(Name.class);
stub(name.getString()).toReturn("name");
+ stub(segment.getName()).toReturn(name);
+ stub(segment.getIndex()).toReturn(2);
UUID uuid = UUID.randomUUID();
- node = new JcrNode(session, uuid, name);
+ node = new JcrNode(session, uuid, segment);
stub(session.getNodeByUUID(uuid.toString())).toReturn(root);
node.setProperties(new HashSet<Property>());
node.setChildren(new ArrayList<Segment>());
@@ -68,17 +71,22 @@
}
@Test
- public void shouldHaveZeroDepth() throws Exception {
+ public void shouldProvideDepth() throws Exception {
assertThat(node.getDepth(), is(1));
}
@Test
+ public void shouldProvideIndex() throws Exception {
+ assertThat(node.getIndex(), is(2));
+ }
+
+ @Test
public void shouldProvideName() throws Exception {
assertThat(node.getName(), is("name"));
}
@Test
public void shouldProvidePath() throws Exception {
- assertThat(node.getPath(), is("/name"));
+ assertThat(node.getPath(), is("/name[2]"));
}
}
Deleted: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyIteratorTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -1,180 +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.jcr;
-
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsNot.not;
-import static org.hamcrest.core.IsNull.notNullValue;
-import static org.junit.Assert.assertThat;
-import java.util.HashSet;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import javax.jcr.Property;
-import javax.jcr.PropertyIterator;
-import org.junit.Test;
-import org.mockito.Mockito;
-
-/**
- * @author jverhaeg
- */
-public class JcrPropertyIteratorTest {
-
- @Test( expected = AssertionError.class )
- public void shouldNotAllowNoProperties() throws Exception {
- new JcrPropertyIterator(null);
- }
-
- @Test
- public void shouldIndicateWhenPropertiesRemain() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- assertThat(iter.hasNext(), is(false));
- props.add(Mockito.mock(Property.class));
- iter = new JcrPropertyIterator(props);
- assertThat(iter.hasNext(), is(true));
- }
-
- @Test
- public void shouldAllowNextWhenPropertiesRemain() throws Exception {
- Set<Property> props = new HashSet<Property>();
- Property prop1 = Mockito.mock(Property.class);
- props.add(prop1);
- Property prop2 = Mockito.mock(Property.class);
- props.add(prop2);
- PropertyIterator iter = new JcrPropertyIterator(props);
- Property iterProp1 = (Property)iter.next();
- assertThat(iterProp1, notNullValue());
- Property iterProp2 = (Property)iter.next();
- assertThat(iterProp2, notNullValue());
- assertThat(iterProp1, is(not(iterProp2)));
- }
-
- @Test( expected = NoSuchElementException.class )
- public void shouldNotAllowNextWhenNoPropertiesRemain() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.next();
- }
-
- @Test
- public void shouldAllowNextPropertyWhenPropertiesRemain() throws Exception {
- Set<Property> props = new HashSet<Property>();
- Property prop1 = Mockito.mock(Property.class);
- props.add(prop1);
- Property prop2 = Mockito.mock(Property.class);
- props.add(prop2);
- PropertyIterator iter = new JcrPropertyIterator(props);
- Property iterProp1 = iter.nextProperty();
- assertThat(iterProp1, notNullValue());
- Property iterProp2 = iter.nextProperty();
- assertThat(iterProp2, notNullValue());
- assertThat(iterProp1, is(not(iterProp2)));
- }
-
- @Test( expected = NoSuchElementException.class )
- public void shouldNotAllowNextPropertyWhenNoPropertiesRemain() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.nextProperty();
- }
-
- @Test
- public void shouldAllowRemoveAfterNext() throws Exception {
- Set<Property> props = new HashSet<Property>();
- props.add(Mockito.mock(Property.class));
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.next();
- iter.remove();
- assertThat(props.isEmpty(), is(true));
- }
-
- @Test( expected = IllegalStateException.class )
- public void shouldNotAllowRemoveBeforeNext() throws Exception {
- Set<Property> props = new HashSet<Property>();
- props.add(Mockito.mock(Property.class));
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.remove();
- }
-
- @Test( expected = IllegalStateException.class )
- public void shouldNotAllowRemoveTwice() throws Exception {
- Set<Property> props = new HashSet<Property>();
- props.add(Mockito.mock(Property.class));
- props.add(Mockito.mock(Property.class));
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.next();
- iter.remove();
- iter.remove();
- }
-
- @Test
- public void shouldProvideSize() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- assertThat(iter.getSize(), is(0L));
- props.add(Mockito.mock(Property.class));
- iter = new JcrPropertyIterator(props);
- assertThat(iter.getSize(), is(1L));
- iter.next();
- iter.remove();
- assertThat(iter.getSize(), is(0L));
- }
-
- @Test
- public void shouldProvidePosition() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- assertThat(iter.getPosition(), is(0L));
- props.add(Mockito.mock(Property.class));
- iter = new JcrPropertyIterator(props);
- assertThat(iter.getPosition(), is(0L));
- iter.next();
- assertThat(iter.getPosition(), is(1L));
- iter.remove();
- assertThat(iter.getPosition(), is(1L));
- }
-
- @Test( expected = IllegalArgumentException.class )
- public void shouldNotAllowNegativeSkip() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.skip(-1);
- }
-
- @Test
- public void shouldAllowSkip() throws Exception {
- Set<Property> props = new HashSet<Property>();
- props.add(Mockito.mock(Property.class));
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.skip(0);
- assertThat(iter.hasNext(), is(true));
- iter.skip(1);
- assertThat(iter.hasNext(), is(false));
- }
-
- @Test( expected = NoSuchElementException.class )
- public void shouldNotAllowSkipPastRemainingProperties() throws Exception {
- Set<Property> props = new HashSet<Property>();
- PropertyIterator iter = new JcrPropertyIterator(props);
- iter.skip(1);
- }
-}
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrPropertyTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -24,7 +24,6 @@
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.stub;
import java.io.InputStream;
import java.io.Reader;
import java.util.Calendar;
@@ -105,10 +104,16 @@
@Test
public void shouldProvideStream() throws Exception {
- Property prop = new JcrProperty(node, executionContext, name, "value");
+ Property prop = new JcrProperty(node, executionContext, name, new Object());
InputStream stream = prop.getStream();
- assertThat(stream, notNullValue());
- stream.close();
+ try {
+ assertThat(stream, notNullValue());
+ assertThat(prop.getType(), is(PropertyType.BINARY));
+ } finally {
+ if (stream != null) {
+ stream.close();
+ }
+ }
}
@Test
@@ -172,11 +177,4 @@
public void shouldNotProvideLengths() throws Exception {
new JcrProperty(node, executionContext, name, "value").getLengths();
}
-
- @Test
- public void shouldProvideDepth() throws Exception {
- Property prop = new JcrProperty(node, executionContext, name, true);
- stub(node.getDepth()).toReturn(0);
- assertThat(prop.getDepth(), is(1));
- }
}
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRepositoryTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -99,6 +99,16 @@
new JcrRepository(executionContextFactory, null);
}
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowNoDescriptorKey() {
+ repository.getDescriptor(null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowEmptyDescriptorKey() {
+ repository.getDescriptor("");
+ }
+
@Test
public void shouldProvideBuiltInDescriptorKeys() {
testDescriptorKeys(repository);
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRootNodeTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRootNodeTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrRootNodeTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -45,7 +45,7 @@
private Set<Property> properties;
@Before
- public void before() {
+ public void before() throws Exception {
MockitoAnnotations.initMocks(this);
properties = new HashSet<Property>();
root = new JcrRootNode(session);
@@ -58,12 +58,17 @@
}
@Test
- public void shouldHaveZeroDepth() {
+ public void shouldHaveZeroDepth() throws Exception {
assertThat(root.getDepth(), is(0));
}
@Test
- public void shouldHaveEmptyName() {
+ public void shouldIndicateIndexIsOne() throws Exception {
+ assertThat(root.getIndex(), is(1));
+ }
+
+ @Test
+ public void shouldHaveEmptyName() throws Exception {
String name = root.getName();
assertThat(name, notNullValue());
assertThat(name.length(), is(0));
@@ -75,7 +80,7 @@
}
@Test
- public void shouldProvidePath() {
+ public void shouldProvidePath() throws Exception {
assertThat(root.getPath(), is("/"));
}
}
Modified: trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java
===================================================================
--- trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2008-09-08 16:28:03 UTC (rev 508)
+++ trunk/dna-jcr/src/test/java/org/jboss/dna/jcr/JcrSessionTest.java 2008-09-09 15:18:27 UTC (rev 509)
@@ -27,8 +27,11 @@
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.stub;
+import java.io.InputStream;
import java.lang.ref.WeakReference;
+import java.security.AccessControlException;
import java.security.Principal;
+import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -36,8 +39,10 @@
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Property;
+import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.Session;
+import javax.jcr.ValueFactory;
import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import org.jboss.dna.spi.ExecutionContext;
@@ -125,7 +130,42 @@
new JcrSession(repository, executionContext, WORKSPACE_NAME, connection, null);
}
+ @Test( expected = UnsupportedOperationException.class )
+ public void shouldNotAllowAddLockToken() throws Exception {
+ session.addLockToken(null);
+ }
+
@Test
+ public void shouldAllowCheckReadPermission() throws Exception {
+ session.checkPermission("/", "read");
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCheckPermissionWithNoPath() throws Exception {
+ session.checkPermission(null, "read");
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCheckPermissionWithEmptyPath() throws Exception {
+ session.checkPermission("", "read");
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCheckPermissionWithNoActions() throws Exception {
+ session.checkPermission("/", null);
+ }
+
+ @Test( expected = IllegalArgumentException.class )
+ public void shouldNotAllowCheckPermissionWithEmptyActions() throws Exception {
+ session.checkPermission("/", "");
+ }
+
+ @Test( expected = AccessControlException.class )
+ public void shouldNotAllowCheckNonReadPermission() throws Exception {
+ session.checkPermission("/", "any");
+ }
+
+ @Test
public void shouldProvideNoAttributes() throws Exception {
assertThat(session.getAttribute(null), nullValue());
}
@@ -148,7 +188,7 @@
}
@Test
- public void shouldBeLiveBeforeLogout() throws Exception {
+ public void shouldIndicateLiveBeforeLogout() throws Exception {
assertThat(session.isLive(), is(true));
}
@@ -158,7 +198,7 @@
}
@Test
- public void shouldNotBeLiveAfterLogout() throws Exception {
+ public void shouldIndicateNotLiveAfterLogout() throws Exception {
session.logout();
assertThat(session.isLive(), is(false));
}
@@ -205,4 +245,35 @@
item = session.getItem("/a/b/booleanProperty");
assertThat(item, instanceOf(Property.class));
}
+
+ @Test
+ public void shouldProvideValueFactory() throws Exception {
+ ValueFactory factory = session.getValueFactory();
+ assertThat(factory, notNullValue());
+ assertThat(factory.createValue(false), notNullValue());
+ assertThat(factory.createValue(Calendar.getInstance()), notNullValue());
+ assertThat(factory.createValue(0.0), notNullValue());
+ assertThat(factory.createValue(Mockito.mock(InputStream.class)), notNullValue());
+ assertThat(factory.createValue(0L), notNullValue());
+ Node node = Mockito.mock(Node.class);
+ stub(node.getUUID()).toReturn(UUID.randomUUID().toString());
+ assertThat(factory.createValue(node), notNullValue());
+ assertThat(factory.createValue(""), notNullValue());
+ assertThat(factory.createValue("", PropertyType.BINARY), notNullValue());
+ }
+
+ @Test
+ public void shouldNotHavePendingChanges() throws Exception {
+ assertThat(session.hasPendingChanges(), is(false));
+ }
+
+ @Test
+ public void shouldAllowImpersonation() throws Exception {
+ assertThat(session.impersonate(null), notNullValue());
+ }
+
+ @Test
+ public void shouldProvideItemExists() throws Exception {
+ assertThat(session.itemExists(""), is(false));
+ }
}
15 years, 7 months
DNA SVN: r508 - in trunk/docs/examples/gettingstarted/dna-example-java-sequencer: workspace/project1/src/org/acme and 1 other directory.
by dna-commits@lists.jboss.org
Author: spagop
Date: 2008-09-08 12:28:03 -0400 (Mon, 08 Sep 2008)
New Revision: 508
Modified:
trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java
trunk/docs/examples/gettingstarted/dna-example-java-sequencer/workspace/project1/src/org/acme/MySource.java
Log:
enhancement of sequencer and meta data to support array type
Modified: trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java
===================================================================
--- trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java 2008-09-08 16:26:38 UTC (rev 507)
+++ trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java 2008-09-08 16:28:03 UTC (rev 508)
@@ -345,7 +345,7 @@
try {
Node javaPackageDeclarationNode = javaCompilationUnit.getNode("java:package/java:packageDeclaration");
javaElements.add(extractInfo(javaPackageDeclarationNode));
- tree.put("Package", javaElements);
+ tree.put("Class package", javaElements);
} catch (PathNotFoundException e) {
// do nothing
}
@@ -357,7 +357,7 @@
Node javasingleTypeImportDeclarationNode = singleImportIterator.nextNode();
javaElements.add(extractInfo(javasingleTypeImportDeclarationNode));
}
- tree.put("Single Imports", javaElements);
+ tree.put("Class single Imports", javaElements);
} catch (PathNotFoundException e) {
// do nothing
}
@@ -368,7 +368,7 @@
Node javaImportOnDemandtDeclarationNode = javaImportOnDemandIterator.nextNode();
javaElements.add(extractInfo(javaImportOnDemandtDeclarationNode));
}
- tree.put("On demand imports", javaElements);
+ tree.put("Class on demand imports", javaElements);
} catch (PathNotFoundException e) {
// do nothing
@@ -377,7 +377,7 @@
javaElements = new ArrayList<Properties>();
Node javaNormalDeclarationClassNode = javaCompilationUnit.getNode("java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration");
javaElements.add(extractInfo(javaNormalDeclarationClassNode));
- tree.put("class head information", javaElements);
+ tree.put("Class head information", javaElements);
// field member informations
javaElements = new ArrayList<Properties>();
@@ -397,12 +397,29 @@
Node javaParameterizedType = rootFieldTypeNode.getNode("java:parameterizedType");
javaElements.add(extractInfo(javaParameterizedType));
}
+ if(rootFieldTypeNode.hasNode("java:arrayType")) {
+ Node javaArrayType = rootFieldTypeNode.getNode("java:arrayType[2]");
+ javaElements.add(extractInfo(javaArrayType));
+ }
}
tree.put("Class field members", javaElements);
// constructor informations
-
+ javaElements = new ArrayList<Properties>();
+ for (NodeIterator javaConstructorIterator = javaCompilationUnit.getNode("java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:constructor").getNodes(); javaConstructorIterator.hasNext();) {
+ Node javaConstructor = javaConstructorIterator.nextNode();
+ javaElements.add(extractInfo(javaConstructor));
+ }
+ tree.put("Class constructors", javaElements);
+
// method informations
+ javaElements = new ArrayList<Properties>();
+ for (NodeIterator javaMethodIterator = javaCompilationUnit.getNode("java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method").getNodes(); javaMethodIterator.hasNext();) {
+ Node javaMethod = javaMethodIterator.nextNode();
+ javaElements.add(extractInfo(javaMethod));
+ }
+ tree.put("Class member functions", javaElements);
+
javaInfo = new JavaInfo(javaCompilationUnit.getPath(), javaCompilationUnit.getName(), "java source", tree);
javaInfos.add(javaInfo);
}
Modified: trunk/docs/examples/gettingstarted/dna-example-java-sequencer/workspace/project1/src/org/acme/MySource.java
===================================================================
--- trunk/docs/examples/gettingstarted/dna-example-java-sequencer/workspace/project1/src/org/acme/MySource.java 2008-09-08 16:26:38 UTC (rev 507)
+++ trunk/docs/examples/gettingstarted/dna-example-java-sequencer/workspace/project1/src/org/acme/MySource.java 2008-09-08 16:28:03 UTC (rev 508)
@@ -35,14 +35,19 @@
private List<String> l;
private A<Integer> o;
private X x;
+ private int[] ia;
+ private Object[] oa;
+ private Collection[] ca;
MySource() {
}
- public MySource(int i, int j, Object o) {
+
+ public MySource( int i,
+ int j,
+ Object o ) {
this.i = i;
this.j = j;
}
-
public int getI() {
return this.i;
@@ -56,11 +61,22 @@
this.j = j;
}
- public void doSomething(int p1, double p2, Object o) {
+ public void doSomething( int p1,
+ double p2,
+ Object o ) {
l = new ArrayList<String>();
l.add("N1");
}
+ private double doSomething2( Object[] oa,
+ int[] ia ) {
+ System.out.println("genial");
+ }
+
+ public Object doSomething3() {
+ return null;
+ }
+
// nested class
class A<E> {
E e;
@@ -92,3 +108,4 @@
}
}
+
\ No newline at end of file
15 years, 7 months
DNA SVN: r507 - trunk/extensions/dna-sequencer-java/src/test/workspace/projectX/src/org/acme.
by dna-commits@lists.jboss.org
Author: spagop
Date: 2008-09-08 12:26:38 -0400 (Mon, 08 Sep 2008)
New Revision: 507
Modified:
trunk/extensions/dna-sequencer-java/src/test/workspace/projectX/src/org/acme/MySource.java
Log:
enhancement of sequencer and meta data to support array type
Modified: trunk/extensions/dna-sequencer-java/src/test/workspace/projectX/src/org/acme/MySource.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/test/workspace/projectX/src/org/acme/MySource.java 2008-09-08 16:25:57 UTC (rev 506)
+++ trunk/extensions/dna-sequencer-java/src/test/workspace/projectX/src/org/acme/MySource.java 2008-09-08 16:26:38 UTC (rev 507)
@@ -35,8 +35,9 @@
private List<String> l;
private A<Integer> o;
private X x;
- private int[] ai;
- private Object[] ao;
+ private int[] ia;
+ private Object[] oa;
+ private Collection[] ca;
MySource() {
}
@@ -62,6 +63,14 @@
l = new ArrayList<String>();
l.add("N1");
}
+
+ private double doSomething2(Object[] oa, int[] ia) {
+ System.out.println("genial");
+ }
+
+ public Object doSomething3() {
+ return null;
+ }
// nested class
class A<E> {
15 years, 7 months
DNA SVN: r506 - in trunk/extensions/dna-sequencer-java/src: test/java/org/jboss/dna/sequencer/java and 1 other directory.
by dna-commits@lists.jboss.org
Author: spagop
Date: 2008-09-08 12:25:57 -0400 (Mon, 08 Sep 2008)
New Revision: 506
Added:
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/ArrayTypeFieldMetadataSequencer.java
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/VariableSequencer.java
Modified:
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/AbstractJavaMetadata.java
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/CompilationUnitParser.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/JavaSourceCndDefinition.java
trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/SimpleTypeMetadataSequencer.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
Log:
enhancement of sequencer and meta data to support array type
Modified: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/AbstractJavaMetadata.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/AbstractJavaMetadata.java 2008-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/AbstractJavaMetadata.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -45,6 +45,7 @@
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
+import org.jboss.dna.common.util.ArgCheck;
import org.jboss.dna.sequencer.java.metadata.ArrayTypeFieldMetadata;
import org.jboss.dna.sequencer.java.metadata.ClassMetadata;
import org.jboss.dna.sequencer.java.metadata.ConstructorMetadata;
@@ -301,57 +302,28 @@
@SuppressWarnings( "unchecked" )
protected void processParametersOfMethodDeclaration( MethodDeclaration methodDeclaration,
MethodMetadata methodMetadata ) {
- List<SingleVariableDeclaration> params = methodDeclaration.parameters();
- for (SingleVariableDeclaration singleVariableDeclaration : params) {
+ for (SingleVariableDeclaration singleVariableDeclaration : (List<SingleVariableDeclaration>)methodDeclaration.parameters()) {
Type type = singleVariableDeclaration.getType();
if (type.isPrimitiveType()) {
- PrimitiveFieldMetadata primitiveFieldMetadata = new PrimitiveFieldMetadata();
- primitiveFieldMetadata.setType(((PrimitiveType)type).getPrimitiveTypeCode().toString());
- Variable variable = new Variable();
- variable.setName(JavaMetadataUtil.getName(singleVariableDeclaration.getName()));
- primitiveFieldMetadata.getVariables().add(variable);
- List<IExtendedModifier> extendedModifiers = singleVariableDeclaration.modifiers();
- for (IExtendedModifier extendedModifier : extendedModifiers) {
- ModifierMetadata modifierMetadata = new ModifierMetadata();
- if (extendedModifier.isAnnotation()) {
- // TODO
- } else {
- Modifier modifier = (Modifier)extendedModifier;
- modifierMetadata.setName(modifier.getKeyword().toString());
- primitiveFieldMetadata.getModifiers().add(modifierMetadata);
- }
- }
+ PrimitiveFieldMetadata primitiveFieldMetadata = (PrimitiveFieldMetadata)processVariableDeclaration(singleVariableDeclaration,
+ type);
methodMetadata.getParameters().add(primitiveFieldMetadata);
}
if (type.isParameterizedType()) {
- // TODO
+ ParameterizedTypeFieldMetadata parameterizedTypeFieldMetadata = (ParameterizedTypeFieldMetadata)processVariableDeclaration(singleVariableDeclaration,
+ type);
+ methodMetadata.getParameters().add(parameterizedTypeFieldMetadata);
}
if (type.isQualifiedType()) {
// TODO
}
if (type.isSimpleType()) {
- SimpleType simpleType = (SimpleType)type;
- SimpleTypeFieldMetadata simpleTypeFieldMetadata = new SimpleTypeFieldMetadata();
- simpleTypeFieldMetadata.setType(JavaMetadataUtil.getName(simpleType.getName()));
- Variable variable = new Variable();
- variable.setName(JavaMetadataUtil.getName(singleVariableDeclaration.getName()));
- simpleTypeFieldMetadata.getVariables().add(variable);
- List<IExtendedModifier> extendedModifiers = singleVariableDeclaration.modifiers();
- for (IExtendedModifier extendedModifier2 : extendedModifiers) {
- ModifierMetadata modifierMetadata = new ModifierMetadata();
- if (extendedModifier2.isAnnotation()) {
- // TODO
- } else {
- Modifier modifier = (Modifier)extendedModifier2;
- modifierMetadata.setName(modifier.getKeyword().toString());
- simpleTypeFieldMetadata.getModifiers().add(modifierMetadata);
- }
- }
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata = (SimpleTypeFieldMetadata)processVariableDeclaration(singleVariableDeclaration, type);
methodMetadata.getParameters().add(simpleTypeFieldMetadata);
}
if (type.isArrayType()) {
-
-
+ ArrayTypeFieldMetadata arrayTypeFieldMetadata = (ArrayTypeFieldMetadata)processVariableDeclaration(singleVariableDeclaration, type);
+ methodMetadata.getParameters().add(arrayTypeFieldMetadata);
}
if (type.isWildcardType()) {
// TODO
@@ -361,6 +333,131 @@
}
/**
+ * Process a {@link SingleVariableDeclaration} of a {@link MethodDeclaration}.
+ *
+ * @param singleVariableDeclaration
+ * @param type
+ * @return a field meta data.
+ */
+ @SuppressWarnings( "unchecked" )
+ private FieldMetadata processVariableDeclaration( SingleVariableDeclaration singleVariableDeclaration,
+ Type type ) {
+
+ Variable variable;
+ if (type.isPrimitiveType()) {
+ PrimitiveFieldMetadata primitiveFieldMetadata = new PrimitiveFieldMetadata();
+ primitiveFieldMetadata.setType(((PrimitiveType)type).getPrimitiveTypeCode().toString());
+ variable = new Variable();
+ variable.setName(JavaMetadataUtil.getName(singleVariableDeclaration.getName()));
+ primitiveFieldMetadata.getVariables().add(variable);
+ for (IExtendedModifier extendedModifier : (List<IExtendedModifier>)singleVariableDeclaration.modifiers()) {
+ ModifierMetadata modifierMetadata = new ModifierMetadata();
+ if (extendedModifier.isAnnotation()) {
+ // TODO
+ } else {
+ Modifier modifier = (Modifier)extendedModifier;
+ modifierMetadata.setName(modifier.getKeyword().toString());
+ primitiveFieldMetadata.getModifiers().add(modifierMetadata);
+ }
+ }
+ return primitiveFieldMetadata;
+ }
+ if(type.isSimpleType()) {
+ SimpleType simpleType = (SimpleType)type;
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata = new SimpleTypeFieldMetadata();
+ simpleTypeFieldMetadata.setType(JavaMetadataUtil.getName(simpleType.getName()));
+ variable = new Variable();
+ variable.setName(JavaMetadataUtil.getName(singleVariableDeclaration.getName()));
+ simpleTypeFieldMetadata.getVariables().add(variable);
+ for (IExtendedModifier simpleTypeExtendedModifier : (List<IExtendedModifier> )singleVariableDeclaration.modifiers()) {
+ ModifierMetadata modifierMetadata = new ModifierMetadata();
+ if (simpleTypeExtendedModifier.isAnnotation()) {
+ // TODO
+ } else {
+ Modifier modifier = (Modifier)simpleTypeExtendedModifier;
+ modifierMetadata.setName(modifier.getKeyword().toString());
+ simpleTypeFieldMetadata.getModifiers().add(modifierMetadata);
+ }
+ }
+ return simpleTypeFieldMetadata;
+ }
+ if (type.isParameterizedType()) {
+ ParameterizedTypeFieldMetadata parameterizedTypeFieldMetadata = new ParameterizedTypeFieldMetadata();
+ ParameterizedType parameterizedType = (ParameterizedType)type;
+ parameterizedTypeFieldMetadata.setType(getTypeName(parameterizedType));
+ variable = new Variable();
+ variable.setName(JavaMetadataUtil.getName(singleVariableDeclaration.getName()));
+ parameterizedTypeFieldMetadata.getVariables().add(variable);
+ for (IExtendedModifier parameterizedExtendedModifier : (List<IExtendedModifier>)singleVariableDeclaration.modifiers()) {
+ ModifierMetadata modifierMetadata = new ModifierMetadata();
+ if(parameterizedExtendedModifier.isAnnotation()) {
+ // TODO
+ } else {
+ Modifier modifier = (Modifier)parameterizedExtendedModifier;
+ modifierMetadata.setName(modifier.getKeyword().toString());
+ parameterizedTypeFieldMetadata.getModifiers().add(modifierMetadata);
+ }
+ }
+ return parameterizedTypeFieldMetadata;
+ }
+ if(type.isArrayType()) {
+ ArrayTypeFieldMetadata arrayTypeFieldMetadata = new ArrayTypeFieldMetadata();
+ ArrayType arrayType = (ArrayType)type;
+ arrayTypeFieldMetadata.setType(getTypeName(arrayType));
+ variable = new Variable();
+ variable.setName(JavaMetadataUtil.getName(singleVariableDeclaration.getName()));
+ arrayTypeFieldMetadata.getVariables().add(variable);
+
+ for (IExtendedModifier arrayTypeExtendedModifier : (List<IExtendedModifier>)singleVariableDeclaration.modifiers()) {
+ ModifierMetadata modifierMetadata = new ModifierMetadata();
+ if(arrayTypeExtendedModifier.isAnnotation()) {
+ // TODO
+ } else {
+ Modifier modifier = (Modifier)arrayTypeExtendedModifier;
+ modifierMetadata.setName(modifier.getKeyword().toString());
+ arrayTypeFieldMetadata.getModifiers().add(modifierMetadata);
+ }
+ }
+ return arrayTypeFieldMetadata;
+ }
+ return null;
+ }
+
+ /**
+ * Extract the type name
+ *
+ * @param type - the type to be processed. This can be primitive, simple, parameterized ...
+ * @return the name of a type.
+ * @throws IllegalArgumentException if type is null.
+ */
+ private String getTypeName( Type type ) {
+ ArgCheck.isNotNull(type, "type");
+ if (type.isPrimitiveType()) {
+ PrimitiveType primitiveType = (PrimitiveType)type;
+ return primitiveType.getPrimitiveTypeCode().toString();
+ }
+ if (type.isSimpleType()) {
+ SimpleType simpleType = (SimpleType)type;
+ return JavaMetadataUtil.getName(simpleType.getName());
+ }
+ if(type.isArrayType()) {
+ ArrayType arrayType = (ArrayType)type;
+ // the element type is never an array type
+ Type elementType = arrayType.getElementType();
+ if (elementType.isPrimitiveType()) {
+ return ((PrimitiveType)elementType).getPrimitiveTypeCode().toString();
+
+ }
+ // can't be an array type
+ if (elementType.isSimpleType()) {
+ return JavaMetadataUtil.getName(((SimpleType)elementType).getName());
+ }
+
+ }
+ return null;
+ }
+
+ /**
* Get {@link ConstructorMetadata}
*
* @param methodDeclaration
@@ -446,7 +543,7 @@
processModifiersAndVariablesOfFieldDeclaration(fieldDeclaration, arrayTypeFieldMetadata);
return arrayTypeFieldMetadata;
}
-
+
return null;
}
Added: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/ArrayTypeFieldMetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/ArrayTypeFieldMetadataSequencer.java (rev 0)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/ArrayTypeFieldMetadataSequencer.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -0,0 +1,118 @@
+/*
+ * 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.java;
+
+import java.util.List;
+import org.jboss.dna.sequencer.java.metadata.ArrayTypeFieldMetadata;
+import org.jboss.dna.sequencer.java.metadata.ModifierMetadata;
+import org.jboss.dna.sequencer.java.metadata.Variable;
+import org.jboss.dna.spi.graph.NameFactory;
+import org.jboss.dna.spi.graph.Path;
+import org.jboss.dna.spi.graph.PathFactory;
+import org.jboss.dna.spi.sequencers.SequencerOutput;
+
+/**
+ * Sequencer for array types.
+ *
+ * @author Serge Pagop
+ */
+public class ArrayTypeFieldMetadataSequencer implements JavaSourceCndDefinition {
+
+ /**
+ * Sequence all formal parameters of a method.
+ *
+ * @param output - the {@link SequencerOutput}.
+ * @param nameFactory - the {@link NameFactory}.
+ * @param pathFactory - the {@link PathFactory}.
+ * @param arrayTypeFieldMetadata - the meta data of a array type.
+ * @param methodParamRootPath - Base path of the method declaration.
+ */
+ public static void sequenceMethodFormalParam( SequencerOutput output,
+ NameFactory nameFactory,
+ PathFactory pathFactory,
+ ArrayTypeFieldMetadata arrayTypeFieldMetadata,
+ String methodParamRootPath ) {
+ String methodFormalParamRootPath = ArrayTypeFieldMetadataSequencer.createRootPath(methodParamRootPath);
+ Path methodParamChildNode = pathFactory.create(methodFormalParamRootPath);
+ output.setProperty(methodParamChildNode, nameFactory.create(JAVA_ARRAY_TYPE_NAME), arrayTypeFieldMetadata.getType());
+ Path ArrayTypeVariableChildNode = pathFactory.create(JavaMetadataUtil.createPath(methodFormalParamRootPath + SLASH
+ + JAVA_ARRAY_TYPE_VARIABLE + SLASH
+ + JAVA_VARIABLE));
+ for (Variable variable : arrayTypeFieldMetadata.getVariables()) {
+ VariableSequencer.sequenceTheVariable(output, nameFactory, variable, ArrayTypeVariableChildNode);
+ }
+
+ }
+
+ /**
+ * the root path.
+ *
+ * @param basePath - the base path to use to build a root path.
+ * @return the root path, that is compose from other base path.
+ */
+ public static String createRootPath( String basePath ) {
+ return JavaMetadataUtil.createPath(basePath + SLASH + JAVA_TYPE_CHILD_NODE + SLASH + JAVA_ARRAY_TYPE_CHILD_NODE);
+ }
+
+ /**
+ * Sequence member data of array type.
+ *
+ * @param arrayTypeFieldMetadata
+ * @param pathFactory
+ * @param nameFactory
+ * @param output
+ * @param path
+ * @param index
+ */
+ public static void sequenceFieldMemberData( ArrayTypeFieldMetadata arrayTypeFieldMetadata,
+ PathFactory pathFactory,
+ NameFactory nameFactory,
+ SequencerOutput output,
+ String path,
+ int index ) {
+
+ // type
+ Path arryTypeChildNode = pathFactory.create(path);
+ output.setProperty(arryTypeChildNode, nameFactory.create(JAVA_ARRAY_TYPE_NAME), arrayTypeFieldMetadata.getType());
+ // modifiers
+ List<ModifierMetadata> modifiers = arrayTypeFieldMetadata.getModifiers();
+ int arrayModifierIndex = 1;
+ for (ModifierMetadata modifierMetadata : modifiers) {
+ String modifierPath = JavaMetadataUtil.createPathWithIndex(path + SLASH + JAVA_ARRAY_TYPE_MODIFIER_CHILD_NODE + SLASH
+ + JAVA_MODIFIER_DECLARATION_CHILD_NODE, arrayModifierIndex);
+ Path modifierChildNode = pathFactory.create(modifierPath);
+ output.setProperty(modifierChildNode, nameFactory.create(JAVA_MODIFIER_NAME), modifierMetadata.getName());
+ arrayModifierIndex++;
+ }
+ // variables
+ List<Variable> variables = arrayTypeFieldMetadata.getVariables();
+ int arrayVariableIndex = 1;
+ for (Variable variable : variables) {
+ String variablePath = JavaMetadataUtil.createPathWithIndex(path + SLASH + JAVA_ARRAY_TYPE_VARIABLE + SLASH
+ + JAVA_VARIABLE, arrayVariableIndex);
+ Path primitiveChildNode = pathFactory.create(variablePath);
+ VariableSequencer.sequenceTheVariable(output, nameFactory, variable, primitiveChildNode);
+ arrayVariableIndex++;
+ }
+ }
+
+}
Modified: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/CompilationUnitParser.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/CompilationUnitParser.java 2008-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/CompilationUnitParser.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -26,7 +26,7 @@
import org.eclipse.jdt.core.dom.ASTParser;
/**
- * The Parser, tha process the a compilation unit.
+ * The Parser, that process the a compilation unit.
*
* @author Serge Pagop
*/
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-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaMetadataSequencer.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -301,11 +301,13 @@
for (TypeMetadata typeMetadata : javaMetadata.getTypeMetadata()) {
// class declaration
if (typeMetadata instanceof ClassMetadata) {
+
+ String normalClassRootPath = JAVA_COMPILATION_UNIT_NODE + SLASH + JAVA_UNIT_TYPE_CHILD_NODE + SLASH
+ + JAVA_CLASS_DECLARATION_CHILD_NODE + SLASH + JAVA_NORMAL_CLASS_CHILD_NODE
+ + SLASH + JAVA_NORMAL_CLASS_DECLARATION_CHILD_NODE;
+
ClassMetadata classMetadata = (ClassMetadata)typeMetadata;
- Path classChildNode = pathFactory.create(JAVA_COMPILATION_UNIT_NODE + SLASH + JAVA_UNIT_TYPE_CHILD_NODE
- + SLASH + JAVA_CLASS_DECLARATION_CHILD_NODE + SLASH
- + JAVA_NORMAL_CLASS_CHILD_NODE + SLASH
- + JAVA_NORMAL_CLASS_DECLARATION_CHILD_NODE);
+ Path classChildNode = pathFactory.create(normalClassRootPath);
output.setProperty(classChildNode, nameFactory.create(JAVA_NORMAL_CLASS_NAME), classMetadata.getName());
// process modifiers of the class declaration
@@ -313,13 +315,8 @@
int modifierIndex = 1;
for (ModifierMetadata modifierMetadata : classModifiers) {
- Path classModifierChildNode = pathFactory.create(JAVA_COMPILATION_UNIT_NODE + SLASH
- + JAVA_UNIT_TYPE_CHILD_NODE + SLASH
- + JAVA_CLASS_DECLARATION_CHILD_NODE + SLASH
- + JAVA_NORMAL_CLASS_CHILD_NODE + SLASH
- + JAVA_NORMAL_CLASS_DECLARATION_CHILD_NODE + SLASH
- + JAVA_MODIFIER_CHILD_NODE + SLASH
- + JAVA_MODIFIER_DECLARATION_CHILD_NODE + "["
+ Path classModifierChildNode = pathFactory.create(normalClassRootPath + SLASH + JAVA_MODIFIER_CHILD_NODE
+ + SLASH + JAVA_MODIFIER_DECLARATION_CHILD_NODE + "["
+ modifierIndex + "]");
output.setProperty(classModifierChildNode,
@@ -331,24 +328,16 @@
int primitiveIndex = 1;
int simpleIndex = 1;
int parameterizedIndex = 1;
+ int arrayIndex = 1;
for (FieldMetadata fieldMetadata : classMetadata.getFields()) {
+ String fieldMemberDataRootPath = JavaMetadataUtil.createPath(normalClassRootPath + SLASH
+ + JAVA_FIELD_CHILD_NODE + SLASH
+ + JAVA_FIELD_TYPE_CHILD_NODE + SLASH
+ + JAVA_TYPE_CHILD_NODE);
if (fieldMetadata instanceof PrimitiveFieldMetadata) {
// primitive type
PrimitiveFieldMetadata primitiveFieldMetadata = (PrimitiveFieldMetadata)fieldMetadata;
- String primitiveFieldRootPath = JavaMetadataUtil.createPathWithIndex(JAVA_COMPILATION_UNIT_NODE
- + SLASH
- + JAVA_UNIT_TYPE_CHILD_NODE
- + SLASH
- + JAVA_CLASS_DECLARATION_CHILD_NODE
- + SLASH
- + JAVA_NORMAL_CLASS_CHILD_NODE
- + SLASH
- + JAVA_NORMAL_CLASS_DECLARATION_CHILD_NODE
- + SLASH + JAVA_FIELD_CHILD_NODE
- + SLASH
- + JAVA_FIELD_TYPE_CHILD_NODE
- + SLASH + JAVA_TYPE_CHILD_NODE
- + SLASH
+ String primitiveFieldRootPath = JavaMetadataUtil.createPathWithIndex(fieldMemberDataRootPath + SLASH
+ JAVA_PRIMITIVE_TYPE_CHILD_NODE,
primitiveIndex);
// type
@@ -379,7 +368,7 @@
+ JAVA_VARIABLE,
primitiveVariableIndex);
Path primitiveChildNode = pathFactory.create(variablePath);
- sequenceTheVariable(output, nameFactory, variable, primitiveChildNode);
+ VariableSequencer.sequenceTheVariable(output, nameFactory, variable, primitiveChildNode);
primitiveVariableIndex++;
}
primitiveIndex++;
@@ -387,8 +376,17 @@
// Array type
if (fieldMetadata instanceof ArrayTypeFieldMetadata) {
- @SuppressWarnings( "unused" )
ArrayTypeFieldMetadata arrayTypeFieldMetadata = (ArrayTypeFieldMetadata)fieldMetadata;
+ String arrayTypeRootPath = JavaMetadataUtil.createPathWithIndex(fieldMemberDataRootPath + SLASH
+ + JAVA_ARRAY_TYPE_CHILD_NODE,
+ arrayIndex);
+ ArrayTypeFieldMetadataSequencer.sequenceFieldMemberData(arrayTypeFieldMetadata,
+ pathFactory,
+ nameFactory,
+ output,
+ arrayTypeRootPath,
+ arrayIndex);
+ arrayIndex++;
}
// Simple type
@@ -441,7 +439,7 @@
+ JAVA_VARIABLE,
simpleTypeVariableIndex);
Path primitiveChildNode = pathFactory.create(variablePath);
- sequenceTheVariable(output, nameFactory, variable, primitiveChildNode);
+ VariableSequencer.sequenceTheVariable(output, nameFactory, variable, primitiveChildNode);
simpleTypeVariableIndex++;
}
@@ -484,7 +482,10 @@
Path parameterizedTypeVariableChildNode = ParameterizedTypeFieldMetadataSequencer.getParameterizedTypeFieldVariablePath(pathFactory,
parameterizedTypeFieldRootPath,
parameterizedTypeVariableIndex);
- sequenceTheVariable(output, nameFactory, variable, parameterizedTypeVariableChildNode);
+ VariableSequencer.sequenceTheVariable(output,
+ nameFactory,
+ variable,
+ parameterizedTypeVariableChildNode);
parameterizedTypeVariableIndex++;
}
@@ -562,16 +563,20 @@
constructPrimitiveFormalParamRootPath);
// variables
for (Variable variable : primitiveMetadata.getVariables()) {
- sequenceTheVariable(output, nameFactory, variable, constructorPrimitiveParamChildNode);
+ VariableSequencer.sequenceTheVariable(output,
+ nameFactory,
+ variable,
+ constructorPrimitiveParamChildNode);
}
}
// Simple type
if (fieldMetadata instanceof SimpleTypeFieldMetadata) {
- processMethodFormalParamOfSimpleType(output,
- nameFactory,
- pathFactory,
- fieldMetadata,
- constructorParameterRootPath);
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata = (SimpleTypeFieldMetadata)fieldMetadata;
+ SimpleTypeMetadataSequencer.sequenceMethodFormalParam(output,
+ nameFactory,
+ pathFactory,
+ simpleTypeFieldMetadata,
+ constructorParameterRootPath);
}
// parameterized type
@@ -645,7 +650,7 @@
methodPrimitiveFormalParamRootPath);
// variables
for (Variable variable : primitive.getVariables()) {
- sequenceTheVariable(output, nameFactory, variable, methodParamChildNode);
+ VariableSequencer.sequenceTheVariable(output, nameFactory, variable, methodParamChildNode);
}
// type
Path methodPrimitiveTypeParamChildNode = pathFactory.create(methodPrimitiveFormalParamRootPath);
@@ -656,13 +661,23 @@
}
if (fieldMetadata instanceof SimpleTypeFieldMetadata) {
- processMethodFormalParamOfSimpleType(output,
- nameFactory,
- pathFactory,
- fieldMetadata,
- methodParamRootPath);
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata = (SimpleTypeFieldMetadata)fieldMetadata;
+ SimpleTypeMetadataSequencer.sequenceMethodFormalParam(output,
+ nameFactory,
+ pathFactory,
+ simpleTypeFieldMetadata,
+ methodParamRootPath);
}
+ if (fieldMetadata instanceof ArrayTypeFieldMetadata) {
+ ArrayTypeFieldMetadata arrayTypeFieldMetadata = (ArrayTypeFieldMetadata)fieldMetadata;
+ ArrayTypeFieldMetadataSequencer.sequenceMethodFormalParam(output,
+ nameFactory,
+ pathFactory,
+ arrayTypeFieldMetadata,
+ methodParamRootPath);
+ }
+
// TODO parameter reference types
methodParameterIndex++;
@@ -684,6 +699,10 @@
methodReturnPrimitiveType.getType());
}
+ if(methodReturnType instanceof SimpleTypeFieldMetadata) {
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata = (SimpleTypeFieldMetadata) methodReturnType;
+ SimpleTypeMetadataSequencer.sequenceMethodReturnType(output,nameFactory,pathFactory,simpleTypeFieldMetadata,methodRootPath);
+ }
// TODO method return reference type
@@ -699,48 +718,4 @@
progressMonitor.done();
}
-
- /**
- * Process formal parameter of type simple type .
- *
- * @param output - the {@link SequencerOutput}.
- * @param nameFactory - The {@link NameFactory}.
- * @param pathFactory - the {@link PathFactory}.
- * @param fieldMetadata - the meta data.
- * @param methodParamRootPath - base path of the parameter.
- */
- private void processMethodFormalParamOfSimpleType( SequencerOutput output,
- NameFactory nameFactory,
- PathFactory pathFactory,
- FieldMetadata fieldMetadata,
- String methodParamRootPath ) {
- SimpleTypeFieldMetadata simpleTypeFieldMetadata = (SimpleTypeFieldMetadata)fieldMetadata;
- String methodSimpleTypeFormalParamRootPath = SimpleTypeMetadataSequencer.createRootPath(methodParamRootPath);
- SimpleTypeMetadataSequencer.sequenceConstructorSimpleTypeName(simpleTypeFieldMetadata,
- methodSimpleTypeFormalParamRootPath,
- output,
- nameFactory,
- pathFactory);
- Path constructorSimpleTypeParamChildNode = SimpleTypeMetadataSequencer.createSimpleTypeParamPath(pathFactory,
- methodSimpleTypeFormalParamRootPath);
- for (Variable variable : simpleTypeFieldMetadata.getVariables()) {
- sequenceTheVariable(output, nameFactory, variable, constructorSimpleTypeParamChildNode);
- }
- }
-
- /**
- * Sequence a variable.
- *
- * @param output - the {@link SequencerOutput}.
- * @param nameFactory - the {@link NameFactory}.
- * @param variable - the variable to be added in the tree.
- * @param path - the path
- */
- private void sequenceTheVariable( SequencerOutput output,
- NameFactory nameFactory,
- Variable variable,
- Path path ) {
- output.setProperty(path, nameFactory.create(JAVA_VARIABLE_NAME), variable.getName());
- }
-
}
Modified: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaSourceCndDefinition.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaSourceCndDefinition.java 2008-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/JavaSourceCndDefinition.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -125,5 +125,12 @@
public static final String JAVA_PARAMETERIZED_TYPE_MODIFIER_CHILD_NODE ="java:parameterizedTypeModifier";
public static final String JAVA_PARAMETERIZED_TYPE_NAME ="java:parameterizedTypeName";
public static final String JAVA_PARAMETERIZED_TYPE_VARIABLE ="java:parameterizedTypeVariable";
+
+ // Array type
+ public static final String JAVA_ARRAY_TYPE_CHILD_NODE="java:arrayType";
+ public static final String JAVA_ARRAY_TYPE_DESCRIPTION ="java:arrayTypeDescription";
+ public static final String JAVA_ARRAY_TYPE_MODIFIER_CHILD_NODE ="java:arrayTypeModifier";
+ public static final String JAVA_ARRAY_TYPE_NAME ="java:arrayTypeName";
+ public static final String JAVA_ARRAY_TYPE_VARIABLE ="java:arrayTypeVariable";
}
Modified: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/SimpleTypeMetadataSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/SimpleTypeMetadataSequencer.java 2008-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/SimpleTypeMetadataSequencer.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -22,6 +22,7 @@
package org.jboss.dna.sequencer.java;
import org.jboss.dna.sequencer.java.metadata.SimpleTypeFieldMetadata;
+import org.jboss.dna.sequencer.java.metadata.Variable;
import org.jboss.dna.spi.graph.NameFactory;
import org.jboss.dna.spi.graph.Path;
import org.jboss.dna.spi.graph.PathFactory;
@@ -39,6 +40,32 @@
}
/**
+ * @param output
+ * @param nameFactory
+ * @param pathFactory
+ * @param simpleTypeFieldMetadata
+ * @param methodParamRootPath
+ */
+ public static void sequenceMethodFormalParam( SequencerOutput output,
+ NameFactory nameFactory,
+ PathFactory pathFactory,
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata,
+ String methodParamRootPath ) {
+
+ String methodSimpleTypeFormalParamRootPath = SimpleTypeMetadataSequencer.createRootPath(methodParamRootPath);
+ SimpleTypeMetadataSequencer.sequenceConstructorSimpleTypeName(simpleTypeFieldMetadata,
+ methodSimpleTypeFormalParamRootPath,
+ output,
+ nameFactory,
+ pathFactory);
+ Path methodSimpleTypeParamChildNode = SimpleTypeMetadataSequencer.createSimpleTypeParamPath(pathFactory,
+ methodSimpleTypeFormalParamRootPath);
+ for (Variable variable : simpleTypeFieldMetadata.getVariables()) {
+ VariableSequencer.sequenceTheVariable(output, nameFactory, variable, methodSimpleTypeParamChildNode);
+ }
+ }
+
+ /**
* the root path.
*
* @param basePath - the base path to use to build a root path.
@@ -79,8 +106,32 @@
*/
public static Path createSimpleTypeParamPath( PathFactory pathFactory,
String rootPath ) {
- String paramVariablePath = JavaMetadataUtil.createPath(rootPath + SLASH + JAVA_SIMPLE_TYPE_VARIABLE + SLASH + JAVA_VARIABLE);
+ String paramVariablePath = JavaMetadataUtil.createPath(rootPath + SLASH + JAVA_SIMPLE_TYPE_VARIABLE + SLASH
+ + JAVA_VARIABLE);
return pathFactory.create(paramVariablePath);
}
+ /**
+ * Sequence the return type of a method.
+ *
+ * @param output
+ * @param nameFactory
+ * @param pathFactory
+ * @param simpleTypeFieldMetadata
+ * @param methodRootPath
+ */
+ public static void sequenceMethodReturnType( SequencerOutput output,
+ NameFactory nameFactory,
+ PathFactory pathFactory,
+ SimpleTypeFieldMetadata simpleTypeFieldMetadata,
+ String methodRootPath ) {
+ String methodReturnSimpleTypePath = JavaMetadataUtil.createPath(methodRootPath + SLASH + JAVA_RETURN_TYPE + SLASH
+ + JAVA_SIMPLE_TYPE_CHILD_NODE);
+
+ Path methodReturnPrimitiveTypeChildNode = pathFactory.create(methodReturnSimpleTypePath);
+ output.setProperty(methodReturnPrimitiveTypeChildNode,
+ nameFactory.create(JAVA_SIMPLE_TYPE_NAME),
+ simpleTypeFieldMetadata.getType());
+ }
+
}
Added: trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/VariableSequencer.java
===================================================================
--- trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/VariableSequencer.java (rev 0)
+++ trunk/extensions/dna-sequencer-java/src/main/java/org/jboss/dna/sequencer/java/VariableSequencer.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -0,0 +1,50 @@
+/*
+ * 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.java;
+
+import org.jboss.dna.sequencer.java.metadata.Variable;
+import org.jboss.dna.spi.graph.NameFactory;
+import org.jboss.dna.spi.graph.Path;
+import org.jboss.dna.spi.sequencers.SequencerOutput;
+
+/**
+ * Sequencer for variabels.
+ * @author Perge Pagop
+ *
+ */
+public class VariableSequencer implements JavaSourceCndDefinition {
+
+ /**
+ * Sequence a variable.
+ *
+ * @param output - the {@link SequencerOutput}.
+ * @param nameFactory - the {@link NameFactory}.
+ * @param variable - the variable to be added in the tree.
+ * @param path - the path
+ */
+ public static void sequenceTheVariable( SequencerOutput output,
+ NameFactory nameFactory,
+ Variable variable,
+ Path path ) {
+ output.setProperty(path, nameFactory.create(JAVA_VARIABLE_NAME), variable.getName());
+ }
+}
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-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataSequencerTest.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -161,6 +161,27 @@
"java:variableName"),
is(new Object[] {"x"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:field/java:fieldType/java:type/java:arrayType[1]",
+ "java:arrayTypeName"),
+ is(new Object[] {"int"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:field/java:fieldType/java:type/java:arrayType[1]/java:arrayTypeVariable/java:variable[1]",
+ "java:variableName"),
+ is(new Object[] {"ia"}));
+
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:field/java:fieldType/java:type/java:arrayType[2]",
+ "java:arrayTypeName"),
+ is(new Object[] {"Object"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:field/java:fieldType/java:type/java:arrayType[2]/java:arrayTypeVariable/java:variable[1]",
+ "java:variableName"),
+ is(new Object[] {"oa"}));
+
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:field/java:fieldType/java:type/java:arrayType[3]",
+ "java:arrayTypeName"),
+ is(new Object[] {"Collection"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:field/java:fieldType/java:type/java:arrayType[3]/java:arrayTypeVariable/java:variable[1]",
+ "java:variableName"),
+ is(new Object[] {"ca"}));
+
// support for methods sequencing (modifiers, return type, method name, parameters).Not supported are javadoc
// MySource() constructor
@@ -256,6 +277,40 @@
"java:variableName"),
is(new Object[] {"o"}));
+ // private double doSomething2(Object[] oa, int[] ia) method
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]/java:modifier/java:modifierDeclaration[1]",
+ "java:modifierName"),
+ is(new Object[] {"private"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]/java:resultType/java:primitiveType",
+ "java:primitiveTypeName"),
+ is(new Object[] {"double"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]",
+ "java:methodName"),
+ is(new Object[] {"doSomething2"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]/java:parameter/java:formalParameter[1]/java:type/java:arrayType",
+ "java:arrayTypeName"),
+ is(new Object[] {"Object"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]/java:parameter/java:formalParameter[1]/java:type/java:arrayType/java:arrayTypeVariable/java:variable",
+ "java:variableName"),
+ is(new Object[] {"oa"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]/java:parameter/java:formalParameter[2]/java:type/java:arrayType",
+ "java:arrayTypeName"),
+ is(new Object[] {"int"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[5]/java:parameter/java:formalParameter[2]/java:type/java:arrayType/java:arrayTypeVariable/java:variable",
+ "java:variableName"),
+ is(new Object[] {"ia"}));
+
+ // public Object doSomething3() method
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[6]/java:modifier/java:modifierDeclaration[1]",
+ "java:modifierName"),
+ is(new Object[] {"public"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[6]/java:resultType/java:simpleType",
+ "java:simpleTypeName"),
+ is(new Object[] {"Object"}));
+ assertThat(output.getPropertyValues("java:compilationUnit/java:unitType/java:classDeclaration/java:normalClass/java:normalClassDeclaration/java:method/java:methodDeclaration[6]",
+ "java:methodName"),
+ is(new Object[] {"doSomething3"}));
+
}
}
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-09-05 20:01:49 UTC (rev 505)
+++ trunk/extensions/dna-sequencer-java/src/test/java/org/jboss/dna/sequencer/java/JavaMetadataTest.java 2008-09-08 16:25:57 UTC (rev 506)
@@ -157,7 +157,7 @@
assertThat(marker.getName(), is("MyClassAnnotation"));
}
}
- // get fields
+ // get fields (member data)
List<FieldMetadata> fields = classMetadata.getFields();
assertNotNull(fields);
assertTrue(fields.size() > 0);
@@ -196,15 +196,15 @@
assertNotNull(arrayTypeFieldMetadata1);
assertTrue(arrayTypeFieldMetadata1.getModifiers().size() > 0);
assertThat(arrayTypeFieldMetadata1.getType(), is("int"));
- assertThat(arrayTypeFieldMetadata1.getVariables().get(0).getName(), is("ai"));
+ assertThat(arrayTypeFieldMetadata1.getVariables().get(0).getName(), is("ia"));
ArrayTypeFieldMetadata arrayTypeFieldMetadata2 = (ArrayTypeFieldMetadata)fields.get(6);
assertNotNull(arrayTypeFieldMetadata2);
assertTrue(arrayTypeFieldMetadata2.getModifiers().size() > 0);
assertThat(arrayTypeFieldMetadata2.getType(), is("Object"));
- assertThat(arrayTypeFieldMetadata2.getVariables().get(0).getName(), is("ao"));
+ assertThat(arrayTypeFieldMetadata2.getVariables().get(0).getName(), is("oa"));
- // get methods
+ // get methods (member functions)
List<MethodMetadata> methods = classMetadata.getMethods();
assertNotNull(methods);
assertTrue(methods.size() > 0);
@@ -250,6 +250,13 @@
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");
+ assertNotNull(methodTypeMemberMetadata6);
+ assertThat(methodTypeMemberMetadata6.getName(), is("doSomething2"));
+ assertTrue(methodTypeMemberMetadata6.getParameters().size() > 0);
}
}
}
15 years, 7 months
DNA SVN: r505 - in trunk/docs/gettingstarted/src/main/docbook/en-US: content and 1 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-05 16:01:49 -0400 (Fri, 05 Sep 2008)
New Revision: 505
Added:
trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_for_sequencing.xml
trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_repositories.xml
trunk/docs/gettingstarted/src/main/docbook/en-US/images/example-sequencer-client.png
Removed:
trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna.xml
trunk/docs/gettingstarted/src/main/docbook/en-US/images/example-sequencer-cli-client.png
Modified:
trunk/docs/gettingstarted/src/main/docbook/en-US/content/downloading_and_running.xml
trunk/docs/gettingstarted/src/main/docbook/en-US/master.xml
Log:
DNA-214 Update documentation to describe the repository, federation, JCR and other 0.2 features
https://jira.jboss.org/jira/browse/DNA-214
Changed the Getting Started document to add the new repository example.
Modified: trunk/docs/gettingstarted/src/main/docbook/en-US/content/downloading_and_running.xml
===================================================================
--- trunk/docs/gettingstarted/src/main/docbook/en-US/content/downloading_and_running.xml 2008-09-05 19:59:46 UTC (rev 504)
+++ trunk/docs/gettingstarted/src/main/docbook/en-US/content/downloading_and_running.xml 2008-09-05 20:01:49 UTC (rev 505)
@@ -24,7 +24,7 @@
-->
<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
<chapter id="downloading_and_running">
- <title>Running the example application</title>
+ <title>Running the example applications</title>
<para>
This chapter provides instructions for downloading and running a sample application that demonstrates how JBoss DNA works
with a JCR repository to automatically sequence changing content to extract useful information. So read on to get the simple
@@ -105,9 +105,17 @@
/resources
/test/java
/resources
+ repository/pom.xml
+ /src/main/assembly
+ /config
+ /java
+ /resources
+ /test/java
+ /resources
]]></programlisting>
- <para>There are essentially two Maven projects: a <code>sequencers</code> project and a parent project. All of the source
- for the example is located in the <code>sequencers</code> subdirectory. And you may have noticed that none
+ <para>There are essentially three Maven projects: a <code>sequencers</code> project, a <code>repository</code> project,
+ and a parent project. All of the source for the sequencing example is located in the <code>sequencers</code> subdirectory,
+ while all of the source for the federation example is located in the <code>repository</code> subdirectory. And you may have noticed that none
of the JBoss DNA libraries are there. This is where Maven comes in. The two <code>pom.xml</code> files tell
Maven everything it needs to know about what libraries are required and how to build the example.</para>
<para>In a terminal, go to the <code>examples</code> directory and run <emphasis role="strong"><code>mvn install</code></emphasis>.
@@ -136,10 +144,11 @@
<para>If there are errors, check whether you have the correct version of Maven installed and that you've correctly updated
your Maven settings as described above.</para>
<para>If you've successfully built the examples, there will be a new <code>examples/sequencers/target/</code> directory that contains
- all of the generated output, including a <code>dna-example-sequencers-basic.dir/</code> subdirectory that contains the following:
+ all of the generated output for the sequencers example, including a <code>dna-example-sequencers-basic.dir/</code> subdirectory
+ that contains the following:
<itemizedlist>
<listitem>
- <para><emphasis role="strong"><code>run.sh</code></emphasis> is the *nix shell script that will run the example.</para>
+ <para><emphasis role="strong"><code>run.sh</code></emphasis> is the *nix shell script that will run the sequencer example application.</para>
</listitem>
<listitem>
<para><emphasis role="strong"><code>log4j.properties</code></emphasis>
@@ -167,26 +176,42 @@
</para>
</listitem>
<listitem>
- <para><emphasis role="strong"><code>lib</code></emphasis>
- subdirectory contains the JARs for all of the JBoss DNA artifacts as well as those for other libraries required
- by JBoss DNA and the example.
+ <para><emphasis role="strong"><code>lib</code></emphasis> subdirectory contains the JARs for all of the JBoss DNA artifacts
+ as well as those for other libraries required by JBoss DNA and the sequencer example.
</para>
</listitem>
</itemizedlist>
- </para>
+ </para>
<note>
- <para>JBoss DNA 0.1 and the examples are currently tested with <ulink url="http://jackrabbit.apache.org/">Apache Jackrabbit</ulink> version 1.3.3.
- This version is stable and used by a number of other projects and applications. However, you should be able to use a newer
- version of Jackrabbit, as long as that version uses the same JCR API. For example, version 1.4.2 was released on March 26, 2008 and
- should be compatible.</para>
+ <para>JBoss DNA &versionNumber; and the sequencer example uses <ulink url="http://jackrabbit.apache.org/">Apache Jackrabbit</ulink> version 1.4.5.
+ This version is stable and used by a number of other projects and applications. However, you should be able to use any
+ version of Jackrabbit, as long as that version uses the same JCR API.</para>
<para>Just remember, if the version of Jackrabbit you want to use for these examples is not in the Maven repository,
you'll have to either add it or add it locally. For more information, see the <ulink url="http://maven.apache.org/">Maven documentation</ulink>.
</para>
</note>
+ <para>Similarly, the <code>examples/repository/target/</code> directory contains all of the generated output for the repository example, including
+ a <code>dna-example-repository-basic.dir/</code> subdirectory that contains the following:
+ <itemizedlist>
+ <listitem>
+ <para><emphasis role="strong"><code>run.sh</code></emphasis> is the *nix shell script that will run the repository example application.</para>
+ </listitem>
+ <listitem>
+ <para><emphasis role="strong"><code>log4j.properties</code></emphasis>
+ is the Log4J configuration file.
+ </para>
+ </listitem>
+ <listitem>
+ <para><emphasis role="strong"><code>lib</code></emphasis> subdirectory contains the JARs for all of the JBoss DNA artifacts
+ as well as those for other libraries required by JBoss DNA and the repository example.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
</sect1>
- <sect1 id="running">
- <title>Running the example</title>
- <para>This example consists of a client application that sets up an in-memory JCR repository and that allows a user to
+ <sect1 id="running_sequencer_example">
+ <title>Running the sequencing example</title>
+ <para>The sequencing example consists of a client application that sets up an in-memory JCR repository and that allows a user to
upload files into that repository. The client also sets up the DNA services with two sequencers so that if any of the
uploaded files are PNG, JPEG, GIF, BMP or other images, DNA will automatically extract the image's metadata (e.g., image
format, physical size, pixel density, etc.) and store that in the repository. Alternatively, if the uploaded file
@@ -196,8 +221,8 @@
To run the client application, go to the <code>examples/sequencers/target/dna-example-sequencers-basic.dir/</code>
directory and type <code>./run.sh</code>. You should see the command-line client and its menus in your terminal:
<figure id="xample-sequencer-cli-client">
- <title>Example Client</title>
- <graphic align="center" scale="100" fileref="example-sequencer-cli-client.png"/>
+ <title>Example client</title>
+ <graphic align="center" scale="100" fileref="example-sequencer-client.png"/>
</figure>
From this menu, you can upload a file into the repository, search for media in the repository, print sequencing statistics,
or quit the application.</para>
@@ -207,7 +232,7 @@
<code>examples/sequencers/target/dna-example-sequencers-basic.dir/</code> directory, you can specify any of the files
in that directory without specifying the path:
<figure id="example-sequencer-upload">
- <title>Uploading an image using the Example Client</title>
+ <title>Uploading an image using the example client</title>
<graphic align="center" scale="100" fileref="example-sequencer-upload.png"/>
</figure>
You can specify any fully-qualified or relative path. The application will notify you if it cannot find the file you
@@ -245,17 +270,17 @@
activities.</para>
<para>So, after the file is uploaded, you can search the repository for the image metadata using the "s" menu option:
<figure id="example-sequencer-search">
- <title>Searching for media using the Example Client</title>
+ <title>Searching for media using the example client</title>
<graphic align="center" scale="100" fileref="example-sequencer-search.png"/>
</figure>
Here are the search results after the <code>sample1.mp3</code> audio file has been uploaded (to the <code>/a/b/sample1.mp3</code> location):
<figure id="example-sequencer-search-with-mp3">
- <title>Searching for media using the Example Client</title>
+ <title>Searching for media using the example client</title>
<graphic align="center" scale="100" fileref="example-sequencer-search-with-mp3.png"/>
</figure>
You can also display the sequencing statistics using the "d" menu option:
<figure id="example-sequencer-statistics">
- <title>Sequencing statistics using the Example Client</title>
+ <title>Sequencing statistics using the example client</title>
<graphic align="center" scale="100" fileref="example-sequencer-statistics.png"/>
</figure>
These stats show how many nodes were sequenced, and how many nodes were skipped because they didn't apply to the sequencer's
@@ -268,14 +293,52 @@
<para>You can repeat this process with other files. Any file that isn't an image or MP3 files (as recognized by the sequencing configurations
that we'll describe later) will not be sequenced.</para>
</sect1>
+ <sect1 id="running_repository_example">
+ <title>Running the repository example</title>
+ <para>The repository example consists of a client application that sets up several DNA repositories, including one that
+ is a federation of several of the others, and then allows you to navigate those repositories.</para>
+ <para>
+ To run the client application, go to the <code>examples/repository/target/dna-example-repository-basic.dir/</code>
+ directory and type <code>./run.sh</code>. You should see the command-line client and its menus in your terminal:
+ <figure id="example-repository-client">
+ <title>Example Client</title>
+ <graphic align="center" scale="100" fileref="example-repository-client.png"/>
+ </figure>
+ From this menu, you can see the list of repositories, select one, and navigate through that repository in a manner similar
+ to a *nix command-line shell (although the client itself uses the JCR API to interact with the repositories).
+ Here are some of the commands you can use:</para>
+ <table frame='all'>
+ <title>Repository client commands to navigate a repository</title>
+ <tgroup cols='2' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1*"/>
+ <colspec colname='c2' colwidth="1*"/>
+ <thead>
+ <row><entry>Command</entry><entry>Description</entry></row>
+ </thead>
+ <tbody>
+ <row><entry>pwd</entry><entry>Print the path of the current node (e.g., the "working directory")</entry></row>
+ <row><entry>ls [<emphasis>path</emphasis>]</entry><entry>List the children and properties of the node at the supplied path,
+ where "<emphasis>path</emphasis>" can be any relative path or absolute path. If "<emphasis>path</emphasis>" is not supplied,
+ the current working node's path is used.</entry></row>
+ <row><entry>cd <emphasis>path</emphasis></entry><entry>Change to the specified node, where "<emphasis>path</emphasis>"
+ can be any relative path or absolute path. For example, "<code>cd alpha</code>" changes the current node to be a child named
+ "<code>alpha</code>"; "<code>cd ..</code>" changes the current node to the parent node; "<code>cd /a/b</code>" changes
+ the current node to be the "<code>/a/b</code>" node.</entry></row>
+ <row><entry>exit</entry><entry>Exit this repository and return the list of repositories.</entry></row>
+ </tbody>
+ </tgroup>
+ </table>
+ <para>Try using the client to walk the different repositories. And while this is a contrived application, it does demonstrate
+ the use of JBoss DNA to federate repositories and provide access through JCR.</para>
+ </sect1>
<sect1 id="downloading_and_running_review">
<title>Summarizing what we just did</title>
- <para>In this chapter you downloaded and installed the example application and used it to upload files into a
- JCR repository. JBoss DNA automatically sequenced the image and/or MP3 files you uploaded, extracted the metadata from the
- files, and stored that metadata inside the repository. The application allowed you to see this metadata
- and the sequencing statistics.</para>
- <para>This application was very simplistic. In fact, running through the example probably only took you a minute or two.
- So while this application won't win any awards, it does show the basics of what JBoss DNA can do.</para>
+ <para>In this chapter you downloaded, installed, and built the example applications. With the sequencer client, you could upload files into a
+ JCR repository, while JBoss DNA automatically sequenced the image, MP3, or Java source files you uploaded, extracted the metadata from the
+ files, and stored that metadata inside the repository. The repository client allowed you to walk through multiple repositories,
+ including one whose content was federated from multiple other repositories.</para>
+ <para>These example applications were very simplistic. In fact, running through the examples probably only took you a few minutes.
+ So while these applications won't win any awards, they hopefully showed you the basics of what JBoss DNA can do.</para>
<para>In the <link linkend="using_dna">next chapter</link> we'll venture into the code to get an understanding
of how JBoss DNA actually works and how you can use it in your own applications.</para>
</sect1>
Deleted: trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna.xml
===================================================================
--- trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna.xml 2008-09-05 19:59:46 UTC (rev 504)
+++ trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna.xml 2008-09-05 20:01:49 UTC (rev 505)
@@ -1,485 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ JBoss, Home of Professional Open Source.
- ~
- ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
- ~ indicated by the @author tags or express copyright attribution
- ~ statements applied by the authors. All third-party contributions are
- ~ distributed under license by Red Hat Middleware LLC.
- ~
- ~ This copyrighted material is made available to anyone wishing to use, modify,
- ~ copy, or redistribute it subject to the terms and conditions of the GNU
- ~ Lesser General Public License, as published by the Free Software Foundation.
- ~
- ~ This program is distributed in the hope that it will be useful,
- ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
- ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
- ~ for more details.
- ~
- ~ You should have received a copy of the GNU Lesser General Public License
- ~ along with this distribution; if not, write to:
- ~ Free Software Foundation, Inc.
- ~ 51 Franklin Street, Fifth Floor
- ~ Boston, MA 02110-1301 USA
- -->
-<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
-<chapter id="using_dna">
- <title>Using JBoss DNA</title>
- <para>As we've mentioned before, JBoss DNA is able to work with existing JCR repositories. Your client applications
- make changes to the information in those repositories, and JBoss DNA automatically uses its sequencers to extract
- additional information from the uploaded files.</para>
- <note>
- <para>Configuring JBoss DNA sequencers is a bit more manual than is ideal. As you'll see, JBoss DNA uses dependency
- injection to allow a great deal of flexibility in how it can be configured and customized. However, the next release will
- provide a much easier mechanism for configuring not only the sequencer service but also the upcoming federation engine and
- JCR implementation.</para>
- </note>
- <sect1 id="sequencing_service">
- <title>Configuring the Sequencing Service</title>
- <para>The JBoss DNA <emphasis>sequencing service</emphasis> is the component that manages the <emphasis>sequencers</emphasis>,
- reacting to changes in JCR repositories and then running the appropriate sequencers.
- This involves processing the changes on a node, determining which (if any) sequencers should be run on that node,
- and for each sequencer constructing the execution environment, calling the sequencer, and saving the information
- generated by the sequencer.</para>
- <para>To set up the sequencing service, an instance is created, and dependent components are injected into
- the object. This includes among other things:
- <itemizedlist>
- <listitem>
- <para>An <emphasis>execution context</emphasis> that defines the context in which the service runs, including
- a factory for JCR sessions given names of the repository and workspace. This factory must be configured,
- and is how JBoss DNA knows about your JCR repositories and how to connect to them. More on this a bit later.</para>
- </listitem>
- <listitem>
- <para>An optional <emphasis>factory for class loaders</emphasis> used to load sequencers. If no factory is supplied,
- the service uses the current thread's context class loader (or if that is null, the class loader that loaded the
- sequencing service class).</para>
- </listitem>
- <listitem>
- <para>An <code>java.util.concurrent.ExecutorService</code> used to execute the sequencing activites. If none
- is supplied, a new single-threaded executor is created by calling <code>Executors.newSingleThreadExecutor()</code>.
- (This can easily be changed by subclassing and overriding the <code>SequencerService.createDefaultExecutorService()</code> method.)</para>
- </listitem>
- <listitem>
- <para>Filters for sequencers and events. By default, all sequencers are considered for "node added", "property added"
- and "property changed" events.</para>
- </listitem>
- </itemizedlist>
- </para>
- <para>As mentioned above, the <code>ExecutionContext</code> provides access to a <code>SessionFactory</code> that is used
- by JBoss DNA to establish sessions to your JCR repositories. Two implementations are available:
- <itemizedlist>
- <listitem>
- <para>The <code>JndiSessionFactory</code> looks up JCR <code>Repository</code> instances in JNDI using
- names that are supplied when creating sessions. This implementation also has methods to set the
- JCR <code>Credentials</code> for a given workspace name.</para>
- </listitem>
- <listitem>
- <para>The <code>SimpleSessionFactory</code> has methods to register the JCR <code>Repository</code> instances
- with names, as well as methods to set the JCR <code>Credentials</code> for a given workspace name.</para>
- </listitem>
- </itemizedlist>
- You can use the <code>SimpleExecutionContext</code> implementation of <code>ExecutionContext</code> and supply
- a <code>SessionFactory</code> instance, or you can provide your own implementation.</para>
- <para>Here's an example of how to instantiate and configure the SequencingService:</para>
- <programlisting role="JAVA"><![CDATA[
-SimpleSessionFactory sessionFactory = new SimpleSessionFactory();
-sessionFactory.registerRepository("Main Repository", this.repository);
-Credentials credentials = new SimpleCredentials("jsmith", "secret".toCharArray());
-sessionFactory.registerCredentials("Main Repository/Workspace1", credentials);
-ExecutionContext executionContext = new SimpleExecutionContext(sessionFactory);
-
-// Create the sequencing service, passing in the execution context ...
-SequencingService sequencingService = new SequencingService();
-sequencingService.setExecutionContext(executionContext);
- ]]></programlisting>
- <para>After the sequencing service is created and configured, it must be started. The SequencingService
- has an <emphasis>administration object</emphasis> (that is an instance of <code>ServiceAdministrator</code>)
- with <code>start()</code>, <code>pause()</code>, and <code>shutdown()</code> methods. The latter method will
- close the queue for sequencing, but will allow sequencing operations already running to complete normally.
- To wait until all sequencing operations have completed, simply call the <code>awaitTermination</code> method
- and pass it the maximum amount of time you want to wait.</para>
- <programlisting role="JAVA"><![CDATA[sequencingService.getAdministrator().start();
-]]></programlisting>
- <para>The sequencing service must also be configured with the sequencers that it will use. This is done using the
- <code>addSequencer(SequencerConfig)</code> method and passing a <code>SequencerConfig</code> instance that
- you create. Here's an example:</para>
- <programlisting role="JAVA"><![CDATA[
-String name = "Image Sequencer";
-String desc = "Sequences image files to extract the characteristics of the image";
-String classname = "org.jboss.dna.sequencer.images.ImageMetadataSequencer";
-String[] classpath = null; // Use the current classpath
-String[] pathExpressions = {"//(*.(jpg|jpeg|gif|bmp|pcx|png)[*])/jcr:content[@jcr:data] => /images/$1"};
-SequencerConfig imageSequencerConfig = new SequencerConfig(name, desc, classname,
- classpath, pathExpressions);
-sequencingService.addSequencer(imageSequencerConfig);
-
-name = "Mp3 Sequencer";
-desc = "Sequences mp3 files to extract the id3 tags of the audio file";
-classname = "org.jboss.dna.sequencer.mp3.Mp3MetadataSequencer";
-String[] mp3PathExpressions = {"//(*.mp3[*])/jcr:content[@jcr:data] => /mp3s/$1"};
-SequencerConfig mp3SequencerConfig = new SequencerConfig(name, desc, classname,
- classpath, mp3PathExpressions);
-sequencingService.addSequencer(mp3SequencerConfig);
- ]]></programlisting>
- <para>This code fragment is pretty self-explanatory, except for the <code>classpath</code> and <code>pathExpression</code> parameters.
- The classpath parameter defines the classpath that is passed to the class loader factory mentioned above.
- Our sequencer is on the classpath, so we can simply use <code>null</code> here.</para>
- <para>The path expression is more complicated. Sequencer path expressions are used by the sequencing service to
- determine whether a particular changed node should be sequenced. The expressions consist of two parts: a selection
- criteria and an output expression:</para>
- <programlisting><![CDATA[ inputPath => outputPath ]]></programlisting>
- <para>The <emphasis>inputPath</emphasis> part defines an expression for the path that is to change and that should be sequenced.
- Input paths consist of '<code>/</code>' separated segments, where each segment represents a pattern for a single node's
- name (including the same-name-sibling indexes) and '<code>@</code>' signifies a property name.</para>
- <para>Before getting into the details, let's look at some simple examples:</para>
- <table frame='all'>
- <title>Simple Input Path Examples</title>
- <tgroup cols='2' align='left' colsep='1' rowsep='1'>
- <colspec colname='c1' colwidth="1*"/>
- <colspec colname='c2' colwidth="1*"/>
- <thead>
- <row>
- <entry>Input Path</entry>
- <entry>Description</entry>
- </row>
- </thead>
- <tbody>
- <row><entry>/a/b</entry><entry>Match node "<code>b</code>" that is a child of the top level node "<code>a</code>". Neither node
- may have any same-name-sibilings.</entry></row>
- <row><entry>/a/*</entry><entry>Match any child node of the top level node "<code>a</code>".</entry></row>
- <row><entry>/a/*.txt</entry><entry>Match any child node of the top level node "<code>a</code>" that also has a name ending in "<code>.txt</code>".</entry></row>
- <row><entry>/a/*.txt</entry><entry>Match any child node of the top level node "<code>a</code>" that also has a name ending in "<code>.txt</code>".</entry></row>
- <row><entry>/a/b@c</entry><entry>Match the property "<code>c</code>" of node "<code>/a/b</code>".</entry></row>
- <row><entry>/a/b[2]</entry><entry>The second child named "<code>b</code>" below the top level node "<code>a</code>".</entry></row>
- <row><entry>/a/b[2,3,4]</entry><entry>The second, third or fourth child named "<code>b</code>" below the top level node "<code>a</code>".</entry></row>
- <row><entry>/a/b[*]</entry><entry>Any (and every) child named "<code>b</code>" below the top level node "<code>a</code>".</entry></row>
- <row><entry>//a/b</entry><entry>Any node named "<code>b</code>" that exists below a node named "<code>a</code>", regardless
- of where node "<code>a</code>" occurs. Again, neither node may have any same-name-sibilings.</entry></row>
- </tbody>
- </tgroup>
- </table>
- <para>With these simple examples, you can probably discern the most important rules. First, the '<code>*</code>' is a wildcard character
- that matches any character or sequence of characters in a node's name (or index if appearing in between square brackets), and
- can be used in conjunction with other characters (e.g., "<code>*.txt</code>").</para>
- <para>Second, square brackets (i.e., '<code>[</code>' and '<code>]</code>') are used to match a node's same-name-sibiling index.
- You can put a single non-negative number or a comma-separated list of non-negative numbers. Use '0' to match a node that has no
- same-name-sibilings, or any positive number to match the specific same-name-sibling.</para>
- <para>Third, combining two delimiters (e.g., "<code>//</code>") matches any sequence of nodes, regardless of what their names are
- or how many nodes. Often used with other patterns to identify nodes at any level matching other patterns.
- Three or more sequential slash characters are treated as two.</para>
- <para>Many input paths can be created using just these simple rules. However, input paths can be more complicated. Here are some
- more examples:</para>
- <table frame='all'>
- <title>More Complex Input Path Examples</title>
- <tgroup cols='2' align='left' colsep='1' rowsep='1'>
- <colspec colname='c1' colwidth="1*"/>
- <colspec colname='c2' colwidth="1*"/>
- <thead>
- <row>
- <entry>Input Path</entry>
- <entry>Description</entry>
- </row>
- </thead>
- <tbody>
- <row><entry>/a/(b|c|d)</entry><entry>Match children of the top level node "<code>a</code>" that are named "<code>a</code>",
- "<code>b</code>" or "<code>c</code>". None of the nodes may have same-name-sibling indexes.</entry></row>
- <row><entry>/a/b[c/d]</entry><entry>Match node "<code>b</code>" child of the top level node "<code>a</code>", when node
- "<code>b</code>" has a child named "<code>c</code>", and "<code>c</code>" has a child named "<code>d</code>".
- Node "<code>b</code>" is the selected node, while nodes "<code>b</code>" and "<code>b</code>" are used as criteria but are not
- selected.</entry></row>
- <row><entry>/a(/(b|c|d|)/e)[f/g/@something]</entry><entry>Match node "<code>/a/b/e</code>", "<code>/a/c/e</code>", "<code>/a/d/e</code>",
- or "<code>/a/e</code>" when they also have a child "<code>f</code>" that itself has a child "<code>g</code>" with property
- "<code>something</code>". None of the nodes may have same-name-sibling indexes.</entry></row>
- </tbody>
- </tgroup>
- </table>
- <para>These examples show a few more advanced rules. Parentheses (i.e., '<code>(</code>' and '<code>)</code>') can be used
- to define a set of options for names, as shown in the first and third rules. Whatever part of the selected node's path
- appears between the parentheses is captured for use within the output path. Thus, the first input path in the previous table
- would match node "<code>/a/b</code>", and "b" would be captured and could be used within the output path using "<code>$1</code>",
- where the number used in the output path identifies the parentheses.</para>
- <para>Square brackets can also be used to specify criteria on a node's properties or children. Whatever appears in between the square
- brackets does not appear in the selected node.</para>
- <para>Let's go back to the previous code fragment and look at the first path expression:</para>
- <programlisting><![CDATA[ //(*.(jpg|jpeg|gif|bmp|pcx|png)[*])/jcr:content[@jcr:data] => /images/$1 ]]></programlisting>
- <para>This matches a node named "<code>jcr:content</code>" with property "<code>jcr:data</code>" but no siblings with the same name,
- and that is a child of a node whose name ends with "<code>.jpg</code>", "<code>.jpeg</code>", "<code>.gif</code>", "<code>.bmp</code>", "<code>.pcx</code>",
- or "<code>.png</code>" that may have any same-name-sibling index. These nodes can appear at any level in the repository.
- Note how the input path capture the filename (the segment containing the file extension), including any same-name-sibling index.
- This filename is then used in the output path, which is where the sequenced content is placed.</para>
- <para>Now that we've covered path expressions, let's get back to the <code>SequencingService</code>.
- After the service is started, it is ready to start reacting to changes in the repository. But it first
- must be wired to the repositories using a listener. This is accomplished using the <code>ObservationService</code>
- described in the <link linkend="observation_service">next section</link>.</para>
- </sect1>
- <sect1 id="observation_service">
- <title>Configuring the Observation Service</title>
- <para>The JBoss DNA <code>ObservationService</code> is responsible for listening to one or more JCR repositories
- and multiplexing the events to its listeners. Unlike JCR events, this framework embeds in the events the
- name of the repository and workspace that can be passed to a <code>SessionFactory</code> to obtain a session
- to the repository in which the change occurred. This simple design makes it very easy for JBoss DNA to
- concurrently work with multiple JCR repositories.</para>
- <para>Configuring an observation service is pretty easy, especially if you reuse the same <code>SessionFactory</code>
- supplied to the sequencing service. Here's an example:</para>
- <programlisting role="JAVA"><![CDATA[
- this.observationService = new ObservationService(sessionFactory);
- this.observationService.getAdministrator().start();
- ]]></programlisting>
- <note>
- <para>Both <code>ObservationService</code> and <code>SequencingService</code> implement
- <code>AdministeredService</code>, which has a <code>ServiceAdministrator</code> used to start, pause, and shutdown the
- service. In other words, the lifecycle of the services are managed in the same way.</para>
- </note>
- <para>After the observation service is started, listeners can be added. The <code>SequencingService</code> implements the required
- interface, and so it may be registered directly:</para>
- <programlisting role="JAVA"><![CDATA[
- observationService.addListener(sequencingService);
- ]]></programlisting>
- <para>Finally, the observation service must be wired to monitor one of your JCR repositories. This is done with
- one of the <code>monitor(...)</code> methods:</para>
- <programlisting role="JAVA"><![CDATA[
- int eventTypes = Event.NODE_ADDED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED;
- observationService.monitor("Main Repository/Workspace1", eventTypes);
- ]]></programlisting>
- <para>At this point, the observation service is listening to a JCR repository and forwarding the appropriate events
- to the sequencing service, which will asynchronously process the changes and sequence the information added to or changed in the repository.
- </para>
- </sect1>
- <sect1 id="shutting_down">
- <title>Shutting down JBoss DNA services</title>
- <para>The JBoss DNA services are utilizing resources and threads that must be released before your application is ready to shut down.
- The safe way to do this is to simply obtain the <code>ServiceAdministrator</code> for each service (via the <code>getServiceAdministrator()</code> method)
- and call <code>shutdown()</code>. As previously mentioned, the shutdown method will simply prevent new work from being processed
- and will not wait for existing work to be completed. If you want to wait until the service completes all its work, you must wait
- until the service terminates. Here's an example that shows how this is done:</para>
- <programlisting role="JAVA"><![CDATA[
-// Shut down the service and wait until it's all shut down ...
-sequencingService.getAdministrator().shutdown();
-sequencingService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
-
-// Shut down the observation service ...
-observationService.getAdministrator().shutdown();
-observationService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
- ]]></programlisting>
- <para>At this point, we've covered how to configure and use the JBoss DNA services in your application.
- The next chapter goes back to the <link linkend="downloading_and_running">sample application</link> to show how all
- these pieces fit together.</para>
- </sect1>
- <sect1 id="example_application_review">
- <title>Reviewing the example application</title>
- <para>Recall that the example application consists of a client application that sets up an in-memory JCR repository and
- that allows a user to upload files into that repository. The client also sets up the DNA services with an image sequencer so
- that if any of the uploaded files are PNG, JPEG, GIF, BMP or other images, DNA will automatically extract the image's
- metadata (e.g., image format, physical size, pixel density, etc.) and store that in the repository. Or, if the client uploads
- MP3 audio files, the title, author, album, year, and comment are extracted from the audio file and stored in the repository.</para>
- <para>
- The example is comprised of 3 classes and 1 interface, located in the <code>src/main/java</code> directory:</para>
- <programlisting><![CDATA[
- org/jboss/example/dna/sequencers/ConsoleInput.java
- /MediaInfo.java
- /SequencingClient.java
- /UserInterface.java
- ]]></programlisting>
- <para><code>SequencingClient</code> is the class that contains the main application. <code>MediaInfo</code> is a simple Java object
- that encapsulates metadata about a media file (as generated by the sequencer), and used by the client to
- pass information to the <code>UserInterface</code>, which is an interface with methods that will be called at runtime to
- request data from the user. <code>ConsoleInput</code> is an implementation of this that creates a text user interface,
- allowing the user to operate the client from the command-line. We can easily create a graphical implementation of
- <code>UserInterface</code> at a later date. We can also create a mock implementation for testing purposes that simulates
- a user entering data. This allows us to check the behavior of the client automatically using conventional JUnit test cases,
- as demonstrated by the code in the <code>src/test/java</code> directory:</para>
- <programlisting><![CDATA[
- org/jboss/example/dna/sequencers/SequencingClientTest.java
- /MockUserInterface.java
- ]]></programlisting>
- <para>If we look at the <code>SequencingClient</code> code, there are a handful of methods that encapsulate the various activities.</para>
- <note>
- <para>To keep the code shown in this book as readable as possible, some of the comments and error handling have been removed.</para>
- </note>
- <para>The <code>startRepository()</code> method starts up an in-memory Jackrabbit JCR repository. The bulk of this method is simply
- gathering and passing the information required by Jackrabbit. Because Jackrabbit's <code>TransientRepository</code>
- implementation shuts down after the last session is closed, the application maintains a session to ensure that the
- repository remains open throughout the application's lifetime. And finally, the node type needed by the image sequencer is
- registered with Jackrabbit.</para>
- <programlisting role="JAVA"><![CDATA[
-public void startRepository() throws Exception {
- if (this.repository == null) {
- try {
-
- // Load the Jackrabbit configuration ...
- File configFile = new File(this.jackrabbitConfigPath);
- String pathToConfig = configFile.getAbsolutePath();
-
- // Find the directory where the Jackrabbit repository data will be stored ...
- File workingDirectory = new File(this.workingDirectory);
- String workingDirectoryPath = workingDirectory.getAbsolutePath();
-
- // Get the Jackrabbit custom node definition (CND) file ...
- URL cndFile = Thread.currentThread().getContextClassLoader().getResource("jackrabbitNodeTypes.cnd");
-
- // Create the Jackrabbit repository instance and establish a session to keep the repository alive ...
- this.repository = new TransientRepository(pathToConfig, workingDirectoryPath);
- if (this.username != null) {
- Credentials credentials = new SimpleCredentials(this.username, this.password);
- this.keepAliveSession = this.repository.login(credentials, this.workspaceName);
- } else {
- this.keepAliveSession = this.repository.login();
- }
-
- try {
- // Register the node types (only valid the first time) ...
- Workspace workspace = this.keepAliveSession.getWorkspace();
- JackrabbitNodeTypeManager mgr = (JackrabbitNodeTypeManager)workspace.getNodeTypeManager();
- mgr.registerNodeTypes(cndFile.openStream(), JackrabbitNodeTypeManager.TEXT_X_JCR_CND);
- } catch (RepositoryException e) {
- if (!e.getMessage().contains("already exists")) throw e;
- }
-
- } catch (Exception e) {
- this.repository = null;
- this.keepAliveSession = null;
- throw e;
- }
- }
-}
- ]]></programlisting>
- <para>As you can see, this method really has nothing to do with JBoss DNA, other than setting up a JCR repository that JBoss
- DNA will use.</para>
- <para>The <code>shutdownRepository()</code> method shuts down the Jackrabbit transient repository by closing the "keep-alive session".
- Again, this method really does nothing specifically with JBoss DNA, but is needed to manage the JCR repository that JBoss DNA uses.</para>
- <programlisting role="JAVA"><![CDATA[
-public void shutdownRepository() throws Exception {
- if (this.repository != null) {
- try {
- this.keepAliveSession.logout();
- } finally {
- this.repository = null;
- this.keepAliveSession = null;
- }
- }
-}
- ]]></programlisting>
- <para>The <code>startDnaServices()</code> method first starts the JCR repository (if it was not already started), and proceeds
- to create and configure the <code>SequencingService</code> as described <link linkend="sequencing_service">earlier</link>.
- This involes setting up the <code>SessionFactory</code> and <code>ExecutionContext</code>, creating the
- <code>SequencingService</code> instance, and configuring the image sequencer. The method then continues by setting up the
- <code>ObservationService</code> as described <link linkend="observation_service">earlier</link> and starting the service.</para>
- <programlisting role="JAVA"><![CDATA[
-public void startDnaServices() throws Exception {
- if (this.repository == null) this.startRepository();
- if (this.sequencingService == null) {
-
- SimpleSessionFactory sessionFactory = new SimpleSessionFactory();
- sessionFactory.registerRepository(this.repositoryName, this.repository);
- if (this.username != null) {
- Credentials credentials = new SimpleCredentials(this.username, this.password);
- sessionFactory.registerCredentials(this.repositoryName + "/" + this.workspaceName, credentials);
- }
- this.executionContext = new SimpleExecutionContext(sessionFactory);
-
- // Create the sequencing service, passing in the execution context ...
- this.sequencingService = new SequencingService();
- this.sequencingService.setExecutionContext(executionContext);
-
- // Configure the sequencers.
- String name = "Image Sequencer";
- String desc = "Sequences image files to extract the characteristics of the image";
- String classname = "org.jboss.dna.sequencer.images.ImageMetadataSequencer";
- String[] classpath = null; // Use the current classpath
- String[] pathExpressions = {"//(*.(jpg|jpeg|gif|bmp|pcx|png|iff|ras|pbm|pgm|ppm|psd))[*]/jcr:content[@jcr:data] => /images/$1"};
- SequencerConfig imageSequencerConfig = new SequencerConfig(name, desc, classname, classpath, pathExpressions);
- this.sequencingService.addSequencer(imageSequencerConfig);
-
- // Set up the MP3 sequencer ...
- name = "Mp3 Sequencer";
- desc = "Sequences mp3 files to extract the id3 tags of the audio file";
- classname = "org.jboss.dna.sequencer.mp3.Mp3MetadataSequencer";
- String[] mp3PathExpressions = {"//(*.mp3)[*]/jcr:content[@jcr:data] => /mp3s/$1"};
- SequencerConfig mp3SequencerConfig = new SequencerConfig(name, desc, classname, classpath, mp3PathExpressions);
- this.sequencingService.addSequencer(mp3SequencerConfig);
-
- // Use the DNA observation service to listen to the JCR repository (or multiple ones), and
- // then register the sequencing service as a listener to this observation service...
- this.observationService = new ObservationService(this.executionContext.getSessionFactory());
- this.observationService.getAdministrator().start();
- this.observationService.addListener(this.sequencingService);
- this.observationService.monitor(this.repositoryName + "/" + this.workspaceName, Event.NODE_ADDED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED);
- }
- // Start up the sequencing service ...
- this.sequencingService.getAdministrator().start();
-}
- ]]></programlisting>
- <para>The <code>shutdownDnaServices()</code> method is pretty straightforward: it just calls shutdown on each of the services
- and waits until they terminate.</para>
- <programlisting role="JAVA"><![CDATA[
-public void shutdownDnaServices() throws Exception {
- if (this.sequencingService == null) return;
-
- // Shut down the service and wait until it's all shut down ...
- this.sequencingService.getAdministrator().shutdown();
- this.sequencingService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
-
- // Shut down the observation service ...
- this.observationService.getAdministrator().shutdown();
- this.observationService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
-}
- ]]></programlisting>
- <para>None of the other methods really do anything with JBoss DNA <emphasis>per se</emphasis>. Instead, they merely work with the repository
- using the JCR API.</para>
- <para>The <code>main</code> method of the <code>SequencingClient</code> class creates a <code>SequencingClient</code> instance,
- and passes a new <code>ConsoleInput</code> instance:</para>
- <programlisting role="JAVA"><![CDATA[
-public static void main( String[] args ) throws Exception {
- SequencingClient client = new SequencingClient();
- client.setRepositoryInformation("repo", "default", "jsmith", "secret".toCharArray());
- client.setUserInterface(new ConsoleInput(client));
-}
- ]]></programlisting>
- <para>If we look at the <code>ConsoleInput</code> constructor, it starts the repository, the DNA services, and a thread
- for the user interface. At this point, the constructor returns, but the main application continues under the user interface thread.
- When the user requests to quit, the user interface thread also shuts down the DNA services and JCR repository.</para>
- <programlisting role="JAVA"><![CDATA[
-public ConsoleInput( SequencerClient client ) {
- try {
- client.startRepository();
- client.startDnaServices();
-
- System.out.println(getMenu());
- Thread eventThread = new Thread(new Runnable() {
- private boolean quit = false;
- public void run() {
- try {
- while (!quit) {
- // Display the prompt and process the requested operation ...
- }
- } finally {
- try {
- // Terminate ...
- client.shutdownDnaServices();
- client.shutdownRepository();
- } catch (Exception err) {
- System.out.println("Error shutting down sequencing service and repository: "
- + err.getLocalizedMessage());
- err.printStackTrace(System.err);
- }
- }
- }
- });
- eventThread.start();
- } catch (Exception err) {
- System.out.println("Error: " + err.getLocalizedMessage());
- err.printStackTrace(System.err);
- }
-}
- ]]></programlisting>
- <para>At this point, we've reviewed all of the interesting code in the example application. However, feel free
- to play with the application, trying different things.</para>
- </sect1>
- <sect1 id="using_dna_review">
- <title>Summarizing what we just did</title>
- <para>In this chapter we covered the different JBoss DNA components and how they can be used in your application.
- Specifically, we described how the <code>SequencingService</code> and <code>ObservationService</code> can
- be configured and used. And we ended the chapter by reviewing the example application, which not only uses
- JBoss DNA, but also the repository via the JCR API.</para>
- </sect1>
-</chapter>
Copied: trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_for_sequencing.xml (from rev 499, trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna.xml)
===================================================================
--- trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_for_sequencing.xml (rev 0)
+++ trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_for_sequencing.xml 2008-09-05 20:01:49 UTC (rev 505)
@@ -0,0 +1,553 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss, Home of Professional Open Source.
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
+<chapter id="using_dna_for_sequencing">
+ <title>Using JBoss DNA for Sequencing</title>
+ <para>As we've mentioned before, JBoss DNA is able to work with existing JCR repositories. Your client applications
+ make changes to the information in those repositories, and JBoss DNA automatically uses its sequencers to extract
+ additional information from the uploaded files.</para>
+ <note>
+ <para>Configuring JBoss DNA sequencers is a bit more manual than is ideal. As you'll see, JBoss DNA uses dependency
+ injection to allow a great deal of flexibility in how it can be configured and customized. However, the next release will
+ provide a much easier mechanism for configuring the services using DNA repositories and configuration files. Current
+ plans are to use the <a href="http://www.jboss.org/jbossmc">JBoss Microcontainer</a>.</para>
+ </note>
+ <sect1 id="sequencing_service">
+ <title>Configuring the Sequencing Service</title>
+ <para>The JBoss DNA <emphasis>sequencing service</emphasis> is the component that manages the <emphasis>sequencers</emphasis>,
+ reacting to changes in JCR repositories and then running the appropriate sequencers.
+ This involves processing the changes on a node, determining which (if any) sequencers should be run on that node,
+ and for each sequencer constructing the execution environment, calling the sequencer, and saving the information
+ generated by the sequencer.</para>
+ <para>To set up the sequencing service, an instance is created, and dependent components are injected into
+ the object. This includes among other things:
+ <itemizedlist>
+ <listitem>
+ <para>An <emphasis>execution context</emphasis> that defines the context in which the service runs, including
+ a factory for JCR sessions given names of the repository and workspace. This factory must be configured,
+ and is how JBoss DNA knows about your JCR repositories and how to connect to them. More on this a bit later.</para>
+ </listitem>
+ <listitem>
+ <para>An optional <emphasis>factory for class loaders</emphasis> used to load sequencers. If no factory is supplied,
+ the service uses the current thread's context class loader (or if that is null, the class loader that loaded the
+ sequencing service class).</para>
+ </listitem>
+ <listitem>
+ <para>An <code>java.util.concurrent.ExecutorService</code> used to execute the sequencing activites. If none
+ is supplied, a new single-threaded executor is created by calling <code>Executors.newSingleThreadExecutor()</code>.
+ (This can easily be changed by subclassing and overriding the <code>SequencerService.createDefaultExecutorService()</code> method.)</para>
+ </listitem>
+ <listitem>
+ <para>Filters for sequencers and events. By default, all sequencers are considered for "node added", "property added"
+ and "property changed" events.</para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>As mentioned above, the <code>ExecutionContext</code> provides access to a <code>SessionFactory</code> that is used
+ by JBoss DNA to establish sessions to your JCR repositories. Two implementations are available:
+ <itemizedlist>
+ <listitem>
+ <para>The <code>JndiSessionFactory</code> looks up JCR <code>Repository</code> instances in JNDI using
+ names that are supplied when creating sessions. This implementation also has methods to set the
+ JCR <code>Credentials</code> for a given workspace name.</para>
+ </listitem>
+ <listitem>
+ <para>The <code>SimpleSessionFactory</code> has methods to register the JCR <code>Repository</code> instances
+ with names, as well as methods to set the JCR <code>Credentials</code> for a given workspace name.</para>
+ </listitem>
+ </itemizedlist>
+ You can use the <code>SimpleExecutionContext</code> implementation of <code>ExecutionContext</code> and supply
+ a <code>SessionFactory</code> instance, or you can provide your own implementation.</para>
+ <para>Here's an example of how to instantiate and configure the SequencingService:</para>
+ <programlisting role="JAVA"><![CDATA[
+SimpleSessionFactory sessionFactory = new SimpleSessionFactory();
+sessionFactory.registerRepository("Main Repository", this.repository);
+Credentials credentials = new SimpleCredentials("jsmith", "secret".toCharArray());
+sessionFactory.registerCredentials("Main Repository/Workspace1", credentials);
+ExecutionContext executionContext = new SimpleExecutionContext(sessionFactory);
+
+// Create the sequencing service, passing in the execution context ...
+SequencingService sequencingService = new SequencingService();
+sequencingService.setExecutionContext(executionContext);
+ ]]></programlisting>
+ <para>After the sequencing service is created and configured, it must be started. The SequencingService
+ has an <emphasis>administration object</emphasis> (that is an instance of <code>ServiceAdministrator</code>)
+ with <code>start()</code>, <code>pause()</code>, and <code>shutdown()</code> methods. The latter method will
+ close the queue for sequencing, but will allow sequencing operations already running to complete normally.
+ To wait until all sequencing operations have completed, simply call the <code>awaitTermination</code> method
+ and pass it the maximum amount of time you want to wait.</para>
+ <programlisting role="JAVA"><![CDATA[sequencingService.getAdministrator().start();
+]]></programlisting>
+ <para>The sequencing service must also be configured with the sequencers that it will use. This is done using the
+ <code>addSequencer(SequencerConfig)</code> method and passing a <code>SequencerConfig</code> instance that
+ you create. Here's the code that defines 3 sequencer configurations: 1 that places image metadata into
+ "<code><![CDATA[/images/<filename>]]></code>", another that places MP3 metadata into "<code><![CDATA[/mp3s/<filename>]]></code>",
+ and a third that places a structure that represents the classes, methods, and attributes found within Java source into
+ "<code><![CDATA[/java/<filename>]]></code>".</para>
+ <programlisting role="JAVA"><![CDATA[
+String name = "Image Sequencer";
+String desc = "Sequences image files to extract the characteristics of the image";
+String classname = "org.jboss.dna.sequencer.images.ImageMetadataSequencer";
+String[] classpath = null; // Use the current classpath
+String[] pathExpressions = {"//(*.(jpg|jpeg|gif|bmp|pcx|png)[*])/jcr:content[@jcr:data] => /images/$1"};
+SequencerConfig imageSequencerConfig = new SequencerConfig(name, desc, classname,
+ classpath, pathExpressions);
+sequencingService.addSequencer(imageSequencerConfig);
+
+name = "Mp3 Sequencer";
+desc = "Sequences mp3 files to extract the id3 tags of the audio file";
+classname = "org.jboss.dna.sequencer.mp3.Mp3MetadataSequencer";
+pathExpressions = {"//(*.mp3[*])/jcr:content[@jcr:data] => /mp3s/$1"};
+SequencerConfig mp3SequencerConfig = new SequencerConfig(name, desc, classname,
+ classpath, pathExpressions);
+sequencingService.addSequencer(mp3SequencerConfig);
+
+name = "Java Sequencer";
+desc = "Sequences java files to extract the characteristics of the Java source";
+classname = "org.jboss.dna.sequencer.java.JavaMetadataSequencer";
+pathExpressions = {"//(*.java[*])/jcr:content[@jcr:data] => /java/$1"};
+SequencerConfig javaSequencerConfig = new SequencerConfig(name, desc, classname,
+ classpath, pathExpressions);
+this.sequencingService.addSequencer(javaSequencerConfig);
+ ]]></programlisting>
+ <para>Each configuration defines several things, including the name, description, and sequencer implementation class.
+ The configuration also defines the classpath information, which can be passed to the class loader factory to get
+ a Java classloader with which the sequencer class can be loaded. (If no classpath information is provided, as is done
+ in the code above, the application class loader is used.) The configuration also specifies the path expressions that
+ identify the nodes that should be sequenced with the sequencer and where to store the output generated by the sequencer.
+ Path expressions are pretty straightforward but are quite powerful, so before we go any further with the example,
+ let's dive into path expressions in more detail.</para>
+ <sect2 id="path_expressions">
+ <title>Path Expressions</title>
+ <para>Path expressions consist of two parts: a selection criteria (or an input path) and an output path:</para>
+ <programlisting><![CDATA[ inputPath => outputPath ]]></programlisting>
+ <para>The <emphasis>inputPath</emphasis> part defines an expression for the path of a node that is to be sequenced.
+ Input paths consist of '<code>/</code>' separated segments, where each segment represents a pattern for a single node's
+ name (including the same-name-sibling indexes) and '<code>@</code>' signifies a property name.</para>
+ <para>Let's first look at some simple examples:</para>
+ <table frame='all'>
+ <title>Simple Input Path Examples</title>
+ <tgroup cols='2' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1*"/>
+ <colspec colname='c2' colwidth="1*"/>
+ <thead>
+ <row>
+ <entry>Input Path</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row><entry>/a/b</entry><entry>Match node "<code>b</code>" that is a child of the top level node "<code>a</code>". Neither node
+ may have any same-name-sibilings.</entry></row>
+ <row><entry>/a/*</entry><entry>Match any child node of the top level node "<code>a</code>".</entry></row>
+ <row><entry>/a/*.txt</entry><entry>Match any child node of the top level node "<code>a</code>" that also has a name ending in "<code>.txt</code>".</entry></row>
+ <row><entry>/a/*.txt</entry><entry>Match any child node of the top level node "<code>a</code>" that also has a name ending in "<code>.txt</code>".</entry></row>
+ <row><entry>/a/b@c</entry><entry>Match the property "<code>c</code>" of node "<code>/a/b</code>".</entry></row>
+ <row><entry>/a/b[2]</entry><entry>The second child named "<code>b</code>" below the top level node "<code>a</code>".</entry></row>
+ <row><entry>/a/b[2,3,4]</entry><entry>The second, third or fourth child named "<code>b</code>" below the top level node "<code>a</code>".</entry></row>
+ <row><entry>/a/b[*]</entry><entry>Any (and every) child named "<code>b</code>" below the top level node "<code>a</code>".</entry></row>
+ <row><entry>//a/b</entry><entry>Any node named "<code>b</code>" that exists below a node named "<code>a</code>", regardless
+ of where node "<code>a</code>" occurs. Again, neither node may have any same-name-sibilings.</entry></row>
+ </tbody>
+ </tgroup>
+ </table>
+ <para>With these simple examples, you can probably discern the most important rules. First, the '<code>*</code>' is a wildcard character
+ that matches any character or sequence of characters in a node's name (or index if appearing in between square brackets), and
+ can be used in conjunction with other characters (e.g., "<code>*.txt</code>").</para>
+ <para>Second, square brackets (i.e., '<code>[</code>' and '<code>]</code>') are used to match a node's same-name-sibiling index.
+ You can put a single non-negative number or a comma-separated list of non-negative numbers. Use '0' to match a node that has no
+ same-name-sibilings, or any positive number to match the specific same-name-sibling.</para>
+ <para>Third, combining two delimiters (e.g., "<code>//</code>") matches any sequence of nodes, regardless of what their names are
+ or how many nodes. Often used with other patterns to identify nodes at any level matching other patterns.
+ Three or more sequential slash characters are treated as two.</para>
+ <para>Many input paths can be created using just these simple rules. However, input paths can be more complicated. Here are some
+ more examples:</para>
+ <table frame='all'>
+ <title>More Complex Input Path Examples</title>
+ <tgroup cols='2' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1*"/>
+ <colspec colname='c2' colwidth="1*"/>
+ <thead>
+ <row>
+ <entry>Input Path</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row><entry>/a/(b|c|d)</entry><entry>Match children of the top level node "<code>a</code>" that are named "<code>a</code>",
+ "<code>b</code>" or "<code>c</code>". None of the nodes may have same-name-sibling indexes.</entry></row>
+ <row><entry>/a/b[c/d]</entry><entry>Match node "<code>b</code>" child of the top level node "<code>a</code>", when node
+ "<code>b</code>" has a child named "<code>c</code>", and "<code>c</code>" has a child named "<code>d</code>".
+ Node "<code>b</code>" is the selected node, while nodes "<code>b</code>" and "<code>b</code>" are used as criteria but are not
+ selected.</entry></row>
+ <row><entry>/a(/(b|c|d|)/e)[f/g/@something]</entry><entry>Match node "<code>/a/b/e</code>", "<code>/a/c/e</code>", "<code>/a/d/e</code>",
+ or "<code>/a/e</code>" when they also have a child "<code>f</code>" that itself has a child "<code>g</code>" with property
+ "<code>something</code>". None of the nodes may have same-name-sibling indexes.</entry></row>
+ </tbody>
+ </tgroup>
+ </table>
+ <para>These examples show a few more advanced rules. Parentheses (i.e., '<code>(</code>' and '<code>)</code>') can be used
+ to define a set of options for names, as shown in the first and third rules. Whatever part of the selected node's path
+ appears between the parentheses is captured for use within the output path. Thus, the first input path in the previous table
+ would match node "<code>/a/b</code>", and "b" would be captured and could be used within the output path using "<code>$1</code>",
+ where the number used in the output path identifies the parentheses.</para>
+ <para>Square brackets can also be used to specify criteria on a node's properties or children. Whatever appears in between the square
+ brackets does not appear in the selected node.</para>
+ <para>Let's go back to the previous code fragment and look at the first path expression:</para>
+ <programlisting><![CDATA[ //(*.(jpg|jpeg|gif|bmp|pcx|png)[*])/jcr:content[@jcr:data] => /images/$1 ]]></programlisting>
+ <para>This matches a node named "<code>jcr:content</code>" with property "<code>jcr:data</code>" but no siblings with the same name,
+ and that is a child of a node whose name ends with "<code>.jpg</code>", "<code>.jpeg</code>", "<code>.gif</code>", "<code>.bmp</code>", "<code>.pcx</code>",
+ or "<code>.png</code>" that may have any same-name-sibling index. These nodes can appear at any level in the repository.
+ Note how the input path capture the filename (the segment containing the file extension), including any same-name-sibling index.
+ This filename is then used in the output path, which is where the sequenced content is placed.</para>
+ </sect2>
+ <sect2 id="path_expressions_in_example">
+ <title>Path Expressions Used in the Example</title>
+ <para>Now that we've covered path expressions, let's go back to the three sequencer configuration in the example.
+ Here they are again, with a description of what each path means:</para>
+ <table frame='all'>
+ <title>Path Expressions for the 3 Sequencers</title>
+ <tgroup cols='3' align='left' colsep='1' rowsep='1'>
+ <colspec colname='c1' colwidth="1*"/>
+ <colspec colname='c2' colwidth="1*"/>
+ <colspec colname='c2' colwidth="1*"/>
+ <thead>
+ <row>
+ <entry>Input Path</entry>
+ <entry>Output Path</entry>
+ <entry>Description</entry>
+ </row>
+ </thead>
+ <tbody>
+ <row>
+ <entry><![CDATA[//(*.(jpg|jpeg|gif|bmp|pcx|png)[*])/jcr:content[@jcr:data]]]></entry>
+ <entry><![CDATA[/images/$1]]></entry>
+ <entry>Any node with a name ending in "<code>.jpg</code>", "<code>.jpeg</code>", "<code>.gif</code>", "<code>.bmp</code>",
+ "<code>.pcx</code>", or "<code>.png</code>", whether or not it has a same-name-sibling index, but that has a child named
+ "<code>jcr:content</code>" with "<code>jcr:data</code>" property. The node name representing the filename (including any
+ same-name-sibling index) is captured, and used to place the output in "<code><![CDATA[/images/<filename>]]></code>".</entry>
+ </row>
+ <row>
+ <entry><![CDATA[//(*.mp3[*])/jcr:content[@jcr:data]]]></entry>
+ <entry><![CDATA[/mp3s/$1]]></entry>
+ <entry>Any node with a name ending in "<code>.mp3</code>", whether or not it has a same-name-sibling index, but that has a child named
+ "<code>jcr:content</code>" with "<code>jcr:data</code>" property. The node name representing the filename (including any
+ same-name-sibling index) is captured, and used to place the output in "<code><![CDATA[/mp3s/<filename>]]></code>".</entry>
+ </row>
+ <row>
+ <entry><![CDATA[//(*.java[*])/jcr:content[@jcr:data]]]></entry>
+ <entry><![CDATA[/java/$1]]></entry>
+ <entry>Any node with a name ending in "<code>.java</code>", whether or not it has a same-name-sibling index, but that has a child named
+ "<code>jcr:content</code>" with "<code>jcr:data</code>" property. The node name representing the filename (including any
+ same-name-sibling index) is captured, and used to place the output in "<code><![CDATA[/java/<filename>]]></code>".</entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </table>
+ <para>After these sequencer configurations are defined and added to the <code>SequencingService</code>,
+ the service is now ready to start reacting to changes in the repository and automatically looking for nodes to sequence.
+ But we first need to wire the service into the repository to receive those change events.
+ This is accomplished using the <code>ObservationService</code>
+ described in the <link linkend="observation_service">next section</link>.</para>
+ </sect2>
+ </sect1>
+ <sect1 id="observation_service">
+ <title>Configuring the Observation Service</title>
+ <para>The JBoss DNA <code>ObservationService</code> is responsible for listening to one or more JCR repositories
+ and multiplexing the events to its listeners. Unlike JCR events, this framework embeds in the events the
+ name of the repository and workspace that can be passed to a <code>SessionFactory</code> to obtain a session
+ to the repository in which the change occurred. This simple design makes it very easy for JBoss DNA to
+ concurrently work with multiple JCR repositories.</para>
+ <para>Configuring an observation service is pretty easy, especially if you reuse the same <code>SessionFactory</code>
+ supplied to the sequencing service. Here's an example:</para>
+ <programlisting role="JAVA"><![CDATA[
+ this.observationService = new ObservationService(sessionFactory);
+ this.observationService.getAdministrator().start();
+ ]]></programlisting>
+ <note>
+ <para>Both <code>ObservationService</code> and <code>SequencingService</code> implement
+ <code>AdministeredService</code>, which has a <code>ServiceAdministrator</code> used to start, pause, and shutdown the
+ service. In other words, the lifecycle of the services are managed in the same way.</para>
+ </note>
+ <para>After the observation service is started, listeners can be added. The <code>SequencingService</code> implements the required
+ interface, and so it may be registered directly:</para>
+ <programlisting role="JAVA"><![CDATA[
+ observationService.addListener(sequencingService);
+ ]]></programlisting>
+ <para>Finally, the observation service must be wired to monitor one of your JCR repositories. This is done with
+ one of the <code>monitor(...)</code> methods:</para>
+ <programlisting role="JAVA"><![CDATA[
+ int eventTypes = Event.NODE_ADDED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED;
+ observationService.monitor("Main Repository/Workspace1", eventTypes);
+ ]]></programlisting>
+ <para>At this point, the observation service is listening to a JCR repository and forwarding the appropriate events
+ to the sequencing service, which will asynchronously process the changes and sequence the information added to or changed in the repository.
+ </para>
+ </sect1>
+ <sect1 id="shutting_down">
+ <title>Shutting down JBoss DNA services</title>
+ <para>The JBoss DNA services are utilizing resources and threads that must be released before your application is ready to shut down.
+ The safe way to do this is to simply obtain the <code>ServiceAdministrator</code> for each service (via the <code>getServiceAdministrator()</code> method)
+ and call <code>shutdown()</code>. As previously mentioned, the shutdown method will simply prevent new work from being processed
+ and will not wait for existing work to be completed. If you want to wait until the service completes all its work, you must wait
+ until the service terminates. Here's an example that shows how this is done:</para>
+ <programlisting role="JAVA"><![CDATA[
+// Shut down the service and wait until it's all shut down ...
+sequencingService.getAdministrator().shutdown();
+sequencingService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
+
+// Shut down the observation service ...
+observationService.getAdministrator().shutdown();
+observationService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
+ ]]></programlisting>
+ <para>At this point, we've covered how to configure and use the JBoss DNA services in your application.
+ The next chapter goes back to the <link linkend="downloading_and_running">sample application</link> to show how all
+ these pieces fit together.</para>
+ </sect1>
+ <sect1 id="example_application_review">
+ <title>Reviewing the example application</title>
+ <para>Recall that the example application consists of a client application that sets up an in-memory JCR repository and
+ that allows a user to upload files into that repository. The client also sets up the DNA services with an image sequencer so
+ that if any of the uploaded files are PNG, JPEG, GIF, BMP or other images, DNA will automatically extract the image's
+ metadata (e.g., image format, physical size, pixel density, etc.) and store that in the repository. Or, if the client uploads
+ MP3 audio files, the title, author, album, year, and comment are extracted from the audio file and stored in the repository.</para>
+ <para>
+ The example is comprised of 3 classes and 1 interface, located in the <code>src/main/java</code> directory:</para>
+ <programlisting><![CDATA[
+ org/jboss/example/dna/sequencers/ConsoleInput.java
+ /MediaInfo.java
+ /SequencingClient.java
+ /UserInterface.java
+ ]]></programlisting>
+ <para><code>SequencingClient</code> is the class that contains the main application. <code>MediaInfo</code> is a simple Java object
+ that encapsulates metadata about a media file (as generated by the sequencer), and used by the client to
+ pass information to the <code>UserInterface</code>, which is an interface with methods that will be called at runtime to
+ request data from the user. <code>ConsoleInput</code> is an implementation of this that creates a text user interface,
+ allowing the user to operate the client from the command-line. We can easily create a graphical implementation of
+ <code>UserInterface</code> at a later date. We can also create a mock implementation for testing purposes that simulates
+ a user entering data. This allows us to check the behavior of the client automatically using conventional JUnit test cases,
+ as demonstrated by the code in the <code>src/test/java</code> directory:</para>
+ <programlisting><![CDATA[
+ org/jboss/example/dna/sequencers/SequencingClientTest.java
+ /MockUserInterface.java
+ ]]></programlisting>
+ <para>If we look at the <code>SequencingClient</code> code, there are a handful of methods that encapsulate the various activities.</para>
+ <note>
+ <para>To keep the code shown in this book as readable as possible, some of the comments and error handling have been removed.</para>
+ </note>
+ <para>The <code>startRepository()</code> method starts up an in-memory Jackrabbit JCR repository. The bulk of this method is simply
+ gathering and passing the information required by Jackrabbit. Because Jackrabbit's <code>TransientRepository</code>
+ implementation shuts down after the last session is closed, the application maintains a session to ensure that the
+ repository remains open throughout the application's lifetime. And finally, the node type needed by the image sequencer is
+ registered with Jackrabbit.</para>
+ <programlisting role="JAVA"><![CDATA[
+public void startRepository() throws Exception {
+ if (this.repository == null) {
+ try {
+
+ // Load the Jackrabbit configuration ...
+ File configFile = new File(this.jackrabbitConfigPath);
+ String pathToConfig = configFile.getAbsolutePath();
+
+ // Find the directory where the Jackrabbit repository data will be stored ...
+ File workingDirectory = new File(this.workingDirectory);
+ String workingDirectoryPath = workingDirectory.getAbsolutePath();
+
+ // Get the Jackrabbit custom node definition (CND) file ...
+ URL cndFile = Thread.currentThread().getContextClassLoader().getResource("jackrabbitNodeTypes.cnd");
+
+ // Create the Jackrabbit repository instance and establish a session to keep the repository alive ...
+ this.repository = new TransientRepository(pathToConfig, workingDirectoryPath);
+ if (this.username != null) {
+ Credentials credentials = new SimpleCredentials(this.username, this.password);
+ this.keepAliveSession = this.repository.login(credentials, this.workspaceName);
+ } else {
+ this.keepAliveSession = this.repository.login();
+ }
+
+ try {
+ // Register the node types (only valid the first time) ...
+ Workspace workspace = this.keepAliveSession.getWorkspace();
+ JackrabbitNodeTypeManager mgr = (JackrabbitNodeTypeManager)workspace.getNodeTypeManager();
+ mgr.registerNodeTypes(cndFile.openStream(), JackrabbitNodeTypeManager.TEXT_X_JCR_CND);
+ } catch (RepositoryException e) {
+ if (!e.getMessage().contains("already exists")) throw e;
+ }
+
+ } catch (Exception e) {
+ this.repository = null;
+ this.keepAliveSession = null;
+ throw e;
+ }
+ }
+}
+ ]]></programlisting>
+ <para>As you can see, this method really has nothing to do with JBoss DNA, other than setting up a JCR repository that JBoss
+ DNA will use.</para>
+ <para>The <code>shutdownRepository()</code> method shuts down the Jackrabbit transient repository by closing the "keep-alive session".
+ Again, this method really does nothing specifically with JBoss DNA, but is needed to manage the JCR repository that JBoss DNA uses.</para>
+ <programlisting role="JAVA"><![CDATA[
+public void shutdownRepository() throws Exception {
+ if (this.repository != null) {
+ try {
+ this.keepAliveSession.logout();
+ } finally {
+ this.repository = null;
+ this.keepAliveSession = null;
+ }
+ }
+}
+ ]]></programlisting>
+ <para>The <code>startDnaServices()</code> method first starts the JCR repository (if it was not already started), and proceeds
+ to create and configure the <code>SequencingService</code> as described <link linkend="sequencing_service">earlier</link>.
+ This involes setting up the <code>SessionFactory</code> and <code>ExecutionContext</code>, creating the
+ <code>SequencingService</code> instance, and configuring the image sequencer. The method then continues by setting up the
+ <code>ObservationService</code> as described <link linkend="observation_service">earlier</link> and starting the service.</para>
+ <programlisting role="JAVA"><![CDATA[
+public void startDnaServices() throws Exception {
+ if (this.repository == null) this.startRepository();
+ if (this.sequencingService == null) {
+
+ SimpleSessionFactory sessionFactory = new SimpleSessionFactory();
+ sessionFactory.registerRepository(this.repositoryName, this.repository);
+ if (this.username != null) {
+ Credentials credentials = new SimpleCredentials(this.username, this.password);
+ sessionFactory.registerCredentials(this.repositoryName + "/" + this.workspaceName, credentials);
+ }
+ this.executionContext = new SimpleExecutionContext(sessionFactory);
+
+ // Create the sequencing service, passing in the execution context ...
+ this.sequencingService = new SequencingService();
+ this.sequencingService.setExecutionContext(executionContext);
+
+ // Configure the sequencers.
+ String name = "Image Sequencer";
+ String desc = "Sequences image files to extract the characteristics of the image";
+ String classname = "org.jboss.dna.sequencer.images.ImageMetadataSequencer";
+ String[] classpath = null; // Use the current classpath
+ String[] pathExpressions = {"//(*.(jpg|jpeg|gif|bmp|pcx|png|iff|ras|pbm|pgm|ppm|psd))[*]/jcr:content[@jcr:data] => /images/$1"};
+ SequencerConfig imageSequencerConfig = new SequencerConfig(name, desc, classname, classpath, pathExpressions);
+ this.sequencingService.addSequencer(imageSequencerConfig);
+
+ // Set up the MP3 sequencer ...
+ name = "Mp3 Sequencer";
+ desc = "Sequences mp3 files to extract the id3 tags of the audio file";
+ classname = "org.jboss.dna.sequencer.mp3.Mp3MetadataSequencer";
+ pathExpressions = {"//(*.mp3)[*]/jcr:content[@jcr:data] => /mp3s/$1"};
+ SequencerConfig mp3SequencerConfig = new SequencerConfig(name, desc, classname, classpath, pathExpressions);
+ this.sequencingService.addSequencer(mp3SequencerConfig);
+
+ name = "Java Sequencer";
+ desc = "Sequences java files to extract the characteristics of the Java source";
+ classname = "org.jboss.dna.sequencer.java.JavaMetadataSequencer";
+ pathExpressions = {"//(*.java[*])/jcr:content[@jcr:data] => /java/$1"};
+ SequencerConfig javaSequencerConfig = new SequencerConfig(name, desc, classname,classpath, pathExpressions);
+ this.sequencingService.addSequencer(javaSequencerConfig);
+
+ // Use the DNA observation service to listen to the JCR repository (or multiple ones), and
+ // then register the sequencing service as a listener to this observation service...
+ this.observationService = new ObservationService(this.executionContext.getSessionFactory());
+ this.observationService.getAdministrator().start();
+ this.observationService.addListener(this.sequencingService);
+ this.observationService.monitor(this.repositoryName + "/" + this.workspaceName, Event.NODE_ADDED | Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED);
+ }
+ // Start up the sequencing service ...
+ this.sequencingService.getAdministrator().start();
+}
+ ]]></programlisting>
+ <para>The <code>shutdownDnaServices()</code> method is pretty straightforward: it just calls shutdown on each of the services
+ and waits until they terminate.</para>
+ <programlisting role="JAVA"><![CDATA[
+public void shutdownDnaServices() throws Exception {
+ if (this.sequencingService == null) return;
+
+ // Shut down the service and wait until it's all shut down ...
+ this.sequencingService.getAdministrator().shutdown();
+ this.sequencingService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
+
+ // Shut down the observation service ...
+ this.observationService.getAdministrator().shutdown();
+ this.observationService.getAdministrator().awaitTermination(5, TimeUnit.SECONDS);
+}
+ ]]></programlisting>
+ <para>None of the other methods really do anything with JBoss DNA <emphasis>per se</emphasis>. Instead, they merely work with the repository
+ using the JCR API.</para>
+ <para>The <code>main</code> method of the <code>SequencingClient</code> class creates a <code>SequencingClient</code> instance,
+ and passes a new <code>ConsoleInput</code> instance:</para>
+ <programlisting role="JAVA"><![CDATA[
+public static void main( String[] args ) throws Exception {
+ SequencingClient client = new SequencingClient();
+ client.setRepositoryInformation("repo", "default", "jsmith", "secret".toCharArray());
+ client.setUserInterface(new ConsoleInput(client));
+}
+ ]]></programlisting>
+ <para>If we look at the <code>ConsoleInput</code> constructor, it starts the repository, the DNA services, and a thread
+ for the user interface. At this point, the constructor returns, but the main application continues under the user interface thread.
+ When the user requests to quit, the user interface thread also shuts down the DNA services and JCR repository.</para>
+ <programlisting role="JAVA"><![CDATA[
+public ConsoleInput( SequencerClient client ) {
+ try {
+ client.startRepository();
+ client.startDnaServices();
+
+ System.out.println(getMenu());
+ Thread eventThread = new Thread(new Runnable() {
+ private boolean quit = false;
+ public void run() {
+ try {
+ while (!quit) {
+ // Display the prompt and process the requested operation ...
+ }
+ } finally {
+ try {
+ // Terminate ...
+ client.shutdownDnaServices();
+ client.shutdownRepository();
+ } catch (Exception err) {
+ System.out.println("Error shutting down sequencing service and repository: "
+ + err.getLocalizedMessage());
+ err.printStackTrace(System.err);
+ }
+ }
+ }
+ });
+ eventThread.start();
+ } catch (Exception err) {
+ System.out.println("Error: " + err.getLocalizedMessage());
+ err.printStackTrace(System.err);
+ }
+}
+ ]]></programlisting>
+ <para>At this point, we've reviewed all of the interesting code in the example application. However, feel free
+ to play with the application, trying different things.</para>
+ </sect1>
+ <sect1 id="using_dna_review">
+ <title>Summarizing what we just did</title>
+ <para>In this chapter we covered the different JBoss DNA components and how they can be used in your application.
+ Specifically, we described how the <code>SequencingService</code> and <code>ObservationService</code> can
+ be configured and used. And we ended the chapter by reviewing the example application, which not only uses
+ JBoss DNA, but also the repository via the JCR API.</para>
+ </sect1>
+</chapter>
Added: trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_repositories.xml
===================================================================
--- trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_repositories.xml (rev 0)
+++ trunk/docs/gettingstarted/src/main/docbook/en-US/content/using_dna_repositories.xml 2008-09-05 20:01:49 UTC (rev 505)
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ JBoss, Home of Professional Open Source.
+ ~
+ ~ Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ ~ indicated by the @author tags or express copyright attribution
+ ~ statements applied by the authors. All third-party contributions are
+ ~ distributed under license by Red Hat Middleware LLC.
+ ~
+ ~ This copyrighted material is made available to anyone wishing to use, modify,
+ ~ copy, or redistribute it subject to the terms and conditions of the GNU
+ ~ Lesser General Public License, as published by the Free Software Foundation.
+ ~
+ ~ This program is distributed in the hope that it will be useful,
+ ~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ ~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
+ ~ for more details.
+ ~
+ ~ You should have received a copy of the GNU Lesser General Public License
+ ~ along with this distribution; if not, write to:
+ ~ Free Software Foundation, Inc.
+ ~ 51 Franklin Street, Fifth Floor
+ ~ Boston, MA 02110-1301 USA
+ -->
+<!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd">
+<chapter id="using_dna_repositories">
+ <title>Using JBoss DNA Repositories</title>
+ <para>As we've mentioned before, one of the capabilities of JBoss DNA is to provide access through JCR to different kinds
+ of repositories. You're applications work with the JCR API, but JBoss DNA accesses the content from the underlying systems,
+ including able to work with existing JCR repositories.</para>
+</chapter>
+
Deleted: trunk/docs/gettingstarted/src/main/docbook/en-US/images/example-sequencer-cli-client.png
===================================================================
(Binary files differ)
Copied: trunk/docs/gettingstarted/src/main/docbook/en-US/images/example-sequencer-client.png (from rev 497, trunk/docs/gettingstarted/src/main/docbook/en-US/images/example-sequencer-cli-client.png)
===================================================================
(Binary files differ)
Modified: trunk/docs/gettingstarted/src/main/docbook/en-US/master.xml
===================================================================
--- trunk/docs/gettingstarted/src/main/docbook/en-US/master.xml 2008-09-05 19:59:46 UTC (rev 504)
+++ trunk/docs/gettingstarted/src/main/docbook/en-US/master.xml 2008-09-05 20:01:49 UTC (rev 505)
@@ -53,7 +53,8 @@
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/introduction.xml"/>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/understanding_dna.xml"/>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/downloading_and_running.xml"/>
- <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/using_dna.xml"/>
+ <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/using_dna_for_sequencing.xml"/>
+ <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/using_dna_repositories.xml"/>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/custom_sequencers.xml"/>
<xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="content/future.xml"/>
</book>
15 years, 7 months
DNA SVN: r504 - in trunk/docs/examples/gettingstarted: repositories and 12 other directories.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-05 15:59:46 -0400 (Fri, 05 Sep 2008)
New Revision: 504
Added:
trunk/docs/examples/gettingstarted/repositories/
trunk/docs/examples/gettingstarted/repositories/.classpath
trunk/docs/examples/gettingstarted/repositories/.project
trunk/docs/examples/gettingstarted/repositories/pom.xml
trunk/docs/examples/gettingstarted/repositories/src/
trunk/docs/examples/gettingstarted/repositories/src/main/
trunk/docs/examples/gettingstarted/repositories/src/main/assembly/
trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml
trunk/docs/examples/gettingstarted/repositories/src/main/config/
trunk/docs/examples/gettingstarted/repositories/src/main/config/run.sh
trunk/docs/examples/gettingstarted/repositories/src/main/java/
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/
trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
trunk/docs/examples/gettingstarted/repositories/src/main/resources/
trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties
trunk/docs/examples/gettingstarted/repositories/src/test/
trunk/docs/examples/gettingstarted/repositories/src/test/java/
trunk/docs/examples/gettingstarted/repositories/src/test/resources/
Log:
DNA-214 Update documentation to describe the repository, federation, JCR and other 0.2 features
https://jira.jboss.org/jira/browse/DNA-214
Added the start of an example repository client.
Property changes on: trunk/docs/examples/gettingstarted/repositories
___________________________________________________________________
Name: svn:ignore
+ target
Added: trunk/docs/examples/gettingstarted/repositories/.classpath
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/.classpath (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/.classpath 2008-09-05 19:59:46 UTC (rev 504)
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src/main/java"/>
+ <classpathentry kind="src" path="src/main/resources"/>
+ <classpathentry kind="src" output="target/test-classes" path="src/test/java"/>
+ <classpathentry kind="src" output="target/test-classes" path="src/test/resources"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
+ <classpathentry kind="output" path="target/classes"/>
+</classpath>
Added: trunk/docs/examples/gettingstarted/repositories/.project
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/.project (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/.project 2008-09-05 19:59:46 UTC (rev 504)
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>docs-getting-started-examples-repositories</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.maven.ide.eclipse.maven2Builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.maven.ide.eclipse.maven2Nature</nature>
+ </natures>
+</projectDescription>
Added: trunk/docs/examples/gettingstarted/repositories/pom.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/pom.xml (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/pom.xml 2008-09-05 19:59:46 UTC (rev 504)
@@ -0,0 +1,107 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <parent>
+ <groupId>org.jboss.dna.examples</groupId>
+ <artifactId>getting_started</artifactId>
+ <version>0.2-SNAPSHOT</version>
+ <relativePath>..</relativePath>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.jboss.dna.examples</groupId>
+ <artifactId>dna-example-repositories</artifactId>
+ <version>0.2-SNAPSHOT</version>
+ <packaging>jar</packaging>
+ <name>JBoss DNA Repositories Examples</name>
+ <description>Examples that showcase how to use DNA repositories.</description>
+
+ <properties>
+ <dna-version>0.2-SNAPSHOT</dna-version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.jboss.dna</groupId>
+ <artifactId>dna-repository</artifactId>
+ <version>${dna-version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.dna</groupId>
+ <artifactId>dna-jcr</artifactId>
+ <version>${dna-version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.dna</groupId>
+ <artifactId>dna-common</artifactId>
+ <version>${dna-version}</version>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.dna</groupId>
+ <artifactId>dna-connector-inmemory</artifactId>
+ <version>${dna-version}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.dna</groupId>
+ <artifactId>dna-connector-jbosscache</artifactId>
+ <version>${dna-version}</version>
+ <scope>runtime</scope>
+ </dependency>
+ <!--
+ Logging (require SLF4J API for compiling, but use Log4J and its SLF4J binding for testing)
+ -->
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </dependency>
+ <!--
+ Java Content Repository API
+ -->
+ <dependency>
+ <groupId>javax.jcr</groupId>
+ <artifactId>jcr</artifactId>
+ </dependency>
+ <!--
+ Test cases use JUnit
+ -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <configuration>
+ <descriptors>
+ <descriptor>src/main/assembly/basic.xml</descriptor>
+ </descriptors>
+ <finalName>${pom.artifactId}</finalName>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>directory-inline</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+</project>
\ No newline at end of file
Added: trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/assembly/basic.xml 2008-09-05 19:59:46 UTC (rev 504)
@@ -0,0 +1,46 @@
+<assembly>
+ <id>basic</id>
+ <formats>
+ <format>zip</format>
+ </formats>
+ <includeBaseDirectory>false</includeBaseDirectory>
+ <fileSets>
+ <fileSet>
+ <directory>target</directory>
+ <outputDirectory/>
+ <includes>
+ <include>*.jar</include>
+ </includes>
+ </fileSet>
+ <fileSet>
+ <directory>src/main/resources/</directory>
+ <outputDirectory/>
+ <includes>
+ <include>*.*</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+ <files>
+ <file>
+ <source>src/main/config/run.sh</source>
+ <fileMode>0744</fileMode>
+ </file>
+ <file>
+ <source>src/main/resources/log4j.properties</source>
+ <fileMode>0644</fileMode>
+ </file>
+ </files>
+ <dependencySets>
+ <dependencySet>
+ <outputDirectory>/lib</outputDirectory>
+ <unpack>false</unpack>
+ <includes>
+ <!-- Include everything needed by the examples. -->
+ <include>*:jar:*</include>
+ </includes>
+ <!--excludes>
+ <exclude>*:sources</exclude>
+ </excludes-->
+ </dependencySet>
+ </dependencySets>
+</assembly>
\ No newline at end of file
Added: trunk/docs/examples/gettingstarted/repositories/src/main/config/run.sh
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/config/run.sh (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/config/run.sh 2008-09-05 19:59:46 UTC (rev 504)
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+java -Djava.ext.dirs=`pwd`/lib -cp .:dna-example-sequencers-0.1-SNAPSHOT.jar org.jboss.example.dna.repository.RepositoryClient $1
\ No newline at end of file
Added: trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/java/org/jboss/example/dna/repository/RepositoryClient.java 2008-09-05 19:59:46 UTC (rev 504)
@@ -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.example.dna.repository;
+
+/**
+ *
+ * @author Randall Hauch
+ */
+public class RepositoryClient {
+
+ /**
+ * @param args
+ */
+ public static void main( String[] args ) {
+
+ }
+
+}
Added: trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties
===================================================================
--- trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties (rev 0)
+++ trunk/docs/examples/gettingstarted/repositories/src/main/resources/log4j.properties 2008-09-05 19:59:46 UTC (rev 504)
@@ -0,0 +1,12 @@
+# Direct log messages to stdout
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.Target=System.out
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %m%n
+
+# Root logger option
+log4j.rootLogger=INFO, stdout
+
+# Set up the default logging to be INFO level, then override specific units
+log4j.logger.org.jboss.dna=INFO
+
15 years, 7 months
DNA SVN: r503 - trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java.
by dna-commits@lists.jboss.org
Author: rhauch
Date: 2008-09-05 15:57:53 -0400 (Fri, 05 Sep 2008)
New Revision: 503
Modified:
trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java
Log:
Minor correction to the SequencingClient and JavaSequencingClient to handle same-name-siblings.
Modified: trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java
===================================================================
--- trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java 2008-09-05 19:57:12 UTC (rev 502)
+++ trunk/docs/examples/gettingstarted/dna-example-java-sequencer/src/main/java/org/jboss/dna/sequencer/java/JavaSequencingClient.java 2008-09-05 19:57:53 UTC (rev 503)
@@ -242,7 +242,7 @@
String desc = "Sequences java files to extract the characteristics of the java sources";
String classname = "org.jboss.dna.sequencer.java.JavaMetadataSequencer";
String[] classpath = null; // Use the current class path
- String[] pathExpressions = {"//(*.java)[*]/jcr:content[@jcr:data] => /compilationUnits/$1"};
+ String[] pathExpressions = {"//(*.java[*])/jcr:content[@jcr:data] => /compilationUnits/$1"};
SequencerConfig javaSequencerConfig = new SequencerConfig(name, desc, classname, classpath, pathExpressions);
this.sequencingService.addSequencer(javaSequencerConfig);
15 years, 7 months