Java Code Examples for org.openide.nodes.Node#addNodeListener()

The following examples show how to use org.openide.nodes.Node#addNodeListener() . 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: FormEditorSupport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void registerNodeListener() {
    if (formDataObject.isValid()) {
        Node node = formDataObject.getNodeDelegate();
        multiviewTC.setIcon(node.getIcon(BeanInfo.ICON_COLOR_16x16));
        if (nodeListener == null) {
            NodeListener listener = new NodeAdapter() {
                @Override
                public void propertyChange(final PropertyChangeEvent ev) {
                    Mutex.EVENT.writeAccess(new Runnable() {
                        @Override
                        public void run() {
                            if (Node.PROP_ICON.equals(ev.getPropertyName())) {
                                if (formDataObject.isValid() && (multiviewTC != null)) {
                                    multiviewTC.setIcon(formDataObject.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16));
                                }
                            }
                        }
                    });
                }
            };
            node.addNodeListener(org.openide.nodes.NodeOp.weakNodeListener(listener, node));
            nodeListener = listener;
        }
    }
}
 
Example 2
Source File: MatchingObjectNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private MatchingObjectNode(Node original,
        org.openide.nodes.Children children,
        final MatchingObject matchingObject,
        ReplaceCheckableNode checkableNode) {
    super(children, createLookup(matchingObject, checkableNode));
    replacing = checkableNode.isCheckable();
    Parameters.notNull("original", original);                       //NOI18N
    this.matchingObject = matchingObject;
    if (matchingObject.isObjectValid()) {
        this.original = original;
        setValidOriginal();
        origNodeListener = new OrigNodeListener();
        original.addNodeListener(origNodeListener);
    } else {
        setInvalidOriginal();
    }
    validityListener = new ValidityListener(matchingObject);
    matchingObject.addPropertyChangeListener(
            MatchingObject.PROP_INVALIDITY_STATUS,
            validityListener);
    selectionListener = new SelectionListener();
    matchingObject.addPropertyChangeListener(selectionListener);
}
 
Example 3
Source File: PropertiesRowModel.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Object getValueFor(Object node, int column) {
    Node n = Visualizer.findNode(node);
    if (n == null) {
        throw new IllegalStateException("TreeNode must be VisualizerNode but was: " + node + " of class " + node.getClass().getName());
    }
    PropertyChangeListener cacheEntry = nodesListenersCache.get (n);
    if (cacheEntry == null) {
        PropertyChangeListener p = WeakListeners.propertyChange(pcl, n);
        nodesListenersCache.put(n, p);
        n.addPropertyChangeListener(p);
        NodeListener l = WeakListeners.create(NodeListener.class, nl, n);
        n.addNodeListener(l);
    }
    Node.Property theRealProperty = getPropertyFor(n, prop[column]);
    return theRealProperty;
}
 
Example 4
Source File: PropertySheet.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Attach to a node, detaching from the last one if non-null.  */
public void attach(Node n) {
    if (currNode != n) {
        if (currNode != null) {
            detach();
        }

        if (n != null) {
            n.addPropertyChangeListener(inner);
            n.addNodeListener(this);

            if (PropUtils.isLoggable(PropertySheet.class)) {
                PropUtils.log(PropertySheet.class, "Now listening for changes on " + n);
            }
        }

        currNode = n;
    }
}
 
Example 5
Source File: HelpCtxProcessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Create a new presenter.
 * @param obj XML file describing it
 */
public ShortcutAction(DataObject obj, String helpID, boolean showmaster) {
    this.obj = obj;
    this.helpID = helpID;
    this.showmaster = showmaster;
    putValue("noIconInMenu", true); // NOI18N
    Installer.log.log(Level.FINE, "new ShortcutAction: {0} {1} showmaster={2}", new Object[] {obj, helpID, showmaster});
    updateText();
    updateIcon();
    updateEnabled();
    if (obj.isValid()) {
        Node n = obj.getNodeDelegate();
        n.addNodeListener(org.openide.nodes.NodeOp.weakNodeListener (this, n));
    }
    Help h = findHelp();
    if (h != null) {
        h.addChangeListener(WeakListeners.change(this, h));
    }
}
 
Example 6
Source File: SuiteLogicalViewTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testNameAndDisplayName() throws Exception {
    SuiteProject p = generateSuite("Sweet Stuff");
    Node n = p.getLookup().lookup(LogicalViewProvider.class).createLogicalView();
    assertEquals("Sweet Stuff", n.getName());
    assertEquals("Sweet Stuff", n.getDisplayName());
    NL nl = new NL();
    n.addNodeListener(nl);
    EditableProperties ep = p.getHelper().getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
    ep.setProperty("app.name", "sweetness");
    ep.setProperty("app.title", "Sweetness is Now!");
    p.getHelper().putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep);
    TestBase.waitForNodesUpdate();
    assertEquals(new HashSet<String>(Arrays.asList(Node.PROP_NAME, Node.PROP_DISPLAY_NAME)), nl.changed);
    assertEquals("Sweetness is Now!", n.getName());
    assertEquals("Sweetness is Now!", n.getDisplayName());
}
 
Example 7
Source File: Tab.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Initialize this top component properly with information
* obtained from specified root context node */
private void initializeWithRootContext (Node rc) {
    // update TC's attributes
    setToolTipText(rc.getDisplayName());
    setName(rc.getDisplayName());
    updateTitle();
    // attach listener
    if (weakRcL == null) {
        weakRcL = WeakListeners.propertyChange(
            rcListener(), rc
        );
    }
    rc.addPropertyChangeListener(weakRcL);

    if (weakNRcL == null) {
        weakNRcL = NodeOp.weakNodeListener (
            rcListener(), rc
        );
    }
    rc.addNodeListener(weakNRcL);
}
 
Example 8
Source File: ViewTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@RandomlyFails // NB-Core-Build #1012
public void testViewItemChanges() throws Exception {
    FileObject top = FileUtil.toFileObject(copyFolder(FileUtil.toFile(egdirFO.getFileObject("extsrcroot"))));
    FreeformProject extsrcroot_ = (FreeformProject) ProjectManager.getDefault().findProject(top.getFileObject("proj"));
    Node root = extsrcroot_.getLookup().lookup(LogicalViewProvider.class).createLogicalView();
    Children ch = root.getChildren();
    Node[] kids = ch.getNodes(true);
    assertEquals("two child nodes", 2, kids.length);
    assertEquals("correct code name #1", "../src", kids[0].getName());
    assertEquals("correct code name #2", "nbproject/project.xml", kids[1].getName());
    TestNL l = new TestNL();
    root.addNodeListener(l);
    Element data = extsrcroot_.getPrimaryConfigurationData();
    Element view = XMLUtil.findElement(data, "view", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <view>", view);
    Element items = XMLUtil.findElement(view, "items", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <items>", items);
    Element sourceFolder = XMLUtil.findElement(items, "source-folder", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <source-folder>", sourceFolder);
    Element location = XMLUtil.findElement(sourceFolder, "location", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <location>", location);
    NodeList nl = location.getChildNodes();
    assertEquals("one child", 1, nl.getLength());
    location.removeChild(nl.item(0));
    location.appendChild(location.getOwnerDocument().createTextNode("../src2"));
    Element sourceFile =  XMLUtil.findElement(items, "source-file", FreeformProjectType.NS_GENERAL);
    assertNotNull("have <source-file>", sourceFile);
    items.removeChild(sourceFile);
    extsrcroot_.putPrimaryConfigurationData(data);
    // children keys are updated asynchronously. give them a time
    Thread.sleep(500);
    assertFalse("got some changes in children", l.probeChanges().isEmpty());
    kids = ch.getNodes(true);
    assertEquals("one child node", 1, kids.length);
    assertEquals("correct code name #1", "../src2", kids[0].getName());
    assertEquals("correct display name #1", "External Sources", kids[0].getDisplayName());
    assertEquals("correct cookie #1",
            DataObject.find(top.getFileObject("src2")),
            kids[0].getLookup().lookup(DataObject.class));
}
 
Example 9
Source File: OpenProjectHookThrowsExceptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testBehaviourOfProjectsLogicNode() throws Exception {
    
    Node logicalView = new ProjectsRootNode(ProjectsRootNode.LOGICAL_VIEW);
    L listener = new L();
    logicalView.addNodeListener(listener);
    
    assertEquals("2 children", 2, logicalView.getChildren().getNodesCount());
    listener.assertEvents("None", 0);
    assertEquals("No project opened yet", 0, TestProjectOpenedHookImpl.opened);
    
    for (Node n : logicalView.getChildren().getNodes()) {
        TestSupport.TestProject p = n.getLookup().lookup(TestSupport.TestProject.class);
        assertNull("No project of this type, yet", p);
    }
    
    // let project open code run
    down.countDown();
    TestProjectOpenedHookImpl.toOpen.await();
    
    assertEquals("All projects opened", 2, TestProjectOpenedHookImpl.opened);
    
    OpenProjectList.waitProjectsFullyOpen();

    Node[] nodes = logicalView.getChildren().getNodes();
    assertEquals("No projects open", 0, nodes.length);
    
    listener.assertEvents("Goal is to receive no events at all", 1);
    assertTrue("Finished", OpenProjects.getDefault().openProjects().isDone());
    assertFalse("Not cancelled, Finished", OpenProjects.getDefault().openProjects().isCancelled());
    Project[] arr = OpenProjects.getDefault().openProjects().get();
    assertEquals("zero projects to be opened", 0, arr.length);
}
 
Example 10
Source File: CloseProjectsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testClose() throws Exception {
    Node logicalView = new ProjectsRootNode(ProjectsRootNode.LOGICAL_VIEW);
    L listener = new L();
    logicalView.addNodeListener(listener);
    
    assertEquals("30 children", 30, logicalView.getChildren().getNodesCount());
    listener.assertEvents("None", 0);
    assertEquals("No project opened yet", 0, TestProjectOpenedHookImpl.opened);
    
    Node[] nodeArray = logicalView.getChildren().getNodes();
    Project[] arr = new Project[nodeArray.length];
    int i = 0;
    for (Node n : nodeArray) {
        Project p = n.getLookup().lookup(TestSupport.TestProject.class);
        assertNull("No project of this type, yet", p);
        
        arr[i] = n.getLookup().lookup(Project.class);
        assertNotNull("but some project is there", arr[i]);
        
        if (i >= 15) {
            OpenProjects.getDefault().close(new Project[] { arr[i] });
        }
        i++;
    }
    ProjectsRootNode.ProjectChildren.RP.post(new Runnable() {public @Override void run() {}}).waitFinished();
    assertEquals("Just fifteen left nodes", 15, logicalView.getChildren().getNodesCount());

    // let the project open hook run
    down.countDown();
    
    OpenProjects.getDefault().close(arr);
    
    ProjectsRootNode.ProjectChildren.RP.post(new Runnable() {public @Override void run() {}}).waitFinished();
    assertEquals("View is empty", 0, logicalView.getChildren().getNodesCount());
}
 
Example 11
Source File: CookieAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Attach itself as a listener to the given nodes */
private void attachListeners(List<Reference<Node>> nodes) {
    if (nodes != null) {
        Iterator<Reference<Node>> it = nodes.iterator();

        while (it.hasNext()) {
            Node node = it.next().get();

            if (node != null) {
                node.addNodeListener(listener);
            }
        }
    }
}
 
Example 12
Source File: CookieAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Attach itself as a listener to the given nodes */
void attachListeners(List<Reference<Node>> nodes) {
    Iterator<Reference<Node>> it = nodes.iterator();

    while (it.hasNext()) {
        Node node = it.next().get();

        if (node != null) {
            node.addNodeListener(listener);
        }
    }
}
 
Example 13
Source File: TopComponent.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Attaches itself to a given node.
*/
private void attach(Node n) {
    synchronized (top) {
        node = new WeakReference<Node>(n);
        nodeL = WeakListeners.create(NodeListener.class, this, n);
        n.addNodeListener(nodeL);
        top.attachNodeName(this);
        top.setActivatedNodes(new Node[] { n });
        top.setName(n.getDisplayName());
    }
}
 
Example 14
Source File: DataEditorSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Annotates the editor with icon from the data object and also sets 
 * appropriate selected node. But only in the case the data object is valid.
 * This implementation also listen to display name and icon changes of the
 * node and keeps editor top component up-to-date. If you override this
 * method and not call super, please note that you will have to keep things
 * synchronized yourself. 
 *
 * @param editor the editor that has been created and should be annotated
 */
@Override
protected void initializeCloneableEditor (CloneableEditor editor) {
    // Prevention to bug similar to #17134. Don't call getNodeDelegate
    // on invalid data object. Top component should be discarded later.
    if(obj.isValid()) {
        Node ourNode = obj.getNodeDelegate();
        editor.setActivatedNodes (new Node[] { ourNode });
        editor.setIcon(ourNode.getIcon (java.beans.BeanInfo.ICON_COLOR_16x16));
        NodeListener nl = new DataNodeListener(editor);
        ourNode.addNodeListener(org.openide.nodes.NodeOp.weakNodeListener (nl, ourNode));
        nodeL = nl;
    }
}
 
Example 15
Source File: MenuBar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Constructor. */
public LazyMenu(final DataFolder df, boolean icon) {
    this.master = df;
    this.icon = icon;
    this.dynaModel = new DynaMenuModel();
    this.slave = new MenuFolder();
    
    setName(df.getName());
    final FileObject pf = df.getPrimaryFile();
    Object prefix = pf.getAttribute("property-prefix"); // NOI18N
    if (prefix instanceof String) {
        Enumeration<String> en = pf.getAttributes();
        while (en.hasMoreElements()) {
            String attrName = en.nextElement();
            if (attrName.startsWith((String)prefix)) {
                putClientProperty(
                    attrName.substring(((String)prefix).length()), 
                    pf.getAttribute(attrName)
                );
            }
        }
    }

    // Listen for changes in Node's DisplayName/Icon
    Node n = master.getNodeDelegate ();
    n.addNodeListener (org.openide.nodes.NodeOp.weakNodeListener (this, n));
    Mutex.EVENT.readAccess(this);
    getModel().addChangeListener(this);
}
 
Example 16
Source File: BasicAbstractResultsPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addChildAdditionListener(Node addedNode) {
    for (Node n : addedNode.getChildren().getNodes(true)) {
        addChildAdditionListener(n);
    }
    addedNode.addNodeListener(resultsNodeAdditionListener);

}
 
Example 17
Source File: ActionFilterNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void initChildren() {
    Node node = getOriginal();
    node.addNodeListener(WeakListeners.create(NodeListener.class, this, node));
    final boolean leaf = node.isLeaf();
    if (!leaf) {
        setChildren(children);
    }
}
 
Example 18
Source File: DataFolderTimeOrderTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testLastModifiedOrderUpdatedAfterFileIsTouched() throws Exception {
    aa.setSortMode(DataFolder.SortMode.LAST_MODIFIED);

    Node n = aa.getNodeDelegate().cloneNode();
    Node[] nodes = n.getChildren().getNodes(true);
    assertEquals ("Two nodes", 2, nodes.length);

    waitEvents();
    assertEquals("Sort mode not changed and children not refreshed: " + events, 2, events.size());
    assertTrue(DataFolder.PROP_SORT_MODE + " change not fired", events.contains(DataFolder.PROP_SORT_MODE));
    assertTrue(DataFolder.PROP_CHILDREN + " change not fired", events.contains(DataFolder.PROP_CHILDREN));
    assertEquals("Y.txt", nodes[0].getName()); // Y is newer
    assertEquals("X.txt", nodes[1].getName()); // X is older
    events.clear();

    final FileObject orig = lfs.findResource("AA/Y.txt");
    final FileObject touch = lfs.findResource("AA/X.txt");

    // After touching, X.txt will be newer than Y.txt.
    TestFileUtils.touch(FileUtil.toFile(touch), FileUtil.toFile(orig));
    // It's not enough to wait only for DataFolder event
    // because of number of RP tasks run before node children are updated
    // must wait for reorder fired by node itself.
    final CountDownLatch barrier = new CountDownLatch(1);
    NodeListener nodeList = new NodeAdapter() {

        @Override
        public void childrenReordered (NodeReorderEvent ev) {
            barrier.countDown();
        }
      
    };
    n.addNodeListener(nodeList);
    try {
        touch.refresh();
        waitEvents();
        // wait for node reorder event
        barrier.await(10, TimeUnit.SECONDS);
    } finally {
        n.removeNodeListener(nodeList);
    }
    assertEquals(0, barrier.getCount());
    assertTrue(DataFolder.PROP_CHILDREN + " change not fired", events.contains(DataFolder.PROP_CHILDREN));

    Node[] newNodes = n.getChildren().getNodes(true);
    assertEquals("Node " + nodes[1].getName() + " expected first.", newNodes[0], nodes[1]);
    assertEquals("Node " + nodes[0].getName() + " expected second.", newNodes[1], nodes[0]);
}
 
Example 19
Source File: FolderChildrenTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** #175220 - Tests that children keys are not changed when node and underlying
 * data object are garbage collected. It caused collapsing of tree.
 */
public void testNodeKeysNotChanged() throws Exception {
    LOG.info("testNodeKeysNotChanged starting");
    FileObject rootFolder = FileUtil.createMemoryFileSystem().getRoot();
    FileObject fo1 = rootFolder.createData("file1.java");
    assertNotNull(fo1);
    FileObject fo2 = rootFolder.createData("file2.java");
    DataObject do2 = DataObject.find(fo2);
    assertNotNull(fo2);
    Node folderNode = DataFolder.findFolder(rootFolder).getNodeDelegate();
    LOG.log(Level.INFO, "testNodeKeysNotChanged folderNode: {0}", folderNode);
    final AtomicInteger removedEventCount = new AtomicInteger(0);
    folderNode.addNodeListener(new NodeAdapter() {

        @Override
        public void childrenRemoved(NodeMemberEvent ev) {
            removedEventCount.incrementAndGet();
            LOG.log(Level.INFO, "testNodeKeysNotChanged childrenRemoved: {0}", ev);
        }
    });
    LOG.info("testNodeKeysNotChanged addNodeListener");

    // refresh children
    LOG.info("testNodeKeysNotChanged about to getNodes");
    folderNode.getChildren().getNodes(true);
    Node childNode1 = folderNode.getChildren().getNodeAt(0);
    LOG.log(Level.INFO, "testNodeKeysNotChanged child0{0}", childNode1);
    assertNotNull(childNode1);
    Node childNode2 = folderNode.getChildren().getNodeAt(1);
    LOG.log(Level.INFO, "testNodeKeysNotChanged child1{0}", childNode2);
    assertNotNull(childNode2);

    // GC node 2
    WeakReference<Node> ref = new WeakReference<Node>(childNode2);
    childNode2 = null;
    assertGC("Cannot GC childNode2", ref);
    // GC data object 2
    WeakReference<DataObject> refDO = new WeakReference<DataObject>(do2);
    do2 = null;
    assertGC("Cannot GC do2", refDO);

    // add new data object
    FileObject fo3 = rootFolder.createData("file3.java");
    assertNotNull(fo3);
    LOG.log(Level.INFO, "testNodeKeysNotChanged fo3: {0}", fo3);
    // refresh children
    folderNode.getChildren().getNodes(true);
    LOG.info("after get children");
    Node childNodeX = folderNode.getChildren().getNodeAt(1);
    LOG.log(Level.INFO, "childeNodeX: {0}", childNodeX);
    assertNotSame("Node 2 should not be the same when GC'd before.", childNode2, childNodeX);
    assertEquals("No node should be removed.", 0, removedEventCount.intValue());
    LOG.info("done");
}
 
Example 20
Source File: Install.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Shows dialog which waits for finishing of pending tasks,
 * (currently actions only) and offers to user to leave IDE
 * immediatelly interrupting those tasks.
 * @return <code>true</code> if to continue with the action
 * <code>false</code> if the action to cancel
 */
private static boolean showPendingTasks() {
    // Avoid showing the tasks in the dialog when either running internal tests
    if (Boolean.getBoolean("netbeans.full.hack") // NOI18N
            // or there are no pending tasks.
            || getPendingTasks().isEmpty()) {
        return true;
    }
    
    EM panel = new EM();
    
    Dialog[] dialog = new Dialog[1];
    Node root = new AbstractNode(new PendingChildren());
    
    
    JButton exitOption = new JButton();
    Mnemonics.setLocalizedText(exitOption, NbBundle.getMessage(Install.class, "LAB_EndTasks"));
    // No default button.
    // exitOption.setDefaultCapable(false);
    exitOption.getAccessibleContext().setAccessibleDescription(
            NbBundle.getMessage(Install.class, "ACSD_EndTasks"));
    
    PendingDialogCloser closer = new PendingDialogCloser(dialog, exitOption);
    
    panel.getExplorerManager().setRootContext(root);
    // closer will autoclose the dialog if all pending tasks finish
    panel.getExplorerManager().addPropertyChangeListener(closer);
    
    DialogDescriptor dd = new DialogDescriptor(
            panel,
            NbBundle.getMessage(Install.class, "CTL_PendingTitle"),
            true, // modal
            new Object[] {
        exitOption,
        DialogDescriptor.CANCEL_OPTION
    },
            exitOption,
            DialogDescriptor.DEFAULT_ALIGN,
            null,
            closer
            );
    // #33135 - no Help button for this dialog
    dd.setHelpCtx(null);
    
    if(!getPendingTasks().isEmpty()) {
        root.addNodeListener(closer);
        
        dialog[0] = DialogDisplayer.getDefault().createDialog(dd);
        
        dialog[0].addWindowListener(closer);
        
        dialog[0].setVisible(true);
        dialog[0].dispose();
        
        if(dd.getValue() == DialogDescriptor.CANCEL_OPTION
                || dd.getValue() == DialogDescriptor.CLOSED_OPTION) {
            return false;
        }
        
    }
    
    return true;
}