How to get work item Id using link source Reference? - java

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.

Related

Is there a way to get latest object node by date from list of nodes provided by objectMapper?

I have a list of objects as List<KeyWithDocument> docs = getDocuments();. And the class which this individual KeyWithDocument is being mapped to is Detail. The list gives data where each value has a date. I am trying to get the doc only the latest date. I implemented the super simple logic that works.
I want to know if this can be done in a better way.
List<KeyWithDocument> docs = getDocuments();
Detail detail1 = null;
// So this below detail will be my final output after the for loop ends as this will contain the latest date object
Detail detailOutput = null;
Date previousMax = null;
for (KeyWithDocument kd : docs) {
detail1 = objectMapper.treeToValue(kd.getDocument().getContent(), Detail.class);
Date creationDate = detail1.getCreationDate();
if (creationDate == null) {
continue;
}
if (previousMax == null) {
previousMax = creationDate;
detailOutput = objectMapper.treeToValue(kd.getDocument().getContent(), Detail.class);
} else if (previousMax.before(creationDate)){
previousMax = creationDate;
detailOutput = objectMapper.treeToValue(kd.getDocument().getContent(), Detail.class);
}
}
I have modified the variable names from my actual names so pardon me for using bad naming convention here.
Looking for an optimized way of doing this.
Can anyone help me with this?

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

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();
}

Populating Thymeleaf rows, with one of column referenced to another table(Database).Need another column of referenced Table to display

I am beginner with springboot. I came across a situation.Ok, let me give table structure before I explain.
Expenses
expensesId, categories,
Categories
categoryId, categoryname
Expenses table is referring to category table with categoryId.
I am able to populate datatable with expensesList that was sent from a controller to view successfully. But my problem is I get columnid in populated but I wish to populate that column with categoryname instead. I thought for possible solutions for some time and I come up with stupid Idea using If the condition in thymeleaf of mapping categoryId with categoryName but I don't wish to go for that part as I can have more categories growing in future and code is difficult to maintain.
I could really use some help on this.
Link to git project
expensespage link
expenses controller link
Please do provide links if a solution is already available which I missed during my google search on this issue.
Apologies for bad english for Title part as I cannot squeeze question further.
I just added category object containing Id and name to every expenses object in
Expenses Object List and passed to controller. Now I can directly use CategoryName in View with Thymeleaf as follows
<td th:text="${expense.categories.categoryname}"></td>>
What I changed in controller.
Before
#RequestMapping(value = "/expenses")
public String toExpensesPage(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = monitorService.getUserByUserName(authentication.getName()).get(0);
List<Categories> categoriesList = monitorService.getAllCategories();
model.addAttribute("expenses",new Expenses());
if(categoriesList != null) {
model.addAttribute("categories",categoriesList);
}
List<Expenses> expensesList = monitorService.getAllExpensesActive(user.getUserid());
model.addAttribute("expensesList",expensesList);
return "common/expensespage";
}
To.
#RequestMapping(value = "/expenses")
public String toExpensesPage(Model model) {
Map<Integer,String> categoryMap = new HashMap<Integer, String>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = monitorService.getUserByUserName(authentication.getName()).get(0);
/* getting Category List This contains both categoryId and categoryname */
List<Categories> categoriesList = monitorService.getAllCategories();
/* Using hashmap to map id to name so we dont need to iterate categoryList or call to database with category Id..*/
for(int i = 0; i < categoriesList.size();i++){
categoryMap.put(categoriesList.get(i).getCategoryid(),
categoriesList.get(i).getCategoryname());
}
model.addAttribute("expenses",new Expenses());
if(categoriesList != null) {
model.addAttribute("categories",categoriesList);
}
List<Expenses> expensesList = monitorService.getAllExpensesActive(user.getUserid());
/*Assigning category object to expenses object*/
for(int i = 0; i < expensesList.size();i++){
Categories categories = new Categories();
categories.setCategoryid(expensesList.get(i).getCategories().getCategoryid());
categories.setCategoryname(categoryMap.get(expensesList.get(i).getCategories().getCategoryid()));
expensesList.get(i).setCategories(categories);
}
model.addAttribute("expensesList",expensesList);
return "common/expensespage";
}
Added Comment's inside code on how I did. Hope someone find it helpful.

Javax JCR Node getProperties and Titles

I am given a Node and I then request form it another Node.
Node nn = node.getNode("jcr:content");
From here I can do the following to get the value of
nn.getProperty("cq:lastModified")
What I am trying to do is get all the properties without asking for each one by name.
Node nn = node.getNode("jcr:content");
PropertyIterator pi = nn.getProperties();
Now I can iterate over the properties and print their values as so:
while(pi.hasNext())
{
Property p = pi.nextProperty();
String val = p.getString();
}
But how can I find the title of this Property?
I am not sure but you can try getName() method because Property interface is subinterface of Item interface. You can try like below :
while(pi.hasNext())
{
Property p = pi.nextProperty();
String name = p.getName();
String val = p.getString();
}

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