Java Code Examples for org.apache.jackrabbit.commons.JcrUtils

The following examples show how to use org.apache.jackrabbit.commons.JcrUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Tests minimal serialization
 */
@Test
public void testMinimalSerialization() throws Exception {
    JcrUtils.getOrCreateByPath("/testroot", NodeType.NT_UNSTRUCTURED, admin);
    admin.save();

    DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter();
    filter.add(new PathFilterSet("/testroot"));
    RepositoryAddress addr = new RepositoryAddress("/" + admin.getWorkspace().getName() + "/");
    VaultFileSystem jcrfs = Mounter.mount(null, filter, addr, null, admin);
    Aggregate a = jcrfs.getAggregateManager().getRoot().getAggregate("testroot");
    DocViewSerializer s = new DocViewSerializer(a);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    s.writeContent(out);

    assertEquals("valid xml",
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<jcr:root xmlns:jcr=\"http://www.jcp.org/jcr/1.0\" xmlns:nt=\"http://www.jcp.org/jcr/nt/1.0\"\n" +
            "    jcr:primaryType=\"nt:unstructured\"/>\n", out.toString("utf-8"));
}
 
Example 2
/**
 * Tests export of mixed case named properties serialization
 */
@Test
public void testMixedCaseSerialization() throws Exception {
    Node node = JcrUtils.getOrCreateByPath("/testroot", NodeType.NT_UNSTRUCTURED, admin);
    node.setProperty("testproperty", "lowercase");
    node.setProperty("TestProperty", "MixedCase");
    admin.save();

    DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter();
    filter.add(new PathFilterSet("/testroot"));
    RepositoryAddress addr = new RepositoryAddress("/" + admin.getWorkspace().getName() + "/");
    VaultFileSystem jcrfs = Mounter.mount(null, filter, addr, null, admin);
    Aggregate a = jcrfs.getAggregateManager().getRoot().getAggregate("testroot");
    DocViewSerializer s = new DocViewSerializer(a);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    s.writeContent(out);

    assertEquals("valid xml",
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<jcr:root xmlns:jcr=\"http://www.jcp.org/jcr/1.0\" xmlns:nt=\"http://www.jcp.org/jcr/nt/1.0\"\n" +
            "    jcr:primaryType=\"nt:unstructured\"\n" +
            "    TestProperty=\"MixedCase\"\n" +
            "    testproperty=\"lowercase\"/>\n", out.toString("utf-8"));
}
 
Example 3
Source Project: jackrabbit-filevault   Source File: RCPTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimple() throws IOException, RepositoryException, ConfigurationException {
    Node a = JcrUtils.getOrCreateByPath(SRC_TEST_NODE_PATH, NodeType.NT_UNSTRUCTURED, NodeType.NT_UNSTRUCTURED, admin, true);
    a.setProperty("p0", "0");
    a.setProperty("p1", "1");
    a.setProperty("m0", new String[]{"0", "1", "2"}, PropertyType.STRING);
    admin.save();

    assertNodeExists(SRC_TEST_NODE_PATH);

    RepositoryCopier rcp = new RepositoryCopier();
    rcp.copy(admin, SRC_PATH, admin, DST_PATH, true);

    assertProperty(DST_TEST_NODE_PATH + "/p0", "0");
    assertProperty(DST_TEST_NODE_PATH + "/p1", "1");
    assertProperty(DST_TEST_NODE_PATH + "/m0", new String[]{"0", "1", "2"});
}
 
