javax.jcr.RepositoryException Java Examples

The following examples show how to use javax.jcr.RepositoryException. 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
Source File: TestFilteredPropertyExport.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Test
public void filterRelativePropertiesSingleSet_NotDeep_no_propertyFilter_addNodes() throws IOException, RepositoryException, PackageException, ConfigurationException {
    PathFilterSet nodes = new PathFilterSet("/tmp");

    DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter();
    nodes.addInclude(new DefaultPathFilter("/tmp"));

    filter.add(nodes);

    // export and extract
    File pkgFile = assemblePackage(filter);
    clean("/tmp");
    try (VaultPackage vp = packMgr.open(pkgFile)) {
        vp.extract(admin, getDefaultOptions());
        // validate the extracted content
        assertPropertiesExist("/tmp", "p1", "p2", "p3");
        assertNodeMissing("/tmp/foo");
        assertNodeMissing("/tmp/foo/bar");
    } finally {
        pkgFile.delete();
    }
}
 
Example #2
Source File: CatalogDataProviderManagerConfTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException, RepositoryException {
    // load sample content
    context.load().json("/context/jcr-conf.json", "/conf/testing/settings");
    context.load().json("/context/jcr-dataroots.json", COMMERCE_ROOT);
    context.load().json("/context/jcr-wrong-conf.json", "/conf/wrong-configuration/settings");

    // register the services
    context.registerService(new MockResourceResolverFactory());
    FactoryConfig factoryConfig = new FactoryConfig(false);

    Map<String, String> properties = factoryConfig.properties;
    context.registerService(CatalogDataResourceProviderFactory.class, factoryConfig.factory, properties);

    ServiceUserMapped serviceUserMapped = Mockito.mock(ServiceUserMapped.class);
    context.registerService(ServiceUserMapped.class, serviceUserMapped, ImmutableMap.of(ServiceUserMapped.SUBSERVICENAME,
        "virtual-products-service"));

    manager = context.registerInjectActivateService(new CatalogDataResourceProviderManagerImpl());
}
 
Example #3
Source File: TestEmptyPackage.java    From jackrabbit-filevault with 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 #4
Source File: WebdavProviderTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
private static void importFiles(final Node parent, final File sourceDir) throws RepositoryException, IOException {
    final File[] files = sourceDir.listFiles();
    for (final File file : files) {
        if (file.isFile()) {
            final InputStream data = new FileInputStream(file);
            try {
                message("Importing file " + file);
                JcrUtils.putFile(parent, file.getName(), "application/octet-stream", data);
            } finally {
                data.close();
            }
        } else if (file.isDirectory()) {
            message("Importing folder " + file);
            final Node folder = JcrUtils.getOrAddFolder(parent, file.getName());
            importFiles(folder, file);
        }
    }
}
 
Example #5
Source File: DefaultWorkspaceFilter.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void dumpCoverage(Session session, ProgressTrackerListener listener, boolean skipJcrContent)
        throws RepositoryException {
    ProgressTracker tracker = new ProgressTracker(listener);
    // get common ancestor
    Tree<PathFilterSet> tree = new Tree<PathFilterSet>();
    for (PathFilterSet set: nodesFilterSets) {
        tree.put(set.getRoot(), set);
    }
    String rootPath = tree.getRootPath();
    javax.jcr.Node rootNode;
    if (session.nodeExists(rootPath)) {
        rootNode = session.getNode(rootPath);
    } else if (session.nodeExists("/")) {
        log.warn("Common ancestor {} not found. Using root node", rootPath);
        rootNode = session.getRootNode();
        rootPath = "/";
    } else {
        throw new PathNotFoundException("Common ancestor " + rootPath+ " not found.");
    }
    log.debug("Starting coverage dump at {} (skipJcrContent={})", rootPath, skipJcrContent);
    dumpCoverage(rootNode, tracker, skipJcrContent);
}
 
Example #6
Source File: TestUserContentPackage.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Test
public void installUserA_Profile_Picture() throws RepositoryException, IOException, PackageException {
    // install default user at package path
    User userA = installUserA(ImportMode.REPLACE, true, true);
    String authPath = userA.getPath();

    assertPropertyMissing(authPath + "/" + NAME_PROFILE_PROPERTY);

    // install updated profile
    JcrPackage pack = packMgr.upload(getStream("/test-packages/test_user_a_profile_picture.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());

    assertProperty(authPath + "/" + NAME_PROFILE_FULLNAME, "Test User");
    assertProperty(authPath + "/" + NAME_PROFILE_PROPERTY, "a");
    assertNodeExists(authPath + "/" + NAME_PROFILE_PICTURE_NODE);
}
 
Example #7
Source File: PropertyValueArtifact.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @return a input source which systemId is the path of the underlying property
 */
public VaultInputSource getInputSource() throws IOException, RepositoryException {
    final InputStream in = getInputStream();
    return new VaultInputSource() {

        @Override
        public String getSystemId() {
            return path;
        }

        @Override
        public InputStream getByteStream() {
            return in;
        }


        public long getContentLength() {
            return PropertyValueArtifact.this.getContentLength();
        }

        public long getLastModified() {
            return PropertyValueArtifact.this.getLastModified();
        }
    };
}
 
Example #8
Source File: TestSubPackages.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Installs 2 packages that contains same sub packages with different version
 */
@Test
public void testSkipOlderVersionInstallation() throws RepositoryException, IOException, PackageException {
    JcrPackage packNewer = packMgr.upload(getStream("/test-packages/subtest_extract_contains_newer_version.zip"), false);
    assertNotNull(packNewer);

    // install package that contains newer version of the sub package first
    ImportOptions opts = getDefaultOptions();
    opts.setNonRecursive(false);
    packNewer.install(opts);

    // check for sub packages version 1.0.1 exists
    assertPackageNodeExists(PACKAGE_ID_SUB_TEST_101);
    assertTrue(packMgr.open(admin.getNode(getInstallationPath(PACKAGE_ID_SUB_TEST_101))).isInstalled());
    assertNodeExists("/tmp/b");

    opts = getDefaultOptions();
    opts.setNonRecursive(false);
    JcrPackage packOlder = packMgr.upload(getStream("/test-packages/subtest_extract_contains_older_version.zip"), false);
    packOlder.install(opts);
    assertPackageNodeExists(PACKAGE_ID_SUB_TEST_10);
    assertFalse(packMgr.open(admin.getNode(getInstallationPath(PACKAGE_ID_SUB_TEST_10))).isInstalled());
    assertNodeMissing("/tmp/a");

}
 
Example #9
Source File: RepositoryRefactor.java    From urule with Apache License 2.0 6 votes vote down vote up
private void buildPath(List<String> list, Node parentNode) throws RepositoryException {
	NodeIterator nodeIterator=parentNode.getNodes();
	while(nodeIterator.hasNext()){
		Node node=nodeIterator.nextNode();
		String nodePath=node.getPath();
		if(nodePath.endsWith(FileType.Ruleset.toString())){
			list.add(nodePath);
		}else if(nodePath.endsWith(FileType.UL.toString())){
			list.add(nodePath);
		}else if(nodePath.endsWith(FileType.DecisionTable.toString())){
			list.add(nodePath);
		}else if(nodePath.endsWith(FileType.ScriptDecisionTable.toString())){
			list.add(nodePath);
		}else if(nodePath.endsWith(FileType.DecisionTree.toString())){
			list.add(nodePath);					
		}else if(nodePath.endsWith(FileType.RuleFlow.toString())){
			list.add(nodePath);					
		}
		buildPath(list,node);
	}
}
 
Example #10
Source File: TestPackageInstall.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Installs a package with a different node type
 */
@Test
public void testNodeTypeChange() throws RepositoryException, IOException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("/test-packages/tmp.zip"), false);
    assertNotNull(pack);
    assertPackageNodeExists(TMP_PACKAGE_ID);

    ImportOptions opts = getDefaultOptions();
    pack.install(opts);

    assertNodeExists("/tmp/foo");
    assertEquals(admin.getNode("/tmp").getPrimaryNodeType().getName(), "sling:OrderedFolder");

    pack = packMgr.upload(getStream("/test-packages/tmp_nt_folder.zip"), false);
    assertNotNull(pack);
    assertPackageNodeExists(TMP_PACKAGE_ID);

    pack.install(opts);

    assertNodeExists("/tmp/foo");
    assertEquals(admin.getNode("/tmp").getPrimaryNodeType().getName(), "nt:folder");
}
 
Example #11
Source File: DestroyUser.java    From APM with Apache License 2.0 6 votes vote down vote up
@Override
public ActionResult simulate(Context context) throws ActionExecutionException {
  ActionResult actionResult;
  try {
    User user = context.getAuthorizableManager().getUser(userId);
    context.setCurrentAuthorizable(user);
    Action removeFromGroups = new RemoveParents(getGroups(user));
    ActionResult purgeResult = purge.simulate(context);
    ActionResult removeFromGroupsResult = removeFromGroups.execute(context);
    ActionResult removeResult = remove.simulate(context);
    actionResult = purgeResult.merge(removeFromGroupsResult, removeResult);
  } catch (RepositoryException | ActionExecutionException e) {
    actionResult = context.createActionResult();
    actionResult.logError(MessagingUtils.createMessage(e));
  }
  return actionResult;
}
 
Example #12
Source File: TestUserContentPackage.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
@Test
public void installUserA_Profile_Picture_NonExistingUser() throws RepositoryException, IOException, PackageException {
    UserManager mgr = ((JackrabbitSession) admin).getUserManager();
    assertNull("test-user-a must not exist", mgr.getAuthorizable(ID_TEST_USER_A));

    // install updated profile
    JcrPackage pack = packMgr.upload(getStream("/test-packages/test_user_a_profile_picture.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());

    Authorizable user = mgr.getAuthorizable(ID_TEST_USER_A);
    assertNotNull("test-user-a must exist", user);

    // image profile must exist
    assertNodeExists(user.getPath() + "/" + NAME_PROFILE_PICTURE_NODE);
}
 
Example #13
Source File: DocViewSAXFormatter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
protected DocViewSAXFormatter(Aggregate aggregate, XMLStreamWriter writer)
        throws RepositoryException {

    this.aggregate = aggregate;
    this.session = aggregate.getNode().getSession();
    nsResolver = new SessionNamespaceResolver(session);
    itemNameComparator = new ItemNameComparator2(nsResolver);
    this.writer = writer;

    DefaultNamePathResolver npResolver = new DefaultNamePathResolver(nsResolver);

    // resolve the names of some well known properties
    // allowing for session-local prefix mappings
    try {
        jcrPrimaryType = npResolver.getJCRName(NameConstants.JCR_PRIMARYTYPE);
        jcrMixinTypes = npResolver.getJCRName(NameConstants.JCR_MIXINTYPES);
        jcrUUID = npResolver.getJCRName(NameConstants.JCR_UUID);
        jcrRoot = npResolver.getJCRName(NameConstants.JCR_ROOT);
        ntUnstructured = npResolver.getJCRName(NameConstants.NT_UNSTRUCTURED);
    } catch (NamespaceException e) {
        // should never get here...
        String msg = "internal error: failed to resolve namespace mappings";
        throw new RepositoryException(msg, e);
    }

    useBinaryReferences = "true".equals(aggregate.getManager().getConfig().getProperty(VaultFsConfig.NAME_USE_BINARY_REFERENCES));
}
 
Example #14
Source File: SyncHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void syncTree(Session session, SyncMode direction) throws RepositoryException, IOException {
    TreeSync tree = createTreeSync(direction);
    tree.sync(session.getRootNode(), fileRoot);
    // flush fs changes
    observer.checkAndNotify();
    pendingFsChanges.clear();
}
 
Example #15
Source File: Activator.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Create user groups for authors and testers.
 *
 * @param bundleContext The bundle context provided by the component.
 */
private void createGroups(BundleContext bundleContext){
    ServiceReference SlingRepositoryFactoryReference = bundleContext.getServiceReference(SlingRepository.class.getName());
    SlingRepository repository = (SlingRepository)bundleContext.getService(SlingRepositoryFactoryReference);

    Session session = null;

    if (repository != null) {
        try {
            session = repository.loginAdministrative(null);

            if (session != null && session instanceof JackrabbitSession) {
                UserManager userManager = ((JackrabbitSession)session).getUserManager();
                ValueFactory valueFactory = session.getValueFactory();

                Authorizable authors = userManager.getAuthorizable(PublickConstants.GROUP_ID_AUTHORS);

                if (authors == null) {
                    authors = userManager.createGroup(PublickConstants.GROUP_ID_AUTHORS);
                    authors.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_AUTHORS));
                }

                Authorizable testers = userManager.getAuthorizable(PublickConstants.GROUP_ID_TESTERS);

                if (testers == null) {
                    testers = userManager.createGroup(PublickConstants.GROUP_ID_TESTERS);
                    testers.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_TESTERS));
                }
            }
        } catch (RepositoryException e) {
            LOGGER.error("Could not get session", e);
        } finally {
            if (session != null && session.isLive()) {
                session.logout();
                session = null;
            }
        }
    }
}
 
Example #16
Source File: JackrabbitACLImporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public List<String> close() throws SAXException, RepositoryException {
    if (states.peek() != State.INITIAL) {
        log.error("Unexpected end state: {}", states.peek());
    }
    List<String> paths = new ArrayList<>();
    importPolicy.apply(paths);
    return paths;
}
 
Example #17
Source File: StorageUpdate1.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void createChartsNode() throws RepositoryException {
	LOG.info("Creating charts node");
	
       Node rootNode = getTemplate().getRootNode();
       Node nextServerNode = rootNode.getNode(StorageConstants.NEXT_SERVER_FOLDER_NAME);
       
       Node chartsNode = nextServerNode.addNode(StorageConstants.CHARTS_FOLDER_NAME);
       chartsNode.addMixin("mix:referenceable");
       chartsNode.setProperty("className", Folder.class.getName());
       
       getTemplate().save();
}
 
Example #18
Source File: PageServiceImpl.java    From mycollab with GNU Affero General Public License v3.0 5 votes vote down vote up
private static boolean isNodeFolder(Node node) {
    try {
        return node.isNodeType("wiki:folder");
    } catch (RepositoryException e) {
        return false;
    }
}
 
Example #19
Source File: JarExporterTest.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * This test verifies that writing entries that can be compressed together with entries that are already compressed according to
 * {@link org.apache.jackrabbit.vault.fs.impl.io.CompressionUtil} to the same file does result in a readable jar.
 * <p/>
 * There are certain environments that don't support changing the compression level for individual entries due to defects in the jdk
 * and breaking changes made in recent zlib versions.
 *
 * @link https://issues.apache.org/jira/browse/JCRVLT-257
 * @link https://github.com/madler/zlib/issues/305
 */
@Test
public void testEntriesWithSuppressedCompression() throws RepositoryException, IOException {
    Mocks m = new Mocks("org/apache/jackrabbit/vault/fs/io/JarExporter/testEntriesWithSuppressedCompression");
    for (int level : new int[] { NO_COMPRESSION, BEST_COMPRESSION, BEST_SPEED }) {
        File target = File.createTempFile("testEntriesWithSuppressedCompression", ".zip", null);
        ZipStreamArchive archive = null;
        try {
            JarExporter exporter = new JarExporter(target, level);
            exporter.open();
            exporter.writeFile(m.mockFile(".content.xml", "application/xml"), null);
            exporter.writeFile(m.mockFile("content/.content.xml", "application/xml"), null);
            exporter.writeFile(m.mockFile("content/dam/.content.xml", "application/xml"), null);
            // export a file that according to org.apache.jackrabbit.vault.fs.impl.io.CompressionUtil should not be compressed
            exporter.writeFile(m.mockFile("content/dam/asf_logo.png", "image/png"), null);
            exporter.close();
            // now read the zip file
            archive = new ZipStreamArchive(new FileInputStream(target));
            archive.open(false); // this will throw, when the zip file is corrupt
            // 8 entries including root and jcr_root
            assertEquals("Wrong entry count for level " + level, 8, countEntries(archive.getRoot()));
        } catch (ZipException ex) {
            throw new AssertionError("Zip failed for level " + level, ex);
        } finally {
            if (archive != null) {
                archive.close();
            }
            target.delete();
        }
    }
}
 
Example #20
Source File: DumpCoverageTests.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoJcrContentCoverage() throws IOException, RepositoryException, ConfigurationException {
    DefaultWorkspaceFilter filter = new DefaultWorkspaceFilter();
    PathFilterSet set1 = new PathFilterSet(TEST_ROOT + "/content");
    filter.add(set1);
    Collector listener = new Collector();
    filter.dumpCoverage(admin, listener, true);
    checkResults("Partial coverage needs to include all pages", ALL_PAGES, listener.paths);
}
 
Example #21
Source File: ItemNameComparator2.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public int compare(Item o1, Item o2) {
    try {
        return QNameComparator.INSTANCE.compare(getQName(o1.getName()), getQName(o2.getName()));
    } catch (RepositoryException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #22
Source File: CheckIncludes.java    From APM with Apache License 2.0 5 votes vote down vote up
private Group tryGetGroup(final Context context, final ActionResult actionResult) {
  try {
    return context.getAuthorizableManager().getGroup(authorizableId);
  } catch (RepositoryException | ActionExecutionException e) {
    actionResult.logError(MessagingUtils.createMessage(e));
  }
  return null;
}
 
Example #23
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public RegisteredPackage open(@NotNull PackageId id) throws IOException {
    try {
        Node node = getPackageNode(id);
        if (node == null && baseRegistry != null) {
            return baseRegistry.open(id);
        }
        return node == null ? null : new JcrRegisteredPackage(open(node, false));
    } catch (RepositoryException e) {
        throw new IOException(e);
    }
}
 
Example #24
Source File: NodeResourceImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public String getResourceType() {
    try {
        return getResourceTypeForNode(node);
    }
    catch (RepositoryException re) {
        return null; /* ignore */
    }
}
 
Example #25
Source File: TestCustomPrivileges.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Installs a package that contains a custom privilege and then checks if it was installed.
 */
@Test
public void installWithPrivs() throws RepositoryException, IOException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("/test-packages/privileges.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());

    // check if privilege was installed
    PrivilegeManager mgr = ((JackrabbitWorkspace) admin.getWorkspace()).getPrivilegeManager();
    try {
        mgr.getPrivilege("testns:testpriv");
    } catch (RepositoryException e) {
        fail("testns:testpriv privilege not registered.");
    }
}
 
Example #26
Source File: TestPackageInstall.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Installs a package that just adds a property to the root node.
 */
@Test
public void testRootImport() throws RepositoryException, IOException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("/test-packages/testrootimport.zip"), false);
    assertNotNull(pack);

    // just extract - no snapshots
    pack.extract(getDefaultOptions());
    assertProperty("/testproperty", "hello");
}
 
Example #27
Source File: DocViewSAXImporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void ensureCheckedOut() throws RepositoryException {
    if (!isCheckedOut) {
        importInfo.registerToVersion(node.getPath());
        try {
            node.checkout();
        } catch (RepositoryException e) {
            log.warn("error while checkout node (ignored)", e);
        }
        isCheckedOut = true;
    }
    if (!isParentCheckedOut) {
        stack.ensureCheckedOut();
        isParentCheckedOut = true;
    }
}
 
Example #28
Source File: NodeImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
public PropertyIterator getProperties() throws RepositoryException {
    List<Property> children = new ArrayList<>();
    for (Item item : session.getChildren(this))
        if (!item.isNode())
            children.add((Property)item);
    return new PropertyIteratorImpl(children);
}
 
Example #29
Source File: JcrStorageDao.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
public boolean isEntityReferenced(String path) throws NotFoundException {
	checkPath(path);

	try {
		return getNode(path).getReferences().hasNext();
	} catch (RepositoryException e) {
		throw convertJcrAccessException(e);
	}
}
 
Example #30
Source File: DocViewSAXImporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void startDocument() throws SAXException {
    try {
        stack = new StackElement(parentNode, parentNode.isNew());
    } catch (RepositoryException e) {
        throw new SAXException(e);
    }
}