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

The following examples show how to use javax.jcr.Node#getPath() . 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: 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 2
Source File: JcrPackageManagerImplTest.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private String getNextPath(String path) throws RepositoryException {
    Node currentNode = admin.getNode(path);
    if (currentNode.hasNodes()) {
        NodeIterator nodes = currentNode.getNodes();
        while (nodes.hasNext()) {
            Node node = nodes.nextNode();
            if ("jcr:system".equals(node.getName())) {
                continue;
            }
            String nodePath = node.getPath();
            if (visitedPaths.contains(nodePath)) {
                continue;
            } else {
                visitedPaths.add(nodePath);
            }
            return nodePath;
        }
        return getParentPath(path);
    } else {
        return getParentPath(path);
    }
}
 
Example 3
Source File: RepositoryServiceImpl.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 4
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 5
Source File: AggregateManagerImpl.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the artifact manager.
 *
 * @param config the configuration
 * @param wspFilter the workspace filter
 * @param mountpoint the repository address of the mountpoint
 * @param rootNode the root node
 * @param ownSession indicates if the session can be logged out in unmount.
 * @throws RepositoryException if an error occurs.
 */
private AggregateManagerImpl(VaultFsConfig config, WorkspaceFilter wspFilter,
                         RepositoryAddress mountpoint, Node rootNode,
                         boolean ownSession)
        throws RepositoryException {
    session = rootNode.getSession();
    this.mountpoint = mountpoint;
    this.ownSession = ownSession;
    this.config = config;
    workspaceFilter = wspFilter;
    aggregatorProvider = new AggregatorProvider(config.getAggregators());
    artifactHandlers = Collections.unmodifiableList(config.getHandlers());

    // init root node
    Aggregator rootAggregator = rootNode.getDepth() == 0
            ? new RootAggregator()
            : getAggregator(rootNode, null);
    root = new AggregateImpl(this, rootNode.getPath(), rootAggregator);

    // setup node types
    initNodeTypes();
}
 
Example 6
Source File: PageServiceImpl.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
private Folder convertNodeToFolder(Node node) {
    try {
        Folder folder = new Folder();
        folder.setCreatedTime(node.getProperty("jcr:created").getDate());
        folder.setCreatedUser(node.getProperty("wiki:createdUser").getString());
        if (node.hasProperty("wiki:description")) {
            folder.setDescription(node.getProperty("wiki:description").getString());
        } else {
            folder.setDescription("");
        }

        folder.setName(node.getProperty("wiki:name").getString());

        String folderPath = node.getPath();
        if (folderPath.startsWith("/")) {
            folderPath = folderPath.substring(1);
        }
        folder.setPath(folderPath);
        return folder;
    } catch (Exception e) {
        throw new MyCollabException(e);
    }
}
 
Example 7
Source File: AggregateImpl.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void include(Node node, String nodePath) throws RepositoryException {
    if (nodePath == null) {
        nodePath = node.getPath();
    }

    String relPath = nodePath.substring(path.length());
    if (includes == null || !includes.contains(relPath)) {
        if (log.isDebugEnabled()) {
            log.trace("including {} -> {}", path, nodePath);
        }
        if (includes == null) {
            includes = new HashSet<String>();
        }
        includes.add(mgr.cacheString(relPath));
        if (!node.isSame(getNode())) {
            // ensure that parent nodes are included
            include(node.getParent(), null);
        }
    }
}
 
Example 8
Source File: TestCompressionExport.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
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 9
Source File: ChildNodeStash.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * Moves the stashed nodes back below the given parent path.
 * @param parent the new parent node
 * @param importInfo the import info to record the changes
 * @throws RepositoryException if an error occurrs
 */
public void recoverChildren(Node parent, ImportInfo importInfo) throws RepositoryException {
    // move the old child nodes back
    if (tmpNode != null) {
        NodeIterator iter = tmpNode.getNodes();
        boolean hasErrors = false;
        while (iter.hasNext()) {
            Node child = iter.nextNode();
            String newPath = parent.getPath() + "/" + child.getName();
            try {
                if (session.nodeExists(newPath)) {
                    log.debug("Skipping restore from temporary location {} as node already exists at {}", child.getPath(), newPath);
                } else {
                    session.move(child.getPath(), newPath);
                }
            } catch (RepositoryException e) {
                log.warn("Unable to move child back to new location at {} due to: {}. Node will remain in temporary location: {}",
                        new Object[]{newPath, e.getMessage(), child.getPath()});
                if (importInfo != null) {
                    importInfo.onError(newPath, e);
                    hasErrors = true;
                }
            }
        }
        if (!hasErrors) {
            tmpNode.remove();
        }
    }
}
 
Example 10
Source File: GenericAggregator.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean includes(Node root, Node node, String path) throws RepositoryException {
    if (path == null) {
        path = node.getPath();
    }
    return contentFilter.contains(node, path, PathUtil.getDepth(path) - root.getDepth());
}
 
Example 11
Source File: StorageUpdate11.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void convertReports() throws RepositoryException {
	
	String statement = 
			"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
			"//*[@className='ro.nextreports.server.domain.Report' and @type='Next']" + 
			"//*[fn:name()='jcr:content' and @jcr:mimeType='text/xml']";
	  
	QueryResult queryResult = getTemplate().query(statement);

	NodeIterator nodes = queryResult.getNodes();
	LOG.info("Converter 5.1 : Found " + nodes.getSize() + " report nodes");
	while (nodes.hasNext()) {
		
		Node node = nodes.nextNode();
		
		Node reportNode = node.getParent().getParent().getParent().getParent();
		String reportName = reportNode.getName();
		String reportPath = reportNode.getPath();	
		LOG.info(" * Start convert '" + reportPath + "'");						
											
		Property prop = node.getProperty("jcr:data");			
       	String xml = null;
           try {                  	
           	xml = new Converter_5_2().convertFromInputStream(prop.getBinary().getStream(), true);            	            	
           	if (xml != null) {
               	ValueFactory valueFactory = node.getSession().getValueFactory(); 
               	Binary binaryValue = valueFactory.createBinary(new ByteArrayInputStream(xml.getBytes("UTF-8")));
               	node.setProperty ("jcr:data", binaryValue);                	
               	LOG.info("\t -> OK");
               } else {
               	LOG.error("\t -> FAILED : null xml");
               }
           	            	            	
           } catch (Throwable t) {                    	            	            
           	LOG.error("\t-> FAILED : " + t.getMessage(), t);            	
           } 					
           
	}
}
 
Example 12
Source File: NodeNameList.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public boolean restoreOrder(Node parent) throws RepositoryException {
    // assume needsReorder check is performed
    // quick check if node is checked out
    if (!parent.isCheckedOut()) {
        log.warn("Unable to restore order of a checked-in node: " + parent.getPath());
        return false;
    }
    int size = names.size();
    String last = null;
    ArrayList<String> list = new ArrayList<String>(names);
    ListIterator<String> iter = list.listIterator(size);
    while (iter.hasPrevious()) {
        String prev = iter.previous();
        if (parent.hasNode(prev)) {
            log.trace("ordering {} before {}", prev, last);
            try {
                parent.orderBefore(prev, last);
            } catch (Exception e) {
                // probably an error in jcr2spi
                String path = parent.getPath() + "/" + prev;
                log.warn("Ignoring unexpected error during reorder of {}: {}", path, e.toString());
            }
            last = prev;
        }
    }
    return true;
}
 
Example 13
Source File: LinkHelper.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
public void removeLink(Node source, Node target, String name) throws PathNotFoundException, RepositoryException {
	String targetPath = target.getPath();
	Value[] sourceLinks = source.getProperty(name).getValues();
	ArrayList<String> newSourceLinks = new ArrayList<String>();
	for (Value sourceLink : sourceLinks) {
		String link = sourceLink.getString();
		if (!link.equals(target.getPath())) {
			newSourceLinks.add(link);
		}
	}
	String[] newSourceLinksArray = new String[newSourceLinks.size()];
	source.setProperty(name, newSourceLinks.toArray(newSourceLinksArray));
}
 
Example 14
Source File: LinkHelper.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
public void createLink(Node source, Node target, String name) throws PathNotFoundException, RepositoryException {
	String targetPath = target.getPath();
	ArrayList<String> newSourceLinks = new ArrayList<String>();
	if (source.hasProperty(name)) {
		Value[] sourceLinks = source.getProperty(name).getValues();
		for (Value sourceLink : sourceLinks) {
			newSourceLinks.add(sourceLink.getString());
		}
	}
	if (!newSourceLinks.contains(targetPath)) {
		newSourceLinks.add(targetPath);
	}
	String[] newSourceLinksArray = new String[newSourceLinks.size()];
	source.setProperty(name, newSourceLinks.toArray(newSourceLinksArray));
}
 
Example 15
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public void lockPath(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 topAbsPath=fileNode.getPath();
	if(lockManager.isLocked(topAbsPath)){
		String owner=lockManager.getLock(topAbsPath).getLockOwner();
		throw new NodeLockException("【"+path+"】已被"+owner+"锁定,您不能进行再次锁定!");
	}
	List<Node> nodeList=new ArrayList<Node>();
	unlockAllChildNodes(fileNode, user, nodeList, path);
	for(Node node:nodeList){
		if(!lockManager.isLocked(node.getPath())){
			continue;
		}
		Lock lock=lockManager.getLock(node.getPath());
		lockManager.unlock(lock.getNode().getPath());
	}
	if(!fileNode.isNodeType(NodeType.MIX_LOCKABLE)){
		if (!fileNode.isCheckedOut()) {
			versionManager.checkout(fileNode.getPath());
		}
		fileNode.addMixin("mix:lockable");
		session.save();
	}
	lockManager.lock(topAbsPath, true, true, Long.MAX_VALUE, user.getUsername());				
}
 
Example 16
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
private void buildNodeLockInfo(Node node,RepositoryFile file) throws Exception{
	String absPath=node.getPath();
	if(!lockManager.isLocked(absPath)){
		return;
	}
	String owner=lockManager.getLock(absPath).getLockOwner();
	file.setLock(true);
	file.setLockInfo("被"+owner+"锁定");
}
 
Example 17
Source File: FileArtifactHandler.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
private boolean importNtResource(ImportInfo info, Node content, Artifact artifact)
        throws RepositoryException, IOException {

    String path = content.getPath();
    boolean modified = false;
    if (explodeXml && !content.isNodeType(JcrConstants.NT_RESOURCE)) {
        // explode xml
        InputStream in = artifact.getInputStream();
        try {
            content.getSession().importXML(path, in, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
            // can't really augment info here
        } finally {
            in.close();
        }
        modified = true;
    } else {
        ValueFactory factory = content.getSession().getValueFactory();
        Value value = factory.createValue(artifact.getInputStream());
        if (!content.hasProperty(JcrConstants.JCR_DATA)
                || !value.equals(content.getProperty(JcrConstants.JCR_DATA).getValue())) {
            content.setProperty(JcrConstants.JCR_DATA, value);
            modified = true;
        }

        // always update last modified if binary was modified (bug #22969)
        if (!content.hasProperty(JcrConstants.JCR_LASTMODIFIED) || modified) {
            Calendar lastMod = Calendar.getInstance();
            content.setProperty(JcrConstants.JCR_LASTMODIFIED, lastMod);
            modified = true;
        }

        if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)) {
            String mimeType = artifact.getContentType();
            if (mimeType == null) {
                mimeType = Text.getName(artifact.getRelativePath(), '.');
                mimeType = MimeTypes.getMimeType(mimeType, MimeTypes.APPLICATION_OCTET_STREAM);
            }
            content.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
            modified = true;
        }
        if (content.isNew()) {
            // mark binary data as modified
            info.onCreated(path + "/" + JcrConstants.JCR_DATA);
            info.onNop(path);
        } else if (modified) {
            // mark binary data as modified
            info.onModified(path + "/" + JcrConstants.JCR_DATA);
            info.onModified(path);
        }
    }
    return modified;
}
 
Example 18
Source File: DocViewSAXImporter.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
/**
 * Handle an authorizable node
 *
 * @param node the parent node
 * @param ni   doc view node of the authorizable
 * @throws RepositoryException if an error accessing the repository occurrs.
 * @throws SAXException        if an XML parsing error occurrs.
 */
private void handleAuthorizable(Node node, DocViewNode ni) throws RepositoryException, SAXException {
    String id = userManagement.getAuthorizableId(ni);
    String newPath = node.getPath() + "/" + ni.name;
    boolean isIncluded = wspFilter.contains(newPath);
    String oldPath = userManagement.getAuthorizablePath(this.session, id);
    if (oldPath == null) {
        if (!isIncluded) {
            log.trace("auto-creating authorizable node not in filter {}", newPath);
        }

        // just import the authorizable node
        log.trace("Authorizable element detected. starting sysview transformation {}", newPath);
        stack = stack.push();
        stack.adapter = new JcrSysViewTransformer(node);
        stack.adapter.startNode(ni);
        importInfo.onCreated(newPath);
        return;
    }

    Node authNode = session.getNode(oldPath);
    ImportMode mode = wspFilter.getImportMode(newPath);

    // if existing path is not the same as this, we need to register this so that further
    // nodes down the line (i.e. profiles, policies) are imported at the correct location
    // we only follow existing authorizables for non-REPLACE mode and if ignoring this authorizable node
    // todo: check if this also works cross-aggregates
    if (mode != ImportMode.REPLACE || !isIncluded) {
        importInfo.onRemapped(oldPath, newPath);
    }

    if (!isIncluded) {
        // skip authorizable handling - always follow existing authorizable - regardless of mode
        // todo: we also need to check any rep:Memberlist subnodes. see JCRVLT-69
        stack = stack.push(new StackElement(authNode, false));
        importInfo.onNop(oldPath);
        return;
    }

    switch (mode) {
        case MERGE:
            // remember desired memberships.
            // todo: how to deal with multi-node memberships? see JCRVLT-69
            DocViewProperty prop = ni.props.get("rep:members");
            if (prop != null) {
                importInfo.registerMemberships(id, prop.values);
            }

            log.debug("Skipping import of existing authorizable '{}' due to MERGE import mode.", id);
            stack = stack.push(new StackElement(authNode, false));
            importInfo.onNop(newPath);
            break;

        case REPLACE:
            // just replace the entire subtree for now.
            log.trace("Authorizable element detected. starting sysview transformation {}", newPath);
            stack = stack.push();
            stack.adapter = new JcrSysViewTransformer(node);
            stack.adapter.startNode(ni);
            importInfo.onReplaced(newPath);
            break;

        case UPDATE:
            log.trace("Authorizable element detected. starting sysview transformation {}", newPath);
            stack = stack.push();
            stack.adapter = new JcrSysViewTransformer(node, oldPath);
            // we need to tweak the ni.name so that the sysview import does not
            // rename the authorizable node name
            String newName = Text.getName(oldPath);
            DocViewNode mapped = new DocViewNode(
                    newName,
                    newName,
                    ni.uuid,
                    ni.props,
                    ni.mixins,
                    ni.primary
            );
            // but we need to be augment with a potential rep:authorizableId
            if (authNode.hasProperty("rep:authorizableId")) {
                DocViewProperty authId = new DocViewProperty(
                        "rep:authorizableId",
                        new String[]{authNode.getProperty("rep:authorizableId").getString()},
                        false,
                        PropertyType.STRING
                );
                mapped.props.put(authId.name, authId);
            }
            stack.adapter.startNode(mapped);
            importInfo.onReplaced(newPath);
            break;
    }
}
 
Example 19
Source File: DocViewSAXImporter.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    log.trace("<- element {}", qName);
    try {
        // currentNode's import is finished, check if any child nodes
        // need to be removed
        NodeNameList childNames = stack.getChildNames();
        Node node = stack.getNode();
        int numChildren = 0;
        if (node == null) {
            DocViewAdapter adapter = stack.getAdapter();
            if (adapter != null) {
                adapter.endNode();
            }
            // close transformer if last in stack
            if (stack.adapter != null) {
                List<String> createdPaths = stack.adapter.close();
                for (String createdPath : createdPaths) {
                    importInfo.onCreated(createdPath);
                }
                stack.adapter = null;
                log.trace("Sysview transformation complete.");
            }
        } else {
            NodeIterator iter = node.getNodes();
            while (iter.hasNext()) {
                numChildren++;
                Node child = iter.nextNode();
                String path = child.getPath();
                String label = Text.getName(path);
                AccessControlHandling acHandling = getAcHandling(child.getName());
                if (!childNames.contains(label)
                        && !hints.contains(path)
                        && isIncluded(child, child.getDepth() - rootDepth)) {
                    // if the child is in the filter, it belongs to
                    // this aggregate and needs to be removed
                    if (aclManagement.isACLNode(child)) {
                        if (acHandling == AccessControlHandling.OVERWRITE
                                || acHandling == AccessControlHandling.CLEAR) {
                            importInfo.onDeleted(path);
                            aclManagement.clearACL(node);
                        }
                    } else {
                        if (wspFilter.getImportMode(path) == ImportMode.REPLACE) {
                            importInfo.onDeleted(path);
                            // check if child is not protected
                            if (child.getDefinition().isProtected()) {
                                log.debug("Refuse to delete protected child node: {}", path);
                            } else if (child.getDefinition().isMandatory()) {
                                log.debug("Refuse to delete mandatory child node: {}", path);
                            } else {
                                child.remove();
                            }
                        }
                    }
                } else if (acHandling == AccessControlHandling.CLEAR
                        && aclManagement.isACLNode(child)
                        && isIncluded(child, child.getDepth() - rootDepth)) {
                    importInfo.onDeleted(path);
                    aclManagement.clearACL(node);
                }
            }
            if (isIncluded(node, node.getDepth() - rootDepth)) {
                // ensure order
                stack.restoreOrder();
            }
        }
        stack = stack.pop();
        if (node != null && (numChildren == 0 && !childNames.isEmpty() || stack.isRoot())) {
            importInfo.addNameList(node.getPath(), childNames);
        }
    } catch (RepositoryException e) {
        throw new SAXException(e);
    }
}
 
Example 20
Source File: JackrabbitACLImporter.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
public JackrabbitACLImporter(Node accessControlledNode, AccessControlHandling aclHandling)
        throws RepositoryException {
    this(accessControlledNode.getSession(), accessControlledNode.getPath(), aclHandling);
}