Example 4
Source Project: jackrabbit-filevault   Source File: RCPTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddMixin() throws IOException, RepositoryException, ConfigurationException {
    Node a = JcrUtils.getOrCreateByPath(SRC_TEST_NODE_PATH, NodeType.NT_FOLDER, NodeType.NT_FOLDER, admin, true);
    RepositoryCopier rcp = new RepositoryCopier();
    rcp.copy(admin, SRC_PATH, admin, DST_PATH, true);
    assertNodeExists(DST_TEST_NODE_PATH);
    assertPropertyMissing(DST_TEST_NODE_PATH + "/jcr:title");

    a.addMixin(NodeType.MIX_TITLE);
    a.setProperty("jcr:title", "Hello");
    admin.save();
    assertProperty(SRC_TEST_NODE_PATH + "/jcr:title", "Hello");

    rcp = new RepositoryCopier();
    rcp.setOnlyNewer(false);
    rcp.setUpdate(true);
    rcp.copy(admin, SRC_PATH, admin, DST_PATH, true);

    assertProperty(DST_TEST_NODE_PATH + "/jcr:title", "Hello");
    assertProperty(DST_TEST_NODE_PATH + "/jcr:mixinTypes", new String[]{"mix:title"});
}
 
Example 5
Source Project: jackrabbit-filevault   Source File: TestBinarylessExport.java    License: Apache License 2.0 6 votes vote down vote up
@Before
@Ignore
public void setup() throws RepositoryException, PackageException, IOException {
    // test only works for Jackrabbit 2.0 or Oak with FileDataStore
    Assume.assumeTrue(!isOak() || useFileStore());

    Node binaryNode = JcrUtils.getOrCreateByPath(BINARY_NODE_PATH, "nt:unstructured", admin);

    Binary bigBin = admin.getValueFactory().createBinary(IOUtils.toInputStream(BIG_TEXT, "UTF-8"));
    Property bigProperty = binaryNode.setProperty(BIG_BINARY_PROPERTY, bigBin);
    String referenceBigBinary = ((ReferenceBinary) bigProperty.getBinary()).getReference();
    assertNotNull(referenceBigBinary);

    Binary smallBin = admin.getValueFactory().createBinary(IOUtils.toInputStream(SMALL_TEXT, "UTF-8"));
    Property smallProperty = binaryNode.setProperty(SMALL_BINARY_PROPERTY, smallBin);
    if (isOak()) {
        assertTrue(smallProperty.getBinary() instanceof ReferenceBinary);
    } else {
        assertFalse(smallProperty.getBinary() instanceof ReferenceBinary);
    }

    JcrUtils.putFile(binaryNode.getParent(), "file", "text/plain", IOUtils.toInputStream(BIG_TEXT, "UTF-8"));
    admin.save();
}
 
Example 6
Source Project: jackrabbit-filevault   Source File: TestEmptyPackage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Installs a package that contains /tmp/test/content/foo/foo.jsp and then creates a new node
 * /tmp/test/content/bar/bar.jsp. Tests if after reinstall the new node was deleted.
 */
@Test
public void installEmptyFolder() throws RepositoryException, IOException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("/test-packages/tmp_test_folders.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());
    assertNodeExists("/tmp/test/content/foo/foo.jsp");

    // create new node
    Node content = admin.getNode("/tmp/test/content");
    Node bar = content.addNode("bar", NodeType.NT_FOLDER);
    InputStream is = new ByteArrayInputStream("hello, world.".getBytes());
    JcrUtils.putFile(bar, "bar.jsp", "text/plain", is);
    admin.save();

    // now re-install package
    pack.install(getDefaultOptions());

    assertNodeMissing("/tmp/test/content/bar");
    assertNodeMissing("/tmp/test/content/bar/bar.jsp");
}
 
Example 7
Source Project: jackrabbit-filevault   Source File: TestAtomicCounter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests if installing a package with a mix:atomicCounter works (update)
 */
@Test
public void updateAtomicCounter() throws RepositoryException, IOException, PackageException {
    Assume.assumeTrue(isOak());

    Node tmp = JcrUtils.getOrAddNode(admin.getRootNode(), "tmp", NodeType.NT_UNSTRUCTURED);
    Node testroot = JcrUtils.getOrAddNode(tmp, "testroot", NodeType.NT_UNSTRUCTURED);
    testroot.addMixin("mix:atomicCounter");
    testroot.setProperty("oak:increment", 5);
    admin.save();
    assertEquals(5L, testroot.getProperty("oak:counter").getLong());

    JcrPackage pack = packMgr.upload(getStream("/test-packages/atomic-counter-test.zip"), false);
    assertNotNull(pack);
    ImportOptions opts = getDefaultOptions();
    pack.install(opts);

    assertProperty("/tmp/testroot/oak:counter", "42");
}
 
Example 8
@Override
public Page getPage(final String path, final String requestedUser) {
    return jcrTemplate.execute(session -> {
        Node rootNode = session.getRootNode();
        Node node = JcrUtils.getNodeIfExists(rootNode, path);
        if (node != null) {
            if (isNodePage(node)) {
                if (isAccessible(node, requestedUser)) {
                    return convertNodeToPage(node);
                } else {
                    return null;
                }
            }
        }

        return null;
    });
}
 
Example 9
@Override
public List<PageVersion> getPageVersions(final String path) {
    return jcrTemplate.execute(session -> {
        Node rootNode = session.getRootNode();
        Node node = JcrUtils.getNodeIfExists(rootNode, path);
        if (node != null) {
            VersionManager vm = session.getWorkspace().getVersionManager();
            VersionHistory history = vm.getVersionHistory("/" + path);
            List<PageVersion> versions = new ArrayList<>();
            for (VersionIterator it = history.getAllVersions(); it.hasNext(); ) {
                Version version = (Version) it.next();
                if (!"jcr:rootVersion".equals(version.getName())) {
                    versions.add(convertNodeToPageVersion(version));
                }
            }
            return versions;
        } else {
            return null;
        }
    });
}
 
Example 10
@Override
public Page restorePage(final String path, final String versionName) {
    return jcrTemplate.execute(session -> {
        Node rootNode = session.getRootNode();
        Node node = JcrUtils.getNodeIfExists(rootNode, path);
        if (node != null) {
            VersionManager vm = session.getWorkspace().getVersionManager();
            try {
                vm.restore("/" + path, versionName, true);
                node = JcrUtils.getNodeIfExists(rootNode, path);
                return convertNodeToPage(node);
            } catch (Exception e) {
                LOG.error("Error when restore document {} to version {}", path, versionName, e);
            }
        }
        return null;
    });

}
 
Example 11
@Override
public Page getPageByVersion(final String path, final String versionName) {
    return jcrTemplate.execute(session -> {
        Node rootNode = session.getRootNode();
        Node node = JcrUtils.getNodeIfExists(rootNode, path);
        if (node != null) {
            VersionManager vm = session.getWorkspace().getVersionManager();
            VersionHistory history = vm.getVersionHistory("/" + path);
            Version version = history.getVersion(versionName);
            if (version != null) {
                Node frozenNode = version.getFrozenNode();
                return convertNodeToPage(frozenNode);
            } else {
                return null;
            }
        } else {
            return null;
        }
    });
}
 
Example 12
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void removeProject(RepositorySession session, String repositoryId, String namespace, String projectId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node root = jcrSession.getRootNode();
        String namespacePath = getNamespacePath(repositoryId, namespace);

        if (root.hasNode(namespacePath)) {
            Iterator<Node> nodeIterator = JcrUtils.getChildNodes(root.getNode(namespacePath)).iterator();
            while (nodeIterator.hasNext()) {
                Node node = nodeIterator.next();
                if (node.isNodeType(org.apache.archiva.metadata.repository.jcr.JcrConstants.PROJECT_MIXIN_TYPE) && projectId.equals(node.getName())) {
                    node.remove();
                }
            }

        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }

}
 
Example 13
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
private <T extends MetadataFacet> T createFacetFromNode(final MetadataFacetFactory<T> factory, final Node node,
                                                        final String repositoryId, final String name) throws RepositoryException {
    if (factory != null) {
        T metadataFacet;
        if (repositoryId != null) {
            metadataFacet = factory.createMetadataFacet(repositoryId, name);
        } else {
            metadataFacet = factory.createMetadataFacet();
        }
        Map<String, String> map = new HashMap<>();
        for (Property property : JcrUtils.getProperties(node)) {
            String p = property.getName();
            if (!p.startsWith("jcr:")) {
                map.put(p, property.getString());
            }
        }
        metadataFacet.fromProperties(map);
        return metadataFacet;
    }
    return null;
}
 
Example 14
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<ArtifactMetadata> getArtifactsByDateRange(RepositorySession session, String repoId, ZonedDateTime startTime, ZonedDateTime endTime, QueryParameter queryParameter)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);

    List<ArtifactMetadata> artifacts;
    try {
        QueryResult result = queryArtifactByDateRange(jcrSession, repoId, startTime, endTime, queryParameter);

        artifacts = new ArrayList<>();
        for (Node n : JcrUtils.getNodes(result)) {
            artifacts.add(getArtifactFromNode(repoId, n));
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
    return artifacts;
}
 
Example 15
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<ArtifactMetadata> getArtifactsByChecksum(RepositorySession session, String repositoryId, String checksum)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    List<ArtifactMetadata> artifacts;

    String q = getArtifactQuery(repositoryId).append(" AND ([artifact].[checksums/*/value] = $checksum)").toString();

    try {
        Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2);
        ValueFactory valueFactory = jcrSession.getValueFactory();
        query.bindValue("checksum", valueFactory.createValue(checksum));
        QueryResult result = query.execute();

        artifacts = new ArrayList<>();
        for (Node n : JcrUtils.getNodes(result)) {
            artifacts.add(getArtifactFromNode(repositoryId, n));
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
    return artifacts;
}
 
Example 16
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<ArtifactMetadata> getArtifacts(RepositorySession session, String repositoryId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    List<ArtifactMetadata> artifacts;

    String q = getArtifactQuery(repositoryId).toString();

    try {
        Query query = jcrSession.getWorkspace().getQueryManager().createQuery(q, Query.JCR_SQL2);
        QueryResult result = query.execute();

        artifacts = new ArrayList<>();
        for (Node n : JcrUtils.getNodes(result)) {
            if (n.isNodeType(ARTIFACT_NODE_TYPE)) {
                artifacts.add(getArtifactFromNode(repositoryId, n));
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
    return artifacts;
}
 
Example 17
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void removeProjectVersion(RepositorySession session, String repoId, String namespace, String projectId, String projectVersion)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {

        String path = getProjectPath(repoId, namespace, projectId);
        Node root = jcrSession.getRootNode();

        Node nodeAtPath = root.getNode(path);

        for (Node node : JcrUtils.getChildNodes(nodeAtPath)) {
            if (node.isNodeType(PROJECT_VERSION_NODE_TYPE) && StringUtils.equals(projectVersion,
                    node.getName())) {
                node.remove();
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example 18
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
private Node getOrAddNodeByPath(Node baseNode, String name, String nodeType, boolean primaryType)
        throws RepositoryException {
    log.debug("getOrAddNodeByPath " + baseNode + " " + name + " " + nodeType);
    Node node = baseNode;
    for (String n : name.split("/")) {
        if (nodeType != null && primaryType) {
            node = JcrUtils.getOrAddNode(node, n, nodeType);
        } else {
            node = JcrUtils.getOrAddNode(node, n);
            if (nodeType != null && !node.isNodeType(nodeType)) {
                node.addMixin(nodeType);
            }
        }
        if (!node.hasProperty("id")) {
            node.setProperty("id", n);
        }
    }
    return node;
}
 
Example 19
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
private Node getOrAddNodeByPath(Node baseNode, String name, String primaryType, String... mixinTypes)
        throws RepositoryException {
    log.debug("getOrAddNodeByPath baseNode={}, name={}, primary={}, mixin={}", baseNode, name, primaryType, mixinTypes);
    Node node = baseNode;
    for (String n : name.split("/")) {
        node = JcrUtils.getOrAddNode(node, n, primaryType);
        for (String mixin : mixinTypes) {
            if (mixin != null && !node.isNodeType(mixin)) {
                node.addMixin(mixin);
            }

        }
        if (!node.hasProperty("id")) {
            node.setProperty("id", n);
        }
    }
    return node;
}
 
Example 20
Source Project: archiva   Source File: JcrMetadataRepository.java    License: Apache License 2.0 6 votes vote down vote up
private Node findArtifactNode(Session jcrSession, String namespace, String projectId,
                              String projectVersion, String id) throws RepositoryException {

    if (namespace==null || projectId==null||projectVersion==null||id==null) {
        return null;
    }
    Node root = jcrSession.getRootNode();
    Node node = JcrUtils.getOrAddNode(root, "repositories");
    for (Node n : JcrUtils.getChildNodes(node)) {
        String repositoryId = n.getName();
        Node repo = getOrAddRepositoryContentNode(jcrSession, repositoryId);
        Node nsNode = JcrUtils.getNodeIfExists(repo, StringUtils.replaceChars(namespace, '.', '/'));
        if (nsNode!=null) {
            Node projNode = JcrUtils.getNodeIfExists(nsNode, projectId);
            if (projNode !=null ) {
                Node projVersionNode = JcrUtils.getNodeIfExists(projNode, projectVersion);
                if (projVersionNode != null) {
                    return JcrUtils.getNodeIfExists(projVersionNode, id);
                }
            }
        }
    }

    return null;
}
 
Example 21
Source Project: APM   Source File: ScriptStorageImpl.java    License: Apache License 2.0 5 votes vote down vote up
private Script saveScript(FileDescriptor descriptor, LaunchMetadata launchMetadata, boolean overwrite,
    ResourceResolver resolver) {
  Script result = null;
  try {
    final Session session = resolver.adaptTo(Session.class);
    final ValueFactory valueFactory = session.getValueFactory();
    final Binary binary = valueFactory.createBinary(descriptor.getInputStream());
    final Node saveNode = session.getNode(descriptor.getPath());

    final Node fileNode, contentNode;
    if (overwrite && saveNode.hasNode(descriptor.getName())) {
      fileNode = saveNode.getNode(descriptor.getName());
      contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT);
    } else {
      fileNode = saveNode.addNode(generateFileName(descriptor.getName(), saveNode), JcrConstants.NT_FILE);
      contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }

    contentNode.setProperty(JcrConstants.JCR_DATA, binary);
    contentNode.setProperty(JcrConstants.JCR_ENCODING, SCRIPT_ENCODING.name());
    fileNode.addMixin(ScriptNode.APM_SCRIPT);
    fileNode.setProperty(ScriptNode.APM_LAUNCH_ENABLED, launchMetadata.isExecutionEnabled());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_MODE, launchMetadata.getLaunchMode());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_ENVIRONMENT, launchMetadata.getLaunchEnvironment());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_HOOK, launchMetadata.getExecutionHook());
    setOrRemoveProperty(fileNode, ScriptNode.APM_LAUNCH_SCHEDULE, launchMetadata.getExecutionSchedule());
    removeProperty(fileNode, ScriptNode.APM_LAST_EXECUTED);
    JcrUtils.setLastModified(fileNode, Calendar.getInstance());
    session.save();
    result = scriptFinder.find(fileNode.getPath(), resolver);
  } catch (RepositoryException e) {
    LOG.error(e.getMessage(), e);
  }
  return result;
}
 
Example 22
Source Project: jackalope   Source File: PageManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page create(String parentPath, String pageName, String template, String title,
                   boolean autoSave) throws WCMException {
    if (parentPath == null) throw new IllegalArgumentException("Parent path can't be null.");
    if (pageName == null && title == null)
        throw new IllegalArgumentException("Page and title name can't be both null.");
    if (template != null && !template.isEmpty())
        throw new UnsupportedOperationException("Templates are not supported.");

    try {
        Node parent = JcrUtils.getOrCreateByPath(parentPath, JcrConstants.NT_UNSTRUCTURED, session);

        if (pageName == null || pageName.isEmpty())
            pageName = JcrUtil.createValidName(title, JcrUtil.HYPHEN_LABEL_CHAR_MAPPING);
        if (!JcrUtil.isValidName(pageName)) throw new IllegalArgumentException("Illegal page name: " + pageName);

        Node pageNode = parent.addNode(pageName, JcrConstants.CQ_PAGE);
        Node contentNode = pageNode.addNode("jcr:content", JcrConstants.CQ_PAGE_CONTENT);

        if (title != null && !title.isEmpty()) contentNode.setProperty("jcr:title", title);
        if (autoSave) {
            session.save();
        }

        return getPage(pageNode.getPath());
    }
    catch (RepositoryException e) {
        throw new WCMException("Unable to create page", e);
    }
}
 
Example 23
Source Project: jackrabbit-filevault   Source File: JcrPackageRegistry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the primary package root. If the root does not exist yet and {@code autoCreate} is {@code true} it will
 * be created.
 *
 * @param autoCreate if {@code true} the roots are created if missing.
 * @return the the package root or {@code null}
 * @throws RepositoryException if an error occurs.
 */
@Nullable
public Node getPrimaryPackageRoot(boolean autoCreate) throws RepositoryException {
    if (packRoots[0] == null) {
        if (session.nodeExists(packRootPaths[0])) {
            packRoots[0] = session.getNode(packRootPaths[0]);
        } else if (autoCreate) {
            if (session.hasPendingChanges()) {
                throw new RepositoryException("Unwilling to create package root folder while session has transient changes.");
            }
            packRoots[0] = JcrUtils.getOrCreateByPath(packRootPaths[0], NodeType.NT_FOLDER, NodeType.NT_FOLDER, session, true);
        }
    }
    return packRoots[0];
}
 
Example 24
/**
 * Tests if an 'empty' node serialization includes the jcr namespace. see JCRVLT-266
 */
@Test
public void testFormatterIncludesJcrNamespace() throws Exception {
    // rep:itemNames restrictions are only supported in oak.
    Assume.assumeTrue(isOak());

    JcrUtils.getOrCreateByPath("/testroot", NodeType.NT_UNSTRUCTURED, admin);
    admin.save();

    // setup access control
    AccessControlManager acMgr = admin.getAccessControlManager();
    JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, "/testroot");

    Privilege[] privs = new Privilege[]{acMgr.privilegeFromName(Privilege.JCR_READ)};
    Map<String, Value[]> rest = new HashMap<>();
    rest.put("rep:itemNames", new Value[]{
            admin.getValueFactory().createValue("jcr:mixinTypes", PropertyType.NAME),
            admin.getValueFactory().createValue("jcr:primaryType", PropertyType.NAME)
    });
    acl.addEntry(EveryonePrincipal.getInstance(), privs, false, null, rest);
    acMgr.setPolicy("/testroot", acl);
    admin.save();

    Session guest = repository.login(new GuestCredentials());

    DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter();
    filter.add(new PathFilterSet("/testroot"));
    RepositoryAddress addr = new RepositoryAddress("/" + admin.getWorkspace().getName() + "/");
    VaultFileSystem jcrfs = Mounter.mount(null, filter, addr, null, guest);
    Aggregate a = jcrfs.getAggregateManager().getRoot().getAggregate("testroot");
    DocViewSerializer s = new DocViewSerializer(a);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    s.writeContent(out);

    assertEquals("valid xml",
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<jcr:root xmlns:jcr=\"http://www.jcp.org/jcr/1.0\"/>\n", out.toString("utf-8"));
}
 
Example 25
Source Project: jackrabbit-filevault   Source File: RCPTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMixin() throws IOException, RepositoryException, ConfigurationException {
    Node a = JcrUtils.getOrCreateByPath(SRC_TEST_NODE_PATH, NodeType.NT_FOLDER, NodeType.NT_FOLDER, admin, true);
    RepositoryCopier rcp = new RepositoryCopier();
    a.addMixin(NodeType.MIX_TITLE);
    a.setProperty("jcr:title", "Hello");
    admin.save();

    rcp.copy(admin, SRC_PATH, admin, DST_PATH, true);
    assertProperty(DST_TEST_NODE_PATH + "/jcr:title", "Hello");
    assertProperty(DST_TEST_NODE_PATH + "/jcr:mixinTypes", new String[]{"mix:title"});
}
 
Example 26
Source Project: jackrabbit-filevault   Source File: RCPTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveMixin() throws IOException, RepositoryException, ConfigurationException {
    Node a = JcrUtils.getOrCreateByPath(SRC_TEST_NODE_PATH, NodeType.NT_FOLDER, NodeType.NT_FOLDER, admin, true);
    RepositoryCopier rcp = new RepositoryCopier();
    a.addMixin(NodeType.MIX_TITLE);
    a.setProperty("jcr:title", "Hello");
    admin.save();

    rcp.copy(admin, SRC_PATH, admin, DST_PATH, true);
    assertProperty(DST_TEST_NODE_PATH + "/jcr:title", "Hello");
    assertProperty(DST_TEST_NODE_PATH + "/jcr:mixinTypes", new String[]{"mix:title"});


    a.removeMixin(NodeType.MIX_TITLE);
    admin.save();
    // removing a mixing should remove the undeclared properties
    assertPropertyMissing(SRC_TEST_NODE_PATH + "/jcr:title");
    assertPropertyMissingOrEmpty(SRC_TEST_NODE_PATH + "/jcr:mixinTypes");

    rcp = new RepositoryCopier();
    rcp.setOnlyNewer(false);
    rcp.setUpdate(true);
    rcp.copy(admin, SRC_PATH, admin, DST_PATH, true);

    assertNodeExists(DST_TEST_NODE_PATH);
    assertPropertyMissing(DST_TEST_NODE_PATH + "/jcr:title");
    assertPropertyMissingOrEmpty(DST_TEST_NODE_PATH + "/jcr:mixinTypes");
}
 
Example 27
private String storeFile(boolean compressible, String mimeType, int size)
        throws RepositoryException {
    String path = String.format("%s/%s", TEST_PARENT_PATH, fileName(compressible, mimeType, size));
    Node node = JcrUtils.getOrCreateByPath(path, "nt:unstructured", admin);
    byte[] data = compressible ? compressibleData(size) : incompressibleData(size);
    JcrUtils.putFile(node, "file", mimeType, new ByteArrayInputStream(data));
    admin.save();
    return node.getPath();
}
 
Example 28
Source Project: jackrabbit-filevault   Source File: DumpCoverageTests.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws RepositoryException {
    clean(TEST_ROOT);

    JcrUtils.getOrCreateByPath(TEST_ROOT, "nt:folder", admin);
    for (String path: ALL_PAGES) {
        JcrUtils.getOrCreateByPath(path, "nt:folder", admin);
        JcrUtils.getOrCreateByPath(path + "/jcr:content", "nt:folder", admin);
    }
}
 
Example 29
@Override
public Folder getFolder(final String path) {
    return jcrTemplate.execute(session -> {
        Node rootNode = session.getRootNode();
        Node node = JcrUtils.getNodeIfExists(rootNode, path);
        if (node != null) {
            if (isNodeFolder(node)) {
                return convertNodeToFolder(node);
            }
        }

        return null;
    });
}
 
Example 30
@Override
public List<Page> getPages(final String path, final String requestedUser) {
    return jcrTemplate.execute(session -> {
        Node rootNode = session.getRootNode();
        Node node = JcrUtils.getNodeIfExists(rootNode, path);
        if (node != null) {
            if (isNodeFolder(node)) {
                List<Page> pages = new ArrayList<>();
                NodeIterator childNodes = node.getNodes();
                while (childNodes.hasNext()) {
                    Node childNode = childNodes.nextNode();
                    if (isNodePage(childNode)) {
                        if (isAccessible(childNode, requestedUser)) {
                            Page page = convertNodeToPage(childNode);
                            pages.add(page);
                        }
                    }
                }

                return pages;
            } else {
                throw new ContentException(String.format("Do not support any node type except mycollab:folder. The current node has type: %s and its path is %s",
                        node.getPrimaryNodeType().getName(), path));
            }
        }
        return new ArrayList<Page>();
    });
}