Check if linklist is not empty before getNode method - java

I have a sort of convoluted question. I'll try my best to explain. I am working on a Adobe CQ codebase that is JCR and Java-based.
I have a Java ArrayList declaration like this:
ArrayList<Map<String,Property>> list6 = new ArrayList<Map<String,Property>>();
Furthermore I have a linked list defined by CQ/Java code elsewhere in the code. That linked list is called linkSet6. Each 'node' in the list goes by the name links
I am trying to get the content from linkSet6 to ArrayList list6.
The problem I am facing is linkSet6 always exists but it may or may not have links in it. I am doing this and it works fine whenever there are "links"
if(currentNode != null && currentNode.hasNode("linkSet6")) {
baseNode = currentNode.getNode("linkSet6").getNode("links");
list6 = Utilities.parseStructuredMultifield(baseNode);
}
But when linkSet6 is emptyI get this error:
org.apache.sling.api.scripting.ScriptEvaluationException: An exception occurred processing JSP page /apps/citrixosd-responsive/components/content/footerNavigation/footerNavigation.jsp at line 41
Line 41 is this:
baseNode = currentNode.getNode("linkSet6").getNode("links");
I've tried size(),length() etc to check but to no avail. Any tip on how to check if links exist before doing getNode("links").

You can validate if the node exists by using Session.nodeExists(String) method.
if (session.nodeExists(currentNode.getPath + "/linkSet6")) {
...
}
The session object is usually acquired via the ResourceResolver object: resolver.adaptTo(Session.class)
Anyway - I recommend jumping into the Sling abstraction layer. Working with Resource and ResourceResolver is bit more convenient in such case (e.g. getResource will return you a null when a resource does not exist).

hasNode("links") will return true if the node links exists

Related

How to copy a generic list with Eclipse EMF?

how can i split an Elist to two Elists without getting the NullPointerException. I already tried EcoreUtil.copy() / Collections.copy. The Problem seems that when declaring the copy target List it needs to be initialized with = null; I also tried using an Iterator to copy Elements and tried adding them with .set() .add() all exit with the Exception above. The declaration of the target List seems to be working only with an allocation. While debugging i clearly see that the copied object in the List is not null.
EList<RtTask> tasks = rtModule.getTasks();
EList<RtModuleInvocation> invoc0 = null; //target List
for (RtTask rtTask : tasks) {
EList<RtModuleInvocation> invocations = rtTask.getModuleInvocations(); //src List
Thanks.
Thanks to https://www.programcreek.com/java-api-examples/emf i found out the correct way to initialize my Elist with a constructor that Creates an empty instance with no initial capacity.The data storage will be null. and HOP it works.
EList<RtModuleInvocation> invoc0 = new BasicEList<>();
If you want a copy of a list, you can also use the ECollections utility:
ECollections.newBasicEList(Iterable)
Creates a mutable BasicEList containing the given elements.
So to copy the RtModuleInvocation list you can use:
ECollections.newBasicEList(rtTask.getModuleInvocations())

TableViewer.getElementAt() returning a filtered element

I'm trying to automatically select the first item in a filtered table.
I'm essentially doing the following:
table = new TableViewer(...);
table.addFilter(filter);
table.setContentProvider(contentProvider);
table.setInput(input);
first = table.getElementAt(0);
table.setSelection(new StructuredSelection(first));
The surprising thing is that (depending on the filter) I can get an element that is filtered out from getElementAt(0). The result is that ultimately, no item will be selected.
I have tried calling table.refresh() before getting the element with the same results.
If I call getElementAt(0) at a later point, I do indeed get the correct first element (that is not filtered out).
How can I make getElementAt respect the filtering immediately?
In my experience, the most reliable way to select the first (visible) element is - for once only - to bypass JFace, rely on its internal data model, and use SWT API to select the first TableItem like this:
static Object selectFirstElement(TableViewer tableViewer) {
Object firstElement = null;
Table table = tableViewer.getTable();
if (table.getItemCount() > 0) {
firstElement = table.getItem(0).getData();
tableViewer.setSelection(new StructuredSelection(firstElement), true); // true == reveal
}
return firstElement;
}
I've been using this code successfully for several years with sorted, filtered, and virtual tables.
Well, I found what was wrong and it was my own fault. The filter I set is mutable so it can filter more or less strictly. The problem was that I activated the more strict filtering after I set the selection.
Thanks everyone for the help anyways.

Programmatically arranging contents in aem 6.4

everyone. I'm new in working with aem. I'm using aem 6.4. My task is to programmatically sort the order of the contents of a cq:project in aem depending on the content of a JSON file.
The content of the JSON file should be set as the initial child instead of the children sorted by their creation date.
This is the current structure of my cq:page. If the child2 is the one indicated in the JSON file, it should be the first one to be displayed. The content of the JSON file is just the name of one child so even though there are 10 children, the content of the JSON file should always be the first one in the list.
I've spent hours researching on how I can implement this although I still can't find any solution. Any insights on how should I create this? Thanks!
As I understand it, you want a way to order a named child of a cq:Page to be first in the list.
This is possible because cq:Page is an orderable node. This would not be possible otherwise. you chan check any nodetype in CRX Explorer.
I think adding the bit about JSON complicates the question. You just need a simple method such as the following:
private void orderAsFirstChild(String childName, Node parentNode) throws RepositoryException {
if (parentNode.hasNode(childName)) {
// find current first child name
String firstChildName = Optional.ofNullable(parentNode.getNodes())
.map(NodeIterator::nextNode)
.map(node -> {
try {
node.getName();
} catch (RepositoryException e) {
e.printStackTrace();
}
return (String) null;
}) //
.orElse(null);
parentNode.orderBefore(childName, firstChildName);
}
}
You should probably clean this up a little, but this is the general idea using Node#orderBefore
This may helps -
Get the children from the parent node.(you will get 'iterator' convert it to list here-Convert Iterator to ArrayList)
Delete all child nodes now. And keep the back up of above list.
iterate through the list , identify the node which you want place first(by title or some other property) add that to a separate set(LinkedHashSet- to maintain order).
Now add the remaining items/nodes in the same order after your specific node in the above set.(you may need to iterate through again)
Now this Set has nodes/Resources in the order which you want, iterate , create nodes and save your changes.

How to get all existing groups in jcr?

I want to fetch a list of all existing groups in CQ5 JCR. I am able to fetch a list of all existing users in the JCR using following code,
UserManager userManager = jkrSession.getUserManager();
final List<String> users = new ArrayList<String>();
Iterator<Authorizable> iter = userManager.findAuthorizables(
"jcr:primaryType", "rep:User");
while (iter.hasNext()) {
Authorizable auth = iter.next();
if (!auth.isGroup()) {
users.add(auth.getID());
}
}
I haven't found any way to get a list of all existing users. Although, I can see the parent nodes /home/users and /home/groups and I can iterate over the child nodes to fetch users and groups.
I am looking for an easier way out.
The title of your question doesn't sync with your question's content.
First, the following code is really unnecessary, as you are searching for rep:User, and hence only users would be available in the iterator, thereby making your if check fail every time.
Authorizable auth = iter.next();
if (!auth.isGroup()) {
users.add(auth.getID());
}
Hence the while loop could be rewritten as
users.add(iter.next().getID());
Second, if it is the list of all existing groups that you want to fetch, then you can use
Iterator<Authorizable> iter = userManager.findAuthorizables(
"jcr:primaryType", "rep:Group");
This would return only the groups that are present in your instance.
But, if it is both, users and groups that you want to fetch, may be you can try this.
Iterator<Authorizable> iter = userManager.findAuthorizables(
"profile/jcr:primaryType", "nt:unstructured", UserManager.SEARCH_TYPE_AUTHORIZABLE);
This would return all the authorizables that are present in the instance. It is not mandatory that you have to specify only profile/jcr:primaryType and nt:unstructured as the property and value. You can use the relative path to any property which would be present in all the authorizables, containing the same value if you want to list all the authorizables(in my case profile/jcr:primaryType caught my eye first), else the results would be filtered to those authorizables for whom the property value matches.
For further reference you can check the docs.

Getting Lotus Notes data from Document

I am using a local database in my version of Lotus notes(8.5.2), and I am trying to get the data for two things:
The highlighted document/item in a NotesUIView
The document selected in a NotesUIDocument
However, all I get are the Notes URLs and I don't know what I should do with those. Can anyone help me out/throw me a breadcrumb?
P.S. Yes I am using the Java API for Eclipse.
Here is a code sample of what I do:
NotesUIWorkspace workSpace = new NotesUIWorkspace();
NotesUIElement currentElement = workSpace.getCurrentElement();
if (currentElement instanceof NotesUIView) {
NotesUIView currentView = (NotesUIView) currentElement;
NotesUIViewEntryCollection collection = currentView
.getActionableEntries();
Iterator docIterator = collection.documentIterator();
while (docIterator.hasNext()) {
NotesUIDocumentEntry entry = (NotesUIDocumentEntry) docIterator.next();
//I can't seem to get to the NoesUIDocument case like I can below... I want fields!
}
}
if(currentElement instanceof NotesUIDocument){
NotesUIDocument document = (NotesUIDocument) currentElement;
//Seem to be able to get the correct data fields only in this case!
document.getFields();
}
Fetching the "current" document is usually done via the NotesAgentContext.UnprocessedDocuments. In a view, that might return a collection of documents if the user as ticked several.
If you already have an NotesUIView, NotesUIView.getActionableEntries will give you the selected document(s).
When you have a NotesDocumentData instance, NotesUIWorkspace.openDocument can be used to open it up in edit mode. Then NotesUIWorkspace.getCurrentDocument can be used to get hold of the UI Document.
Notice that if you only want to read values from the document, it is more convenient to use the back-end classes like Document.
Have you got a URL as an example? If it includes the UUID of the document in question then you should be able to reference it directly with a getDocument(). Otherwise, the URL should include a view reference and a lookup key for that view in question.

Categories

Resources