AEM 6.1: Get all 'parsys' and 'iparsys' components of the page - java

I have a path to the page (/content/my-site/en/cars, for example) and I need a list of all 'parsys' and 'iparsys' components presented on this page in java code. Are there any ways to do it? Thanks for any help.

I assume you are trying a Sling model or WCMUsePOJO to read inner nodes of a page. Here the techniques:
If you dont know how many parsys nodes are present: This is not an ideal case since page rendering script dictates all included parsys and iparsys. But just incase, you ll run a query for sling:resourceType like this:
Iterator<Resource> parsysResources = resourceResolver.findResources("/jcr:root/content/my-site/en/cars//*[sling:resourceType='foundation/components/parsys']", Query.XPATH);
Iterator<Resource> iparsysResources = resourceResolver.findResources("/jcr:root/content/my-site/en/cars//*[sling:resourceType='foundation/components/iparsys']", Query.XPATH);
Similar query but with Query Builder (Recommended): It is recommended to use query builder API for readability and extensible in future.
List<Resource> parsysIpaysysResources = new ArrayList<>();
Map<String, String> predicateMap = new HashMap<>();
predicateMap.put("path", "/content/my-site/en/cars");
predicateMap.put("1_property", "sling:resourceType");
predicateMap.put("1_property.value", "foundation/components/parsys");
predicateMap.put("2_property", "sling:resourceType");
predicateMap.put("2_property.value", "foundation/components/iparsys");
predicateMap.put("p.limit", "-1");
QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
Session session = resourceResolver.adaptTo(Session.class);
com.day.cq.search.Query query = queryBuilder.createQuery(PredicateGroup.create(predicateMap), session);
SearchResult result = query.getResult();
Iterator<Resource> resources = result.getResources();
while (resources.hasNext()) {
parsysIpaysysResources.add(resources.next());
}
If the parsys nodes are known to be immediate children of page content, listChildren will be cheaper compared to query.
Page pageContent = pageManager.getContainingPage("/content/my-site/en/cars");
Iterator<Resource> children = pageContent.getContentResource().listChildren();
while(children != null && children.hasNext()) {
Resource child = children.next();
if(child.isResourceType("foundation/components/parsys") || child.isResourceType("foundation/components/iparsys")) {
// do something
}
}
If the node name of inner parsys is known, JCR API can be leveraged
Page pageContent = pageManager.getContainingPage("/content/my-site/en/cars");
Node pageContentNode = pageContent.adaptTo(Node.class);
try {
NodeIterator nodeIter = pageContentNode.getNodes("parsys*");
// iterate nodes
} catch (RepositoryException e) {
e.printStackTrace();
}

Related

How to get work item Id using link source Reference?

I am using the below code to fetch parent and children of the work item and I got link reference, Now I want to fetch the work item Id from object. Please help
IReference reference = linkManager.referenceFactory().createReferenceToItem(workItem
.getItemHandle());
ILinkQueryPage page;
ILinkQueryPage page1;
page = linkManager.findLinksByTarget("com.ibm.team.workitem.linktype.parentworkitem", reference, monitor);
ILinkCollection linkCollection = page.getLinks();
Collection childWI = linkCollection.getLinksById("com.ibm.team.workitem.linktype.parentworkitem");
System.out.println(childWI);
ILinkCollection linkCollection = page.getLinks();
Collection childWI = linkCollection.getLinksById(...)
That means you have a collection of ILink(s).
As seen here, it is easy to resolve a link to a WorkItem:
for (ILink l : links) {
IItemHandle linkHandle = (IItemHandle) l.getTargetRef().resolve();
if (linkHandle instanceof IWorkItemHandle) {
IWorkItem aWorkItem = (IWorkItem) teamRepository.itemManager().fetchCompleteItem(linkHandle, IItemManager.DEFAULT, monitor);
}
}
Each WorkItem has a getId() method to access its ID.

Java NamingEnumeration - Getting a single element out of a NamingEnumeration

I am trying to fetch some users from Active Directory group and update them in another one of our site.
The task is almost done except for the part where I need to fetch the user ID from NamingEnumeration and pass it onto another method which will update it through a REST API call. Below is a part of the code where I am fetching users from AD group:
DirContext myContext = new InitialDirContext(envVars);
SearchControls searchCtrls = new SearchControls();
searchCtrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attributes = { "cn", "member"};
searchCtrls.setReturningAttributes(attributes);
String filter = "(&(objectClass=group)(cn=GROUP_NAME))";
NamingEnumeration values = myContext.search("DC=XXXX,DC=XXXX",filter,searchCtrls);
while (values.hasMoreElements())
{
SearchResult result = (SearchResult) values.next();
Attributes attribs = result.getAttributes();
if (null != attribs)
{
for (NamingEnumeration ae = attribs.getAll(); ae.hasMoreElements();)
{
Attribute atr = (Attribute) ae.next();
String attributeID = atr.getID();
for (
Enumeration vals = atr.getAll();
vals.hasMoreElements();
System.out.println(attributeID+": "+vals.nextElement())
);
}
}
}
When I run this, the output is something like below:
member: CN=USERNAME,OU=XXX,OU=XXX,OU=XXX,DC=XXX,DC=XXX,DC=XXX
member: CN=USERNAME,OU=XXX,OU=XXX,OU=XXX,DC=XXX,DC=XXX,DC=XXX
Basically, I need to fetch this CN i.e. USERNAME alone, which I will pass onto another method.
I did try to get them in a String array and process them, to no avail and I am running short of time.
Any ideas would be greatly appreciated. Thanks.
Well, I did get around this problem.
Below approach worked for me.
if (null != attribs)
{
for (NamingEnumeration ae = attribs.getAll(); ae.hasMoreElements();)
{
Attribute atr = (Attribute) ae.next();
for (
Enumeration vals = atr.getAll();
vals.hasMoreElements();
) {
list.add(vals.nextElement().toString());
}
}
}
I let the output inside a list and clipped the unwanted parts to obtain the CN alone.
Would be glad if this helps someone in the future.

How to find nodes with subset of Labels in Neo4j Embeded

I'm using the Java API and I'm looking to find nodes with a subset of Labels. In cypher, I use this query:
Match(n) Where n:label1 OR n:label2 return n
So, Is there any method in api for that?
Thank you
You can actually run a Cypher-query embedded, so why dance ?
try (
Transaction vTx = graphdb.beginTx();
Result vResult = graphdb.execute("your cypher query here");
) {
while (vResult.hasNext()) {
Map<String, Object> vRecord = vResult.next();
// process vRecord here
}
vResult.close();
vTx.success();
}
Hope this helps.
Regards,
Tom
I think it is efficient if you do this in two steps. Like this:
ResourceIterator<Node> thingAs = graphDB.findNodes( Labels.label1 );
ResourceIterator<Node> thingBs = graphDB.findNodes( Labels.label2 );
Otherwise the identical solution should be like this:
ResourceIterable<Node> nodes = graphDB.getAllNodes();
while( nodes.hasNext() )
{
Node node = nodes.next();
if(node.hasLabel(Labels.label1 ) || node.hasLabel(Labels.label2 ))
return true;
}

how to disable page query in Spring-data-elasticsearch

I use spring-data-elasticsearch framework to get query result from elasticsearch server, the java code like this:
public void testQuery() {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withFields("createDate","updateDate").withQuery(matchAllQuery()).withPageable(new PageRequest(0,Integer.MAX_VALUE)).build();
List<Entity> list = template.queryForList(searchQuery, Entity.class);
for (Entity e : list) {
System.out.println(e.getCreateDate());
System.out.println(e.getUpdateDate());
}
}
I get the raw query log in server, like this:
{"from":0,"size":10,"query":{"match_all":{}},"fields":["createDate","updateDate"]}
As per the query log, spring-data-elasticsearch will add size limit to the query. "from":0, "size":10, How can I avoid it to add the size limit?
You don't want to do this, you could use the findAll functionality on a repository that returns an Iterable. I think the best way to obtain all items is to use the scan/scroll functionality. Maybe the following code block can put you in the right direction:
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchAllQuery())
.withIndices("customer")
.withTypes("customermodel")
.withSearchType(SearchType.SCAN)
.withPageable(new PageRequest(0, NUM_ITEMS_PER_SCROLL))
.build();
String scrollId = elasticsearchTemplate.scan(searchQuery, SCROLL_TIME_IN_MILLIS, false);
boolean hasRecords = true;
while (hasRecords) {
Page<CustomerModel> page = elasticsearchTemplate.scroll(scrollId, SCROLL_TIME_IN_MILLIS, CustomerModel.class);
if (page != null) {
// DO something with the records
hasRecords = (page.getContent().size() == NUM_ITEMS_PER_SCROLL);
} else {
hasRecords = false;
}
}

How do you get the name of a git tag with the JGit API

I am familiar with using a tag reference to get a Ref and then start doing something:
Ref ref = repository.getRef("refs/tags/jena-2.11.2");
But if a ref is passed to me and I want to get the "refs/tags/jena-2.11.2" string back, how do I do it with the JGit API?
RevWalk walk = new RevWalk(repository);
RevObject object;
try {
object = walk.parseAny(ref.getObjectId());
} catch (MissingObjectException e) {
.....
} catch (IOException e) {
.....
}
if (object instanceof RevTag) {
// String tagName = object.what?????????
} else if (object instanceof RevCommit) {
...
} else {
...
}
A commit does not known about the labels that may point to it. Therefore there is no object.getRefs() or similar.
If you know that there should be a tag pointing to a given commit, you can use the ListTagCommand to obtain a list of all tags and then iterate over this list until you found the tag that points to this commit.
The NameRevCommand follows a more general approach. Like git name-rev, it finds symbolic names for a given commit.
Following your example, this snippet would print the tag name of the commit:
Map<ObjectId,String> names = git.nameRev().add( object ).addPrefix( "refs/tags/" ).call();
System.out( names.get( object ) );
The addPrefix ensures that tags take precedence over other refs in case that more than one ref points to object.

Categories

Resources