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

The following examples show how to use javax.jcr.Node#getNode() . 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: JcrExporter.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
public void writeFile(InputStream in, String relPath) throws IOException {
    try {
        Node content;
        Node local = getOrCreateItem(relPath, false);
        if (local.hasNode(JcrConstants.JCR_CONTENT)) {
            content = local.getNode(JcrConstants.JCR_CONTENT);
        } else {
            content = local.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
        }
        Binary b = content.getSession().getValueFactory().createBinary(in);
        content.setProperty(JcrConstants.JCR_DATA, b);
        content.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
        if (!content.hasProperty(JcrConstants.JCR_MIMETYPE)){
            content.setProperty(JcrConstants.JCR_MIMETYPE, "application/octet-stream");
        }
        b.dispose();
        in.close();
    } catch (RepositoryException e) {
        IOException io = new IOException("Error while writing file " + relPath);
        io.initCause(e);
        throw io;
    }
}
 
Example 3
Source File: FileArtifactHandler.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void importFile(ImportInfo info, Node parent, Artifact primary, String name, boolean exists)
        throws RepositoryException, IOException {
    Node fileNode;
    Node contentNode;
    if (exists) {
        fileNode = parent.getNode(name);
        if (!fileNode.isNodeType(JcrConstants.NT_FILE)) {
            parent.getSession().refresh(false);
            throw new IOException("Incompatible content. Expected a nt:file but was " + fileNode.getPrimaryNodeType().getName());
        }
        contentNode = fileNode.getNode(JcrConstants.JCR_CONTENT);
        info.onNop(fileNode.getPath());
    } else {
        fileNode = parent.addNode(name, JcrConstants.NT_FILE);
        String contentNodeType = primary.getSerializationType() == SerializationType.XML_GENERIC
                && isExplodeXml() ? getXmlNodeType() : JcrConstants.NT_RESOURCE;
        contentNode = fileNode.addNode(JcrConstants.JCR_CONTENT, contentNodeType);
        info.onCreated(fileNode.getPath());
        info.onCreated(contentNode.getPath());
    }
    importNtResource(info, contentNode, primary);
}
 
Example 4
Source File: TreeSync.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void writeNtFile(SyncResult res, Entry e) throws RepositoryException, IOException {
    Node ntFile = e.node;
    Node content;
    String action = "A";
    if (ntFile == null) {
        e.node = ntFile = e.parentNode.addNode(e.jcrName, NodeType.NT_FILE);
        content = ntFile.addNode(Node.JCR_CONTENT, NodeType.NT_RESOURCE);
    } else {
        content = ntFile.getNode(Node.JCR_CONTENT);
        action = "U";
    }
    Calendar cal = Calendar.getInstance();
    if (preserveFileDate) {
        cal.setTimeInMillis(e.file.lastModified());
    }
    InputStream in = FileUtils.openInputStream(e.file);
    Binary bin = content.getSession().getValueFactory().createBinary(in);
    content.setProperty(Property.JCR_DATA, bin);
    content.setProperty(Property.JCR_LAST_MODIFIED, cal);
    content.setProperty(Property.JCR_MIMETYPE, MimeTypes.getMimeType(e.file.getName(), MimeTypes.APPLICATION_OCTET_STREAM));
    syncLog.log("%s jcr://%s", action, ntFile.getPath());
    res.addEntry(e.getJcrPath(), e.getFsPath(), SyncResult.Operation.UPDATE_JCR);
}
 
Example 5
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 6
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 7
Source File: TreeSync.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private Type getJcrType(Node node) throws RepositoryException {
    if (node == null) {
        return Type.MISSING;
    } else if (node.isNodeType(NodeType.NT_FILE)) {
        if (node.getMixinNodeTypes().length == 0) {
            // only ok, if pure nt:file
            Node content = node.getNode(Node.JCR_CONTENT);
            if (content.isNodeType(NodeType.NT_RESOURCE) && content.getMixinNodeTypes().length == 0) {
                return Type.FILE;
            }
        }
        return Type.UNSUPPORTED;
    }
    for (String nt: FULL_COVERAGE_NTS) {
        try {
            if (node.isNodeType(nt)) {
                return Type.FULL_COVERAGE;
            }
        } catch (RepositoryException e) {
            // ignore
        }
    }
    if (node.isNodeType(NodeType.NT_HIERARCHY_NODE)) {
        return Type.DIRECTORY;
    } else {
        return Type.UNSUPPORTED;
    }
}
 
Example 8
Source File: ThumbnailGenerator.java    From sling-samples with Apache License 2.0 5 votes vote down vote up
private Node getThumbnailFolder(Node addedNode) throws Exception {
	Node post = addedNode.getParent().getParent().getParent();
	if (post.hasNode("thumbnails")) {
		log.info("thumbnails node exists already at " + post.getPath());
		return post.getNode("thumbnails");
	} else {
		Node t = post.addNode("thumbnails", "nt:folder");
		session.save();
		return t;
	}
}
 
Example 9
Source File: RepositoryRefactor.java    From urule with Apache License 2.0 5 votes vote down vote up
public List<String> getFiles(Node rootNode,String path){
	String project=getProject(path);
	try{
		List<String> list=new ArrayList<String>();
		Node projectNode=rootNode.getNode(project);		
		buildPath(list, projectNode);
		return list;
	}catch(Exception ex){
		throw new RuleException(ex);
	}
}
 
Example 10
Source File: BaseRepositoryService.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public List<VersionFile> getVersionFiles(String path) throws Exception{
	path = processPath(path);
	Node rootNode=getRootNode();
	if (!rootNode.hasNode(path)) {
		throw new RuleException("File [" + path + "] not exist.");
	}
	List<VersionFile> files = new ArrayList<VersionFile>();
	Node fileNode = rootNode.getNode(path);
	VersionHistory versionHistory = versionManager.getVersionHistory(fileNode.getPath());
	VersionIterator iterator = versionHistory.getAllVersions();
	while (iterator.hasNext()) {
		Version version = iterator.nextVersion();
		String versionName = version.getName();
		if (versionName.startsWith("jcr:")) {
			continue; // skip root version
		}
		Node fnode = version.getFrozenNode();
		VersionFile file = new VersionFile();
		file.setName(version.getName());
		file.setPath(fileNode.getPath());
		Property prop = fnode.getProperty(CRATE_USER);
		file.setCreateUser(prop.getString());
		prop = fnode.getProperty(CRATE_DATE);
		file.setCreateDate(prop.getDate().getTime());
		if(fnode.hasProperty(VERSION_COMMENT)){
			prop=fnode.getProperty(VERSION_COMMENT);
			file.setComment(prop.getString());
		}
		files.add(file);
	}
	return files;
}
 
Example 11
Source File: StorageUpdate14.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void createIFrameSettings()  throws RepositoryException, IOException {
					
	LOG.info("Add IFrame Settings Node");		
       Node rootNode = getTemplate().getRootNode();
       Node settingsNode = rootNode.getNode(StorageConstants.NEXT_SERVER_FOLDER_NAME + StorageConstants.PATH_SEPARATOR + StorageConstants.SETTINGS_FOLDER_NAME);               
                  
       Node iframeNode = settingsNode.addNode(StorageConstants.IFRAME);
       iframeNode.addMixin("mix:referenceable");         
       iframeNode.setProperty("className", IFrameSettings.class.getName());         
       iframeNode.setProperty(StorageConstants.IFRAME_ENABLE,  true);
       iframeNode.setProperty(StorageConstants.IFRAME_AUTH,  false);
       iframeNode.setProperty(StorageConstants.IFRAME_ENC,  "next$");
       
       getTemplate().save();
}
 
Example 12
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 13
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public List<UserPermission> loadResourceSecurityConfigs(String companyId) throws Exception{
	List<UserPermission> configs=new ArrayList<UserPermission>();
	String filePath=RESOURCE_SECURITY_CONFIG_FILE+(companyId == null ? "" : companyId);
	Node rootNode=getRootNode();
	Node fileNode = rootNode.getNode(filePath);
	Property property = fileNode.getProperty(DATA);
	Binary fileBinary = property.getBinary();
	InputStream inputStream = fileBinary.getStream();
	String content = IOUtils.toString(inputStream, "utf-8");
	inputStream.close();
	Document document = DocumentHelper.parseText(content);
	Element rootElement = document.getRootElement();
	for (Object obj : rootElement.elements()) {
		if (!(obj instanceof Element)) {
			continue;
		}
		Element element = (Element) obj;
		if (!element.getName().equals("user-permission")) {
			continue;
		}
		UserPermission userResource=new UserPermission();
		userResource.setUsername(element.attributeValue("username"));
		userResource.setProjectConfigs(parseProjectConfigs(element));
		configs.add(userResource);
	}
	return configs;
}
 
Example 14
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 15
Source File: TestCugHandling.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * When cugHandling is set to IGNORE, rep:cugPolicy node should not be created.
 */
@Test
public void testCugIgnore() throws Exception {
   extractVaultPackage(CUG_PACKAGE_1, IGNORE);
   Node testRoot = adminSession.getNode(TEST_ROOT);
   assertNodeExists(testRoot, "node_with_cug");
   Node nodeWithCug = testRoot.getNode("node_with_cug");
   assertProperty(nodeWithCug, "jcr:mixinTypes", asSet("rep:CugMixin"));
   assertNodeMissing(nodeWithCug, "rep:cugPolicy");
}
 
Example 16
Source File: JcrPackageRegistry.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public PackageId resolve(Dependency dependency, boolean onlyInstalled) throws IOException {
    try {
        PackageId bestId = null;
        for (Node root: getPackageRoots()) {
            if (!root.hasNode(dependency.getGroup())) {
                continue;
            }
            Node groupNode = root.getNode(dependency.getGroup());
            NodeIterator iter = groupNode.getNodes();
            while (iter.hasNext()) {
                Node child = iter.nextNode();
                if (".snapshot".equals(child.getName())) {
                    continue;
                }
                try (JcrPackageImpl pack = new JcrPackageImpl(this, child)) {
                    if (pack.isValid()) {
                        if (onlyInstalled && !pack.isInstalled()) {
                            continue;
                        }
                        PackageId id = pack.getDefinition().getId();
                        if (dependency.matches(id)) {
                            if (bestId == null || id.getVersion().compareTo(bestId.getVersion()) > 0) {
                                bestId = id;
                            }
                        }
                    }
                }
            }
        } 
        if (bestId == null && baseRegistry != null) {
            bestId = baseRegistry.resolve(dependency, onlyInstalled);
        }
        return bestId;
    } catch (RepositoryException e) {
        throw new IOException(e);
    }
}
 
Example 17
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 18
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 19
Source File: JcrPackageManagerImpl.java    From jackrabbit-filevault with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void assemble(Node packNode, JcrPackageDefinition definition,
                     ProgressTrackerListener listener)
        throws PackageException, RepositoryException, IOException {
    Calendar now = Calendar.getInstance();
    JcrPackageDefinitionImpl def = (JcrPackageDefinitionImpl) definition;
    validateSubPackages(def);
    def.sealForAssembly(now);

    DefaultMetaInf inf = (DefaultMetaInf) def.getMetaInf();
    CompositeExportProcessor processor = new CompositeExportProcessor();

    // tweak filter for primary root, in case it contains sub-packages
    if (!registry.getPackRootPaths()[0].equals(DEFAULT_PACKAGE_ROOT_PATH)) {
        SubPackageExportProcessor sp = new SubPackageExportProcessor(this, packNode.getSession());
        WorkspaceFilter newFilter = sp.prepare(inf.getFilter());
        if (newFilter != null) {
            inf.setFilter(newFilter);
            processor.addProcessor(sp);
        }
    }

    ExportOptions opts = new ExportOptions();
    opts.setMetaInf(inf);
    opts.setListener(listener);
    processor.addProcessor(def.getInjectProcessor());
    opts.setPostProcessor(processor);

    VaultPackage pack = assemble(packNode.getSession(), opts, (File) null);
    PackageId id = pack.getId();

    // update this content
    Node contentNode = packNode.getNode(JcrConstants.JCR_CONTENT);
    
    try (InputStream in = FileUtils.openInputStream(pack.getFile())){
        // stay jcr 1.0 compatible
        //noinspection deprecation
        contentNode.setProperty(JcrConstants.JCR_DATA, in);
        contentNode.setProperty(JcrConstants.JCR_LASTMODIFIED, now);
        contentNode.setProperty(JcrConstants.JCR_MIMETYPE, JcrPackage.MIME_TYPE);
        packNode.getSession().save();
    } catch (IOException e) {
        throw new PackageException(e);
    }
    pack.close();
    dispatch(PackageEvent.Type.ASSEMBLE, id, null);
}
 
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);
}