Java Code Examples for javax.jcr.Node#hasNode()

The following examples show how to use javax.jcr.Node#hasNode() . 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: BaseRepositoryService.java    From urule with Apache License 2.0 8 votes vote down vote up
@Override
public InputStream readFile(String path,String version) throws Exception{
	if(StringUtils.isNotBlank(version)){
		repositoryInteceptor.readFile(path+":"+version);
		return readVersionFile(path, version);
	}
	repositoryInteceptor.readFile(path);
	Node rootNode=getRootNode();
	int colonPos = path.lastIndexOf(":");
	if (colonPos > -1) {
		version = path.substring(colonPos + 1, path.length());
		path = path.substring(0, colonPos);
		return readFile(path, version);
	}
	path = processPath(path);
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	Node fileNode = rootNode.getNode(path);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	return fileBinary.getStream();
}
 
Example 2
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 7 votes vote down vote up
@Override
public void unlockPath(String path,User user) throws Exception{
	path = processPath(path);
	int pos=path.indexOf(":");
	if(pos!=-1){
		path=path.substring(0,pos);
	}
	Node rootNode=getRootNode();
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	Node fileNode = rootNode.getNode(path);
	String absPath=fileNode.getPath();
	if(!lockManager.isLocked(absPath)){
		throw new NodeLockException("当前文件未锁定,不需要解锁!");
	}
	Lock lock=lockManager.getLock(absPath);
	String owner=lock.getLockOwner();
	if(!owner.equals(user.getUsername())){
		throw new NodeLockException("当前文件由【"+owner+"】锁定,您无权解锁!");
	}
	lockManager.unlock(lock.getNode().getPath());
}
 
Example 3
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public void removeNamespace(RepositorySession session, String repositoryId, String projectId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node root = jcrSession.getRootNode();
        String path = getNamespacePath(repositoryId, projectId);
        if (root.hasNode(path)) {
            Node node = root.getNode(path);
            if (node.isNodeType(NAMESPACE_MIXIN_TYPE)) {
                node.remove();
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example 4
Source File: JcrPackageManagerImpl.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * internally lists all the packages below the given package root and adds them to the given list.
 * @param pkgRoot the package root
 * @param packages the list of packages
 * @param group optional group to search below
 * @param built if {@code true} only packages with size > 0 are returned
 * @throws RepositoryException if an error occurrs
 */
private void listPackages(Node pkgRoot, List<JcrPackage> packages, String group, boolean built) throws RepositoryException {
    if (group == null || group.length() == 0) {
        listPackages(pkgRoot, packages, null, built, false);
    } else {
        if (group.equals(pkgRoot.getPath())) {
            group = "";
        } else if (group.startsWith(pkgRoot.getPath() + "/")) {
            group = group.substring(pkgRoot.getPath().length() + 1);
        }
        if (group.startsWith("/")) {
            // don't scan outside the roots
            return;
        }
        Node root = pkgRoot;
        if (group.length() > 0) {
            if (root.hasNode(group)) {
                root = root.getNode(group);
            } else {
                return;
            }
        }
        listPackages(root, packages, null, built, true);
    }
}
 
Example 5
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
public void fileRename(String path, String newPath) throws Exception{
	if(!permissionService.isAdmin()){
		throw new NoPermissionException();
	}
	
	repositoryInteceptor.renameFile(path, newPath);
	path = processPath(path);
	newPath = processPath(newPath);
	Node rootNode=getRootNode();
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	session.getWorkspace().move("/" + path, "/" + newPath);
	session.save();
}
 
Example 6
Source File: JcrExporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private Node getOrCreateItem(String relPath, boolean isDir) throws IOException {
    try {
        String[] segments = Text.explode(relPath, '/');
        Node root = localParent;
        for (int i=0; i<segments.length; i++) {
            String s = segments[i];
            if (root.hasNode(s)) {
                root = root.getNode(s);
                if (isDir) {
                    exportInfo.update(ExportInfo.Type.NOP, root.getPath());
                } else {
                    exportInfo.update(ExportInfo.Type.UPDATE, root.getPath());
                }
            } else {
                if (i == segments.length -1 && !isDir) {
                    root = root.addNode(s, JcrConstants.NT_FILE);
                    exportInfo.update(ExportInfo.Type.ADD, root.getPath());
                } else {
                    root = root.addNode(s, JcrConstants.NT_FOLDER);
                    exportInfo.update(ExportInfo.Type.MKDIR, root.getPath());
                }
            }
        }
        return root;
    } catch (RepositoryException e) {
        IOException io = new IOException("Error while creating item " + relPath);
        io.initCause(e);
        throw io;
    }
}
 
Example 7
Source File: ScriptStorageImpl.java    From APM with Apache License 2.0 5 votes vote down vote up
private String generateFileName(String fileName, Node saveNode) throws RepositoryException {
  String baseName = FilenameUtils.getBaseName(fileName);
  int num = 1;
  do {
    fileName = baseName + ((num > 1) ? ("-" + num) : "") + Apm.FILE_EXT;
    num++;
  } while (saveNode.hasNode(fileName));

  return fileName;
}
 
Example 8
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void removeFacetFromArtifact(RepositorySession session, String repositoryId, String namespace, String project, String projectVersion,
                                    MetadataFacet metadataFacet)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node root = jcrSession.getRootNode();
        String path = getProjectVersionPath(repositoryId, namespace, project, projectVersion);

        if (root.hasNode(path)) {
            Node node = root.getNode(path);

            for (Node n : JcrUtils.getChildNodes(node)) {
                if (n.isNodeType(ARTIFACT_NODE_TYPE)) {
                    ArtifactMetadata artifactMetadata = getArtifactFromNode(repositoryId, n);
                    log.debug("artifactMetadata: {}", artifactMetadata);
                    MetadataFacet metadataFacetToRemove = artifactMetadata.getFacet(metadataFacet.getFacetId());
                    if (metadataFacetToRemove != null && metadataFacet.equals(metadataFacetToRemove)) {
                        n.remove();
                    }
                }
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example 9
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
private void createFileNode(String path, String content,User user,boolean isFile) throws Exception{
	String createUser=user.getUsername();
	repositoryInteceptor.createFile(path,content);
	Node rootNode=getRootNode();
	path = processPath(path);
	try {
		if (rootNode.hasNode(path)) {
			throw new RuleException("File [" + path + "] already exist.");
		}
		Node fileNode = rootNode.addNode(path);
		fileNode.addMixin("mix:versionable");
		fileNode.addMixin("mix:lockable");
		Binary fileBinary = new BinaryImpl(content.getBytes());
		fileNode.setProperty(DATA, fileBinary);
		if(isFile){
			fileNode.setProperty(FILE, true);				
		}
		fileNode.setProperty(CRATE_USER, createUser);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		DateValue dateValue = new DateValue(calendar);
		fileNode.setProperty(CRATE_DATE, dateValue);
		session.save();
	} catch (Exception ex) {
		throw new RuleException(ex);
	}
}
 
Example 10
Source File: JcrPackageImpl.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Nullable
public Node getDefNode() throws RepositoryException {
    Node content = getContent();
    return content != null && content.hasNode(NN_VLT_DEFINITION)
            ? content.getNode(NN_VLT_DEFINITION)
            : null;
}
 
Example 11
Source File: AbstractJcrDao.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
protected void testDuplication(Node parentNode, String name) throws DuplicationException {
      try {
	if (parentNode.hasNode(name)) {
		throw new DuplicationException("An entity with name '" + name + "' already exists.");
	}
} catch (RepositoryException e) {
	throw convertJcrAccessException(e);
}
  }
 
Example 12
Source File: JcrWorkspaceFilter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public static void saveFilter(WorkspaceFilter filter, Node defNode, boolean save)
        throws RepositoryException {
    if (defNode.hasNode(JcrPackageDefinitionImpl.NN_FILTER)) {
        defNode.getNode(JcrPackageDefinitionImpl.NN_FILTER).remove();
    }
    Node filterNode = defNode.addNode(JcrPackageDefinitionImpl.NN_FILTER);
    int nr = 0;
    for (PathFilterSet set: filter.getFilterSets()) {
        Node setNode = filterNode.addNode("f" + nr);
        setNode.setProperty(JcrPackageDefinitionImpl.PN_ROOT, set.getRoot());
        setNode.setProperty(JcrPackageDefinitionImpl.PN_MODE, set.getImportMode().name().toLowerCase());
        List<String> rules = new LinkedList<String>();
        for (ItemFilterSet.Entry e: set.getEntries()) {
            // expect path filter
            if (!(e.getFilter() instanceof DefaultPathFilter)) {
                throw new IllegalArgumentException("Can only handle default path filters.");
            }
            String type = e.isInclude() ? "include" : "exclude";
            String patt = ((DefaultPathFilter) e.getFilter()).getPattern();
            rules.add(type + ":" + patt);
        }
        setNode.setProperty(JcrPackageDefinitionImpl.PN_RULES, rules.toArray(new String[rules.size()]));
        nr++;
    }
    if (save) {
        defNode.getSession().save();
    }
}
 
Example 13
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void removeMetadataFacets(RepositorySession session, String repositoryId, String facetId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node root = jcrSession.getRootNode();
        String path = getFacetPath(repositoryId, facetId);
        if (root.hasNode(path)) {
            root.getNode(path).remove();
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example 14
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void removeRepository(RepositorySession session, String repositoryId)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    try {
        Node root = jcrSession.getRootNode();
        String path = getRepositoryPath(repositoryId);
        if (root.hasNode(path)) {
            root.getNode(path).remove();
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
 
Example 15
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public void removeTimestampedArtifact(RepositorySession session, ArtifactMetadata artifactMetadata, String baseVersion)
        throws MetadataRepositoryException {
    final Session jcrSession = getSession(session);
    String repositoryId = artifactMetadata.getRepositoryId();

    try {
        Node root = jcrSession.getRootNode();
        String path =
                getProjectVersionPath(repositoryId, artifactMetadata.getNamespace(), artifactMetadata.getProject(),
                        baseVersion);

        if (root.hasNode(path)) {
            Node node = root.getNode(path);

            for (Node n : JcrUtils.getChildNodes(node)) {
                if (n.isNodeType(ARTIFACT_NODE_TYPE)) {
                    if (n.hasProperty("version")) {
                        String version = n.getProperty("version").getString();
                        if (StringUtils.equals(version, artifactMetadata.getVersion())) {
                            n.remove();
                        }
                    }

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


}
 
Example 16
Source File: JcrExporter.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public void writeFile(VaultFile file, String relPath)
        throws RepositoryException, IOException {
    Node local = getOrCreateItem(getPlatformFilePath(file, relPath), false);
    track(local.isNew() ? "A" : "U", relPath);
    Node content;
    if (local.hasNode(JcrConstants.JCR_CONTENT)) {
        content = local.getNode(JcrConstants.JCR_CONTENT);
    } else {
        content = local.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
    }
    Artifact a = file.getArtifact();
    switch (a.getPreferredAccess()) {
        case NONE:
            throw new RepositoryException("Artifact has no content.");

        case SPOOL:
            // we can't support spool
        case STREAM:
            try (InputStream in = a.getInputStream()) {
                Binary b = content.getSession().getValueFactory().createBinary(in);
                content.setProperty(JcrConstants.JCR_DATA, b);
                b.dispose();
            }
            break;
    }
    Calendar now = Calendar.getInstance();
    if (a.getLastModified() >= 0) {
        now.setTimeInMillis(a.getLastModified());
    }
    content.setProperty(JcrConstants.JCR_LASTMODIFIED, now);
    if (a.getContentType() != null) {
        content.setProperty(JcrConstants.JCR_MIMETYPE, a.getContentType());
    } else if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)){
        content.setProperty(JcrConstants.JCR_MIMETYPE, "application/octet-stream");
    }
}
 
Example 17
Source File: BaseRepositoryService.java    From urule with Apache License 2.0 5 votes vote down vote up
private InputStream readVersionFile(String path, String version) throws Exception{
	path = processPath(path);
	Node rootNode=getRootNode();
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	Node fileNode = rootNode.getNode(path);
	VersionHistory versionHistory = versionManager.getVersionHistory(fileNode.getPath());
	Version v = versionHistory.getVersion(version);
	Node fnode = v.getFrozenNode();
	Property property = fnode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	return fileBinary.getStream();
}
 
Example 18
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Override
    public void populateStatistics(RepositorySession repositorySession, MetadataRepository repository, String repositoryId,
                                   RepositoryStatistics repositoryStatistics)
            throws MetadataRepositoryException {
        if (!(repository instanceof JcrMetadataRepository)) {
            throw new MetadataRepositoryException(
                    "The statistics population is only possible for JcrMetdataRepository implementations");
        }
        Session session = getSession(repositorySession);
        // TODO: these may be best as running totals, maintained by observations on the properties in JCR

        try {
            QueryManager queryManager = session.getWorkspace().getQueryManager();

            // TODO: Check, if this is still the case - Switched to Jackrabbit OAK with archiva 3.0
            // Former statement: JCR-SQL2 query will not complete on a large repo in Jackrabbit 2.2.0 - see JCR-2835
            //    Using the JCR-SQL2 variants gives
            //      "org.apache.lucene.search.BooleanQuery$TooManyClauses: maxClauseCount is set to 1024"
//            String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])";
//            Query query = queryManager.createQuery( "SELECT size FROM [archiva:artifact] " + whereClause,
//                                                    Query.JCR_SQL2 );
            String whereClause = "WHERE ISDESCENDANTNODE([/repositories/" + repositoryId + "/content])";
            Query query = queryManager.createQuery("SELECT type,size FROM [" + ARTIFACT_NODE_TYPE + "] " + whereClause, Query.JCR_SQL2);

            QueryResult queryResult = query.execute();

            Map<String, Integer> totalByType = new HashMap<>();
            long totalSize = 0, totalArtifacts = 0;
            for (Row row : JcrUtils.getRows(queryResult)) {
                Node n = row.getNode();
                log.debug("Result node {}", n);
                totalSize += row.getValue("size").getLong();

                String type;
                if (n.hasNode(MavenArtifactFacet.FACET_ID)) {
                    Node facetNode = n.getNode(MavenArtifactFacet.FACET_ID);
                    type = facetNode.getProperty("type").getString();
                } else {
                    type = "Other";
                }
                Integer prev = totalByType.get(type);
                totalByType.put(type, prev != null ? prev + 1 : 1);

                totalArtifacts++;
            }

            repositoryStatistics.setTotalArtifactCount(totalArtifacts);
            repositoryStatistics.setTotalArtifactFileSize(totalSize);
            for (Map.Entry<String, Integer> entry : totalByType.entrySet()) {
                log.info("Setting count for type: {} = {}", entry.getKey(), entry.getValue());
                repositoryStatistics.setTotalCountForType(entry.getKey(), entry.getValue());
            }

            // The query ordering is a trick to ensure that the size is correct, otherwise due to lazy init it will be -1
//            query = queryManager.createQuery( "SELECT * FROM [archiva:project] " + whereClause, Query.JCR_SQL2 );
            query = queryManager.createQuery("SELECT * FROM [archiva:project] " + whereClause + " ORDER BY [jcr:score]",
                    Query.JCR_SQL2);
            repositoryStatistics.setTotalProjectCount(query.execute().getRows().getSize());

//            query = queryManager.createQuery(
//                "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL", Query.JCR_SQL2 );
            query = queryManager.createQuery(
                    "SELECT * FROM [archiva:namespace] " + whereClause + " AND namespace IS NOT NULL ORDER BY [jcr:score]",
                    Query.JCR_SQL2);
            repositoryStatistics.setTotalGroupCount(query.execute().getRows().getSize());
        } catch (RepositoryException e) {
            throw new MetadataRepositoryException(e.getMessage(), e);
        }
    }
 
Example 19
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public JcrPackage upload(InputStream in, boolean replace)
        throws RepositoryException, IOException, PackageExistsException {

    MemoryArchive archive = new MemoryArchive(true);
    InputStreamPump pump = new InputStreamPump(in , archive);

    // this will cause the input stream to be consumed and the memory archive being initialized.
    Binary bin = session.getValueFactory().createBinary(pump);
    if (pump.getError() != null) {
        Exception error = pump.getError();
        log.error("Error while reading from input stream.", error);
        bin.dispose();
        throw new IOException("Error while reading from input stream", error);
    }

    if (archive.getJcrRoot() == null) {
        String msg = "Stream is not a content package. Missing 'jcr_root'.";
        log.error(msg);
        bin.dispose();
        throw new IOException(msg);
    }

    final MetaInf inf = archive.getMetaInf();
    PackageId pid = inf.getPackageProperties().getId();

    // invalidate pid if path is unknown
    if (pid == null) {
        pid = createRandomPid();
    }
    if (!pid.isValid()) {
        bin.dispose();
        throw new RepositoryException("Unable to create package. Illegal package name.");
    }

    // create parent node
    String path = getInstallationPath(pid) + ".zip";
    String parentPath = Text.getRelativeParent(path, 1);
    String name = Text.getName(path);
    Node parent = mkdir(parentPath, false);

    // remember installation state properties (GRANITE-2018)
    JcrPackageDefinitionImpl.State state = null;
    Calendar oldCreatedDate = null;

    if (parent.hasNode(name)) {
        try (JcrPackage oldPackage = new JcrPackageImpl(this, parent.getNode(name))) {
            JcrPackageDefinitionImpl oldDef = (JcrPackageDefinitionImpl) oldPackage.getDefinition();
            if (oldDef != null) {
                state = oldDef.getState();
                oldCreatedDate = oldDef.getCreated();
            }
        }

        if (replace) {
            parent.getNode(name).remove();
        } else {
            throw new PackageExistsException("Package already exists: " + pid).setId(pid);
        }
    }
    JcrPackage jcrPack = null;
    try {
        jcrPack = createNew(parent, pid, bin, archive);
        JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) jcrPack.getDefinition();
        Calendar newCreateDate = def == null ? null : def.getCreated();
        // only transfer the old package state to the new state in case both packages have the same create date
        if (state != null && newCreateDate != null && oldCreatedDate != null && oldCreatedDate.compareTo(newCreateDate) == 0) {
            def.setState(state);
        }
        dispatch(PackageEvent.Type.UPLOAD, pid, null);
        return jcrPack;
    } finally {
        bin.dispose();
        if (jcrPack == null) {
            session.refresh(false);
        } else {
            session.save();
        }
    }
}
 
Example 20
Source File: JcrUtils.java    From commons-vfs with Apache License 2.0 3 votes vote down vote up
/**
 * Returns the named child of the given node, creating the child if it does not already exist. If the child node
 * gets added, then it is created with the given node type. The caller is expected to take care of saving or
 * discarding any transient changes.
 *
 * @see Node#getNode(String)
 * @see Node#addNode(String, String)
 * @see Node#isNodeType(String)
 * @param parent parent node
 * @param name name of the child node
 * @param type type of the child node, ignored if the child already exists
 * @return the child node
 * @throws RepositoryException if the child node can not be accessed or created
 */
public static Node getOrAddNode(final Node parent, final String name, final String type)
        throws RepositoryException {
    if (parent.hasNode(name)) {
        return parent.getNode(name);
    }
    return parent.addNode(name, type);
}