Search in sources :

Example 91 with PropertyIterator

use of javax.jcr.PropertyIterator in project sling by apache.

the class ScriptableNode method get.

/**
     * Gets the value of a (Javascript) property or child node. If there is a single single-value
     * JCR property of this node, return its string value. If there are multiple properties
     * of the same name or child nodes of the same name, return an array.
     */
@Override
public Object get(String name, Scriptable start) {
    // builtin javascript properties (jsFunction_ etc.) have priority
    final Object fromSuperclass = super.get(name, start);
    if (fromSuperclass != Scriptable.NOT_FOUND) {
        return fromSuperclass;
    }
    if (node == null) {
        return Undefined.instance;
    }
    final List<Scriptable> items = new ArrayList<Scriptable>();
    // Add all matching nodes to result
    try {
        NodeIterator it = node.getNodes(name);
        while (it.hasNext()) {
            items.add(ScriptRuntime.toObject(this, it.nextNode()));
        }
    } catch (RepositoryException e) {
        log.debug("RepositoryException while collecting Node children", e);
    }
    // Add all matching properties to result
    boolean isMulti = false;
    try {
        PropertyIterator it = node.getProperties(name);
        while (it.hasNext()) {
            Property prop = it.nextProperty();
            if (prop.getDefinition().isMultiple()) {
                isMulti = true;
                Value[] values = prop.getValues();
                for (int i = 0; i < values.length; i++) {
                    items.add(wrap(values[i]));
                }
            } else {
                items.add(wrap(prop.getValue()));
            }
        }
    } catch (RepositoryException e) {
        log.debug("RepositoryException while collecting Node properties", e);
    }
    if (items.size() == 0) {
        return getNative(name, start);
    } else if (items.size() == 1 && !isMulti) {
        return items.iterator().next();
    } else {
        NativeArray result = new NativeArray(items.toArray());
        ScriptRuntime.setObjectProtoAndParent(result, this);
        return result;
    }
}
Also used : NodeIterator(javax.jcr.NodeIterator) NativeArray(org.mozilla.javascript.NativeArray) ArrayList(java.util.ArrayList) PropertyIterator(javax.jcr.PropertyIterator) RepositoryException(javax.jcr.RepositoryException) Scriptable(org.mozilla.javascript.Scriptable) Value(javax.jcr.Value) Property(javax.jcr.Property)

Example 92 with PropertyIterator

use of javax.jcr.PropertyIterator in project sling by apache.

the class VirtualInstanceHelper method dump.

public static void dump(Node node) throws RepositoryException {
    if (node.getPath().equals("/jcr:system") || node.getPath().equals("/rep:policy")) {
        // ignore that one
        return;
    }
    PropertyIterator pi = node.getProperties();
    StringBuilder sb = new StringBuilder();
    while (pi.hasNext()) {
        Property p = pi.nextProperty();
        sb.append(" ");
        sb.append(p.getName());
        sb.append("=");
        if (p.getType() == PropertyType.BOOLEAN) {
            sb.append(p.getBoolean());
        } else if (p.getType() == PropertyType.STRING) {
            sb.append(p.getString());
        } else if (p.getType() == PropertyType.DATE) {
            sb.append(p.getDate().getTime());
        } else {
            sb.append("<unknown type=" + p.getType() + "/>");
        }
    }
    StringBuffer depth = new StringBuffer();
    for (int i = 0; i < node.getDepth(); i++) {
        depth.append(" ");
    }
    logger.info(depth + "/" + node.getName() + " -- " + sb);
    NodeIterator it = node.getNodes();
    while (it.hasNext()) {
        Node child = it.nextNode();
        dump(child);
    }
}
Also used : NodeIterator(javax.jcr.NodeIterator) Node(javax.jcr.Node) PropertyIterator(javax.jcr.PropertyIterator) Property(javax.jcr.Property)

Example 93 with PropertyIterator

use of javax.jcr.PropertyIterator in project sling by apache.

the class JsonContentTest method testContent_Datatypes_JCR.

@Test
public void testContent_Datatypes_JCR() throws RepositoryException {
    Resource underTest = fsroot.getChild("folder2/content/toolbar/profiles/jcr:content");
    ValueMap props = underTest.getValueMap();
    Node node = underTest.adaptTo(Node.class);
    assertEquals("/fs-test/folder2/content/toolbar/profiles/jcr:content", node.getPath());
    assertEquals(6, node.getDepth());
    assertTrue(node.hasProperty("jcr:title"));
    assertEquals(PropertyType.STRING, node.getProperty("jcr:title").getType());
    assertFalse(node.getProperty("jcr:title").isMultiple());
    assertEquals("jcr:title", node.getProperty("jcr:title").getDefinition().getName());
    assertEquals("/fs-test/folder2/content/toolbar/profiles/jcr:content/jcr:title", node.getProperty("jcr:title").getPath());
    assertEquals("Profiles", node.getProperty("jcr:title").getString());
    assertEquals(PropertyType.BOOLEAN, node.getProperty("booleanProp").getType());
    assertEquals(true, node.getProperty("booleanProp").getBoolean());
    assertEquals(PropertyType.LONG, node.getProperty("longProp").getType());
    assertEquals(1234567890123L, node.getProperty("longProp").getLong());
    assertEquals(PropertyType.DECIMAL, node.getProperty("decimalProp").getType());
    assertEquals(1.2345d, node.getProperty("decimalProp").getDouble(), 0.00001d);
    assertEquals(new BigDecimal("1.2345"), node.getProperty("decimalProp").getDecimal());
    assertEquals(PropertyType.STRING, node.getProperty("stringPropMulti").getType());
    assertTrue(node.getProperty("stringPropMulti").isMultiple());
    Value[] stringPropMultiValues = node.getProperty("stringPropMulti").getValues();
    assertEquals(3, stringPropMultiValues.length);
    assertEquals("aa", stringPropMultiValues[0].getString());
    assertEquals("bb", stringPropMultiValues[1].getString());
    assertEquals("cc", stringPropMultiValues[2].getString());
    assertEquals(PropertyType.LONG, node.getProperty("longPropMulti").getType());
    assertTrue(node.getProperty("longPropMulti").isMultiple());
    Value[] longPropMultiValues = node.getProperty("longPropMulti").getValues();
    assertEquals(2, longPropMultiValues.length);
    assertEquals(1234567890123L, longPropMultiValues[0].getLong());
    assertEquals(55L, longPropMultiValues[1].getLong());
    // assert property iterator
    Set<String> propertyNames = new HashSet<>();
    PropertyIterator propertyIterator = node.getProperties();
    while (propertyIterator.hasNext()) {
        propertyNames.add(propertyIterator.nextProperty().getName());
    }
    assertTrue(props.keySet().containsAll(propertyNames));
    // assert node iterator
    Set<String> nodeNames = new HashSet<>();
    NodeIterator nodeIterator = node.getNodes();
    while (nodeIterator.hasNext()) {
        nodeNames.add(nodeIterator.nextNode().getName());
    }
    assertEquals(ImmutableSet.of("par", "rightpar"), nodeNames);
    // node hierarchy
    assertTrue(node.hasNode("rightpar"));
    Node rightpar = node.getNode("rightpar");
    assertEquals(7, rightpar.getDepth());
    Node parent = rightpar.getParent();
    assertTrue(node.isSame(parent));
    Node ancestor = (Node) rightpar.getAncestor(5);
    assertEquals(underTest.getParent().getPath(), ancestor.getPath());
    Node root = (Node) rightpar.getAncestor(0);
    assertEquals("/", root.getPath());
    // node types
    assertTrue(node.isNodeType("app:PageContent"));
    assertEquals("app:PageContent", node.getPrimaryNodeType().getName());
    assertFalse(node.getPrimaryNodeType().isMixin());
    NodeType[] mixinTypes = node.getMixinNodeTypes();
    assertEquals(2, mixinTypes.length);
    assertEquals("type1", mixinTypes[0].getName());
    assertEquals("type2", mixinTypes[1].getName());
    assertTrue(mixinTypes[0].isMixin());
    assertTrue(mixinTypes[1].isMixin());
}
Also used : NodeIterator(javax.jcr.NodeIterator) ValueMap(org.apache.sling.api.resource.ValueMap) Node(javax.jcr.Node) Resource(org.apache.sling.api.resource.Resource) PropertyIterator(javax.jcr.PropertyIterator) BigDecimal(java.math.BigDecimal) NodeType(javax.jcr.nodetype.NodeType) Value(javax.jcr.Value) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 94 with PropertyIterator

use of javax.jcr.PropertyIterator in project sling by apache.

the class AddOrUpdateNodeCommand method updateNode.

private void updateNode(Node node, ResourceProxy resource) throws RepositoryException, IOException {
    if (node.getPath().equals(getPath()) && fileInfo != null) {
        updateFileLikeNodeTypes(node);
    }
    Set<String> propertiesToRemove = new HashSet<>();
    PropertyIterator properties = node.getProperties();
    while (properties.hasNext()) {
        Property property = properties.nextProperty();
        if (property.getDefinition().isProtected() || property.getDefinition().isAutoCreated() || property.getDefinition().getRequiredType() == PropertyType.BINARY) {
            continue;
        }
        propertiesToRemove.add(property.getName());
    }
    propertiesToRemove.removeAll(resource.getProperties().keySet());
    Session session = node.getSession();
    // update the mixin types ahead of type as contraints are enforced before
    // the session is committed
    Object mixinTypes = resource.getProperties().get(JcrConstants.JCR_MIXINTYPES);
    if (mixinTypes != null) {
        updateMixins(node, mixinTypes);
    }
    // this supports the scenario where the node type is changed to a less permissive one
    for (String propertyToRemove : propertiesToRemove) {
        node.getProperty(propertyToRemove).remove();
        getLogger().trace("Removed property {0} from node at {1}", propertyToRemove, node.getPath());
    }
    String primaryType = (String) resource.getProperties().get(JcrConstants.JCR_PRIMARYTYPE);
    if (primaryType != null && !node.getPrimaryNodeType().getName().equals(primaryType) && node.getDepth() != 0) {
        node.setPrimaryType(primaryType);
        session.save();
        getLogger().trace("Set new primary type {0} for node at {1}", primaryType, node.getPath());
    }
    // TODO - review for completeness and filevault compatibility
    for (Map.Entry<String, Object> entry : resource.getProperties().entrySet()) {
        String propertyName = entry.getKey();
        Object propertyValue = entry.getValue();
        Property property = null;
        // so make sure that it does not get processed like a regular property
        if (JcrConstants.JCR_MIXINTYPES.equals(propertyName)) {
            continue;
        }
        if (node.hasProperty(propertyName)) {
            property = node.getProperty(propertyName);
        }
        if (property != null && property.getDefinition().isProtected()) {
            continue;
        }
        ValueFactory valueFactory = session.getValueFactory();
        Value value = null;
        Value[] values = null;
        if (propertyValue instanceof String) {
            value = valueFactory.createValue((String) propertyValue);
            ensurePropertyDefinitionMatchers(property, PropertyType.STRING, false);
        } else if (propertyValue instanceof String[]) {
            values = toValueArray((String[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.STRING, true);
        } else if (propertyValue instanceof Boolean) {
            value = valueFactory.createValue((Boolean) propertyValue);
            ensurePropertyDefinitionMatchers(property, PropertyType.BOOLEAN, false);
        } else if (propertyValue instanceof Boolean[]) {
            values = toValueArray((Boolean[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.BOOLEAN, true);
        } else if (propertyValue instanceof Calendar) {
            value = valueFactory.createValue((Calendar) propertyValue);
            ensurePropertyDefinitionMatchers(property, PropertyType.DATE, false);
        } else if (propertyValue instanceof Calendar[]) {
            values = toValueArray((Calendar[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.DATE, true);
        } else if (propertyValue instanceof Double) {
            value = valueFactory.createValue((Double) propertyValue);
            ensurePropertyDefinitionMatchers(property, PropertyType.DOUBLE, false);
        } else if (propertyValue instanceof Double[]) {
            values = toValueArray((Double[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.DOUBLE, true);
        } else if (propertyValue instanceof BigDecimal) {
            value = valueFactory.createValue((BigDecimal) propertyValue);
            ensurePropertyDefinitionMatchers(property, PropertyType.DECIMAL, false);
        } else if (propertyValue instanceof BigDecimal[]) {
            values = toValueArray((BigDecimal[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.DECIMAL, true);
        } else if (propertyValue instanceof Long) {
            value = valueFactory.createValue((Long) propertyValue);
            ensurePropertyDefinitionMatchers(property, PropertyType.LONG, false);
        } else if (propertyValue instanceof Long[]) {
            values = toValueArray((Long[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.LONG, true);
        // TODO - distinguish between weak vs strong references
        } else if (propertyValue instanceof UUID) {
            Node reference = session.getNodeByIdentifier(((UUID) propertyValue).toString());
            value = valueFactory.createValue(reference);
            ensurePropertyDefinitionMatchers(property, PropertyType.REFERENCE, false);
        } else if (propertyValue instanceof UUID[]) {
            values = toValueArray((UUID[]) propertyValue, session);
            ensurePropertyDefinitionMatchers(property, PropertyType.REFERENCE, true);
        } else {
            throw new IllegalArgumentException("Unable to handle value '" + propertyValue + "' for property '" + propertyName + "'");
        }
        if (value != null) {
            Object[] arguments = { propertyName, value, propertyValue, node.getPath() };
            getLogger().trace("Setting property {0} with value {1} (raw =  {2}) on node at {3}", arguments);
            node.setProperty(propertyName, value);
            getLogger().trace("Set property {0} with value {1} (raw =  {2}) on node at {3}", arguments);
        } else if (values != null) {
            Object[] arguments = { propertyName, values, propertyValue, node.getPath() };
            getLogger().trace("Setting property {0} with values {1} (raw =  {2}) on node at {3}", arguments);
            node.setProperty(propertyName, values);
            getLogger().trace("Set property {0} with values {1} (raw =  {2}) on node at {3}", arguments);
        } else {
            throw new IllegalArgumentException("Unable to extract a value or a value array for property '" + propertyName + "' with value '" + propertyValue + "'");
        }
    }
}
Also used : Node(javax.jcr.Node) UUID(java.util.UUID) Property(javax.jcr.Property) HashSet(java.util.HashSet) Calendar(java.util.Calendar) PropertyIterator(javax.jcr.PropertyIterator) ValueFactory(javax.jcr.ValueFactory) BigDecimal(java.math.BigDecimal) Value(javax.jcr.Value) HashMap(java.util.HashMap) Map(java.util.Map) Session(javax.jcr.Session)

Example 95 with PropertyIterator

use of javax.jcr.PropertyIterator in project sling by apache.

the class MockNodeTest method testPrimaryType.

@Test
public void testPrimaryType() throws RepositoryException {
    assertEquals("nt:unstructured", this.node1.getPrimaryNodeType().getName());
    assertEquals("nt:unstructured", this.node1.getProperty("jcr:primaryType").getString());
    final PropertyIterator properties = this.node1.getProperties();
    while (properties.hasNext()) {
        final Property property = properties.nextProperty();
        if (JcrConstants.JCR_PRIMARYTYPE.equals(property.getName())) {
            return;
        }
    }
    fail("Properties did not include jcr:primaryType");
}
Also used : PropertyIterator(javax.jcr.PropertyIterator) Property(javax.jcr.Property) Test(org.junit.Test)

Aggregations

PropertyIterator (javax.jcr.PropertyIterator)96 Property (javax.jcr.Property)68 Node (javax.jcr.Node)57 NodeIterator (javax.jcr.NodeIterator)28 Value (javax.jcr.Value)23 Test (org.junit.Test)16 RepositoryException (javax.jcr.RepositoryException)15 Session (javax.jcr.Session)15 ArrayList (java.util.ArrayList)14 HashSet (java.util.HashSet)10 PathNotFoundException (javax.jcr.PathNotFoundException)8 HashMap (java.util.HashMap)5 JackrabbitNode (org.apache.jackrabbit.api.JackrabbitNode)5 NodeImpl (org.apache.jackrabbit.core.NodeImpl)5 PropertyImpl (org.apache.jackrabbit.core.PropertyImpl)5 NoSuchElementException (java.util.NoSuchElementException)3 AccessDeniedException (javax.jcr.AccessDeniedException)3 InvalidItemStateException (javax.jcr.InvalidItemStateException)3 ValueFormatException (javax.jcr.ValueFormatException)3 ConstraintViolationException (javax.jcr.nodetype.ConstraintViolationException)3