Java Code Examples for javax.jcr.NodeIterator#hasNext()

The following examples show how to use javax.jcr.NodeIterator#hasNext() . 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 6 votes vote down vote up
private void buildDirectories(Node node, List<RepositoryFile> fileList, String projectPath) throws Exception {
	NodeIterator nodeIterator = node.getNodes();
	while (nodeIterator.hasNext()) {
		Node dirNode = nodeIterator.nextNode();
		if (!dirNode.hasProperty(FILE)) {
			continue;
		}
		if (!dirNode.hasProperty(DIR_TAG)) {
			continue;
		}
		RepositoryFile file = new RepositoryFile();
		file.setName(dirNode.getPath().substring(projectPath.length()));
		file.setFullPath(dirNode.getPath());
		buildDirectories(dirNode, fileList, projectPath);
		fileList.add(file);
	}
}
 
Example 2
Source File: JcrStorageDao.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
public Entity[] getEntityChildren(String path) throws NotFoundException {
	checkPath(path);

	Node node = getNode(path);
	try {
		if (!node.hasNodes()) {
			return new Entity[0];
		}

		List<Entity> entities = new ArrayList<Entity>();
		NodeIterator nodes = node.getNodes();
		while (nodes.hasNext()) {
			Entity entity = getEntity(nodes.nextNode());
			if (entity != null) {
				entities.add(entity);
			}
		}

		return entities.toArray(new Entity[entities.size()]);
	} catch (RepositoryException e) {
		throw convertJcrAccessException(e);
	}
}
 
Example 3
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 6 votes vote down vote up
private void unlockAllChildNodes(Node node,User user,List<Node> nodeList,String rootPath) throws Exception{
	NodeIterator iter=node.getNodes();
	while(iter.hasNext()){
		Node nextNode=iter.nextNode();
		String absPath=nextNode.getPath();
		if(!lockManager.isLocked(absPath)){
			continue;
		}
		Lock lock=lockManager.getLock(absPath);
		String owner=lock.getLockOwner();
		if(!user.getUsername().equals(owner)){
			throw new NodeLockException("当前目录下有子目录被其它人锁定,您不能执行锁定"+rootPath+"目录");
		}
		nodeList.add(nextNode);
		unlockAllChildNodes(nextNode, user, nodeList, rootPath);
	}
}
 
Example 4
Source File: JcrStorageDao.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
public void clearUserWidgetData(String widgetId) {
	try {
		String className = "ro.nextreports.server.domain.UserWidgetParameters";
		String xpath = "/jcr:root" + ISO9075.encodePath(StorageConstants.USERS_DATA_ROOT) + "//*[@className='"
				+ className + "']";
		NodeIterator nodes = getTemplate().query(xpath).getNodes();
		while (nodes.hasNext()) {
			Node node = nodes.nextNode();
			if (node.getName().equals(widgetId)) {
				node.remove();
			}
		}
		getTemplate().save();
	} catch (RepositoryException e) {
		throw convertJcrAccessException(e);
	}
}
 
Example 5
Source File: StorageUpdate3.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private void renameChartWidgetClassName() throws RepositoryException {
	LOG.info("Rename chart widget class name");
	
	String path = StorageConstants.DASHBOARDS_ROOT;
	String className = "ro.nextreports.server.web.chart.ChartWidget";
	String newClassName = "ro.nextreports.server.web.dashboard.chart.ChartWidget";
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@widgetClassName='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	node.setProperty("widgetClassName", newClassName);
       }
       
       getTemplate().save();
}
 
Example 6
Source File: Purge.java    From APM with Apache License 2.0 6 votes vote down vote up
private void purge(final Context context, final ActionResult actionResult)
    throws RepositoryException, ActionExecutionException {
  NodeIterator iterator = getPermissions(context);
  String normalizedPath = normalizePath(path);
  while (iterator != null && iterator.hasNext()) {
    Node node = iterator.nextNode();
    if (node.hasProperty(PermissionConstants.REP_ACCESS_CONTROLLED_PATH)) {
      String parentPath = node.getProperty(PermissionConstants.REP_ACCESS_CONTROLLED_PATH)
          .getString();
      String normalizedParentPath = normalizePath(parentPath);
      boolean isUsersPermission = parentPath.startsWith(context.getCurrentAuthorizable().getPath());
      if (StringUtils.startsWith(normalizedParentPath, normalizedPath) && !isUsersPermission) {
        RemoveAll removeAll = new RemoveAll(parentPath);
        ActionResult removeAllResult = removeAll.execute(context);
        if (Status.ERROR.equals(removeAllResult.getStatus())) {
          copyErrorMessages(removeAllResult, actionResult);
        }
      }
    }
  }
}
 
Example 7
Source File: JcrStorageDao.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
private Entity[] getEntities(QueryResult queryResult) {
	try {
		NodeIterator nodes = queryResult.getNodes();
		List<Entity> entities = new ArrayList<Entity>();
		while (nodes.hasNext()) {
			Entity entity = getEntity(nodes.nextNode());
			if (entity != null) {
				entities.add(entity);
			}
		}

		return entities.toArray(new Entity[entities.size()]);
	} catch (RepositoryException e) {
		throw convertJcrAccessException(e);
	}
}
 
Example 8
Source File: IntegrationTestBase.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
public int countNodes(Node parent) throws RepositoryException {
    int total = 1;
    NodeIterator iter = parent.getNodes();
    while (iter.hasNext()) {
        total += countNodes(iter.nextNode());
    }
    return total;
}
 
Example 9
Source File: CatalogDataResourceProviderManagerImpl.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
/**
 * Find all existing virtual catalog data roots using all query defined in service configuration.
 *
 * @param resolver Resource resolver
 * @return all virtual catalog roots
 */
@SuppressWarnings("unchecked")
private List<Resource> findDataRoots(ResourceResolver resolver) {
    List<Resource> allResources = new ArrayList<>();
    for (String queryString : this.findAllQueries) {
        if (!StringUtils.contains(queryString, "|")) {
            throw new IllegalArgumentException("Query string does not contain query syntax seperated by '|': " + queryString);
        }
        String queryLanguage = StringUtils.substringBefore(queryString, "|");
        String query = StringUtils.substringAfter(queryString, "|");
        // data roots are JCR nodes, so we prefer JCR query because the resource resolver appears to be unreliable
        // when we are in the middle of registering/unregistering resource providers
        try {
            Session session = resolver.adaptTo(Session.class);
            Workspace workspace = session.getWorkspace();
            QueryManager qm = workspace.getQueryManager();
            Query jcrQuery = qm.createQuery(query, queryLanguage);
            QueryResult result = jcrQuery.execute();
            NodeIterator nodes = result.getNodes();
            while (nodes.hasNext()) {
                Node node = nodes.nextNode();
                Resource resource = resolver.getResource(node.getPath());
                if (resource != null) {
                    allResources.add(resource);
                }
            }
        } catch (RepositoryException x) {
            log.error("Error finding data roots", x);
        }
    }
    dataRoots = allResources;
    return allResources;
}
 
Example 10
Source File: StorageUpdater.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void resetFirstUsageDates() throws Exception {
  	LOG.info("Reset firstUsage.date for all users");
String statement = "/jcr:root"
		+ ISO9075.encodePath(StorageConstants.USERS_ROOT)
		+ "//*[@className='ro.nextreports.server.domain.UserPreferences']";
QueryResult queryResult = jcrTemplate.query(statement);

NodeIterator nodes = queryResult.getNodes();
LOG.info("Found " + nodes.getSize() + " user preferences nodes");		
while (nodes.hasNext()) {
	Node node = nodes.nextNode();
	
	Node pNode = node.getNode("preferences");
	try {
		Property property = pNode.getProperty("firstUsage.date");
		if (property.getValue() != null) {
			LOG.info("    removed firstUsage.date = " + property.getString() + "  for user " + node.getParent().getName());
			String s = null;
			pNode.setProperty("firstUsage.date", s);
		}
	} catch (PathNotFoundException ex) {
		// nothing to do
	}
}

jcrTemplate.save();
  }
 
Example 11
Source File: StorageUpdate7.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
private void addDestinations() throws RepositoryException {
	LOG.info("Add destinations to scheduler jobs");

	String path = StorageConstants.SCHEDULER_ROOT ;
	String className = "ro.nextreports.server.domain.SchedulerJob";
       String statement = "/jcr:root" + ISO9075.encodePath(path) + "//*[@className='" + className + "']";
       QueryResult queryResult = getTemplate().query(statement);

       NodeIterator nodes = queryResult.getNodes();
       LOG.info("Found " + nodes.getSize() + " scheduler job nodes");
       while (nodes.hasNext()) {
       	Node node = nodes.nextNode();
       	if (node.hasNode("mail")) {
       		LOG.info("Found 'mail' node for '" + node.getName() + "'");
       		Node mailNode = node.getNode("mail");
       		LOG.info("Create '" + StorageConstants.DESTINATIONS + "' node for '" + node.getName() + "'");
       		Node destinationsNode = node.addNode(StorageConstants.DESTINATIONS);
       		className = SmtpDestination.class.getName();
       		LOG.info("Change 'className' property for 'mail' node to '" + className + "'");
       		mailNode.setProperty("className", className);
       		LOG.info("Move '" + mailNode.getName() + "' to '" + destinationsNode.getName() + "/mail");
       		getTemplate().move(mailNode.getPath(), destinationsNode.getPath() + "/mail");
       	}
       }

       getTemplate().save();
}
 
Example 12
Source File: WebdavProviderTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/** Recursively outputs the contents of the given node. */
private static void dump(final Node node) throws RepositoryException {
    // First output the node path
    message(node.getPath());
    // Skip the virtual (and large!) jcr:system subtree
    if (node.getName().equals("jcr:system")) {
        return;
    }

    if (node.getName().equals("jcr:content")) {
        return;
    }

    // Then output the properties
    final PropertyIterator properties = node.getProperties();
    while (properties.hasNext()) {
        final Property property = properties.nextProperty();
        if (property.getDefinition().isMultiple()) {
            // A multi-valued property, print all values
            final Value[] values = property.getValues();
            for (final Value value : values) {
                message(property.getPath() + " = " + value.getString());
            }
        } else {
            // A single-valued property
            message(property.getPath() + " = " + property.getString());
        }
    }

    // Finally output all the child nodes recursively
    final NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        dump(nodes.nextNode());
    }
}
 
Example 13
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 14
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 15
Source File: TestPackageInstall.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * installs a package that contains a node with childnode ordering and full-coverage sub nodes.
 * see JCRVLT-44
 */
@Test
public void testChildNodeOrder2() throws IOException, RepositoryException, PackageException {
    JcrPackage pack = packMgr.upload(getStream("/test-packages/test_childnodeorder2.zip"), false);
    assertNotNull(pack);
    pack.install(getDefaultOptions());

    assertNodeExists("/tmp/test/en");
    NodeIterator iter = admin.getNode("/tmp/test/en").getNodes();
    StringBuilder names = new StringBuilder();
    while (iter.hasNext()) {
        names.append(iter.nextNode().getName()).append(",");
    }
    assertEquals("child order", "jcr:content,toolbar,products,services,company,events,support,community,blog,", names.toString());
}
 
Example 16
Source File: Webdav4ProviderTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/** Recursively outputs the contents of the given node. */
private static void dump(final Node node) throws RepositoryException {
    // First output the node path
    message(node.getPath());
    // Skip the virtual (and large!) jcr:system subtree
    if (node.getName().equals("jcr:system")) {
        return;
    }

    if (node.getName().equals("jcr:content")) {
        return;
    }

    // Then output the properties
    final PropertyIterator properties = node.getProperties();
    while (properties.hasNext()) {
        final Property property = properties.nextProperty();
        if (property.getDefinition().isMultiple()) {
            // A multi-valued property, print all values
            final Value[] values = property.getValues();
            for (final Value value : values) {
                message(property.getPath() + " = " + value.getString());
            }
        } else {
            // A single-valued property
            message(property.getPath() + " = " + property.getString());
        }
    }

    // Finally output all the child nodes recursively
    final NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
        dump(nodes.nextNode());
    }
}
 
Example 17
Source File: RepositoryServiceImpl.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public List<RepositoryFile> getDirectories(String project) throws Exception {
	Node rootNode=getRootNode();
	NodeIterator nodeIterator = rootNode.getNodes();
	Node targetProjectNode = null;
	while (nodeIterator.hasNext()) {
		Node projectNode = nodeIterator.nextNode();
		if (!projectNode.hasProperty(FILE)) {
			continue;
		}
		String projectName = projectNode.getName();
		if (project != null && !project.equals(projectName)) {
			continue;
		}
		targetProjectNode = projectNode;
		break;
	}
	if (targetProjectNode == null) {
		throw new RuleException("Project [" + project + "] not exist.");
	}
	List<RepositoryFile> fileList = new ArrayList<RepositoryFile>();
	RepositoryFile root = new RepositoryFile();
	root.setName("根目录");
	String projectPath = targetProjectNode.getPath();
	root.setFullPath(projectPath);
	fileList.add(root);
	NodeIterator projectNodeIterator = targetProjectNode.getNodes();
	while (projectNodeIterator.hasNext()) {
		Node dirNode = projectNodeIterator.nextNode();
		if (!dirNode.hasProperty(DIR_TAG)) {
			continue;
		}
		RepositoryFile file = new RepositoryFile();
		file.setName(dirNode.getPath().substring(projectPath.length()));
		file.setFullPath(dirNode.getPath());
		fileList.add(file);
		buildDirectories(dirNode, fileList, projectPath);
	}
	return fileList;
}
 
Example 18
Source File: BaseRepositoryService.java    From urule with Apache License 2.0 5 votes vote down vote up
@Override
public List<RepositoryFile> loadProjects(String companyId) throws Exception{
	List<RepositoryFile> projects=new ArrayList<RepositoryFile>();
	Node rootNode=getRootNode();
	NodeIterator nodeIterator = rootNode.getNodes();
	while (nodeIterator.hasNext()) {
		Node projectNode = nodeIterator.nextNode();
		if (!projectNode.hasProperty(FILE)) {
			continue;
		}
		if(StringUtils.isNotEmpty(companyId)){
			if(projectNode.hasProperty(COMPANY_ID)){
				String id=projectNode.getProperty(COMPANY_ID).getString();
				if(!companyId.equals(id)){
					continue;
				}
			}
		}
		if(projectNode.getName().indexOf(RESOURCE_SECURITY_CONFIG_FILE)>-1){
			continue;
		}
		RepositoryFile projectFile = new RepositoryFile();
		projectFile.setType(Type.project);
		projectFile.setName(projectNode.getName());
		projectFile.setFullPath("/" + projectNode.getName());
		projects.add(projectFile);
	}
	return projects;
}
 
Example 19
Source File: JcrMetadataRepository.java    From archiva with Apache License 2.0 4 votes vote down vote up
private ArtifactMetadata getArtifactFromNode(String repositoryId, Node artifactNode)
        throws RepositoryException {
    String id = artifactNode.getName();

    ArtifactMetadata artifact = new ArtifactMetadata();
    artifact.setId(id);
    artifact.setRepositoryId(repositoryId == null ? artifactNode.getAncestor(2).getName() : repositoryId);

    Node projectVersionNode = artifactNode.getParent();
    Node projectNode = projectVersionNode.getParent();
    Node namespaceNode = projectNode.getParent();

    artifact.setNamespace(namespaceNode.getProperty("namespace").getString());
    artifact.setProject(projectNode.getName());
    artifact.setProjectVersion(projectVersionNode.getName());
    artifact.setVersion(artifactNode.hasProperty("version")
            ? artifactNode.getProperty("version").getString()
            : projectVersionNode.getName());

    if (artifactNode.hasProperty(JCR_LAST_MODIFIED)) {
        artifact.setFileLastModified(artifactNode.getProperty(JCR_LAST_MODIFIED).getDate().getTimeInMillis());
    }

    if (artifactNode.hasProperty("whenGathered")) {
        Calendar cal = artifactNode.getProperty("whenGathered").getDate();
        artifact.setWhenGathered(ZonedDateTime.ofInstant(cal.toInstant(), cal.getTimeZone().toZoneId()));
    }

    if (artifactNode.hasProperty("size")) {
        artifact.setSize(artifactNode.getProperty("size").getLong());
    }

    Node cslistNode = getOrAddNodeByPath(artifactNode, "checksums");
    NodeIterator csNodeIt = cslistNode.getNodes("*");
    while (csNodeIt.hasNext()) {
        Node csNode = csNodeIt.nextNode();
        if (csNode.isNodeType(CHECKSUM_NODE_TYPE)) {
            addChecksum(artifact, csNode);
        }
    }

    retrieveFacetProperties(artifact, artifactNode);
    return artifact;
}
 
Example 20
Source File: StorageUpdate13.java    From nextreports-server with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
	private void createNodeTemplates() throws RepositoryException {
		Session session = SessionFactoryUtils.getSession(getTemplate().getSessionFactory(), false);
    	Workspace workspace = session.getWorkspace();
    	    	
    	NodeTypeManagerImpl nodeTypeManager = (NodeTypeManagerImpl) workspace.getNodeTypeManager();
//    	nodeTypeManager.unregisterNodeType(StorageConstants.NEXT_REPORT_MIXIN);
    	    	
    	NodeTypeTemplate nodeTypeTemplate = nodeTypeManager.createNodeTypeTemplate();
    	nodeTypeTemplate.setName(StorageConstants.NEXT_REPORT_MIXIN);
    	nodeTypeTemplate.setMixin(true);
    	nodeTypeTemplate.setOrderableChildNodes(false);
    	nodeTypeTemplate.setPrimaryItemName("nt:unstructured");
    	nodeTypeTemplate.setDeclaredSuperTypeNames(new String[] { "mix:referenceable", "mix:versionable" });   
    	
    	NodeDefinitionTemplate nodeDefinitionTemplate = nodeTypeManager.createNodeDefinitionTemplate();
    	nodeDefinitionTemplate.setName("runHistory");
    	nodeDefinitionTemplate.setDefaultPrimaryTypeName("nt:unstructured");
    	nodeDefinitionTemplate.setRequiredPrimaryTypeNames(new String[] { "nt:unstructured" });
    	nodeDefinitionTemplate.setAutoCreated(true);
    	nodeDefinitionTemplate.setMandatory(false);
    	nodeDefinitionTemplate.setOnParentVersion(OnParentVersionAction.IGNORE);
    	nodeDefinitionTemplate.setProtected(false);
    	nodeDefinitionTemplate.setSameNameSiblings(false);

    	nodeTypeTemplate.getNodeDefinitionTemplates().add(nodeDefinitionTemplate);
    	    	
    	NodeDefinitionTemplate nodeDefinitionTemplate2 = nodeTypeManager.createNodeDefinitionTemplate();
    	nodeDefinitionTemplate2.setName("templates");
    	nodeDefinitionTemplate2.setDefaultPrimaryTypeName("nt:unstructured");
    	nodeDefinitionTemplate2.setRequiredPrimaryTypeNames(new String[] { "nt:unstructured" });
    	nodeDefinitionTemplate2.setAutoCreated(true);
    	nodeDefinitionTemplate2.setMandatory(false);
    	nodeDefinitionTemplate2.setOnParentVersion(OnParentVersionAction.IGNORE);
    	nodeDefinitionTemplate2.setProtected(false);
    	nodeDefinitionTemplate2.setSameNameSiblings(false);
    	
    	nodeTypeTemplate.getNodeDefinitionTemplates().add(nodeDefinitionTemplate2);

    	LOG.info("Registering node type mixin '" + StorageConstants.NEXT_REPORT_MIXIN + "'");
    	nodeTypeManager.registerNodeType(nodeTypeTemplate, true);
    	
    	// add templates node to all existing reports
    	String statement = 
				"/jcr:root" + ISO9075.encodePath(StorageConstants.REPORTS_ROOT) + 
				"//*[@className='ro.nextreports.server.domain.Report']";
		  
		QueryResult queryResult = getTemplate().query(statement);
		NodeIterator nodes = queryResult.getNodes();
		
		LOG.info("Create templates nodes : Found " + nodes.getSize() + " report nodes");
		while (nodes.hasNext()) {			
			Node node = nodes.nextNode();
			node.addNode("templates");
		}					

    	getTemplate().save();
	}