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

The following are Jave code examples for showing how to use addNodeListener() of the org.openide.nodes.Node class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: incubator-netbeans   File: MatchingObjectNode.java   Source Code and License Vote up 6 votes
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 2
Project: incubator-netbeans   File: SuiteLogicalViewTest.java   Source Code and License Vote up 6 votes
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 3
Project: incubator-netbeans   File: PropertiesRowModel.java   Source Code and License Vote up 6 votes
@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
Project: incubator-netbeans   File: PropertySheet.java   Source Code and License Vote up 6 votes
/** 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
Project: incubator-netbeans   File: HelpCtxProcessor.java   Source Code and License Vote up 6 votes
/** 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
Project: incubator-netbeans   File: FormEditorSupport.java   Source Code and License Vote up 6 votes
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 7
Project: incubator-netbeans   File: BasicAbstractResultsPanel.java   Source Code and License Vote up 5 votes
private void addChildAdditionListener(Node addedNode) {
    for (Node n : addedNode.getChildren().getNodes(true)) {
        addChildAdditionListener(n);
    }
    addedNode.addNodeListener(resultsNodeAdditionListener);

}
 
Example 8
Project: incubator-netbeans   File: OpenProjectHookThrowsExceptionTest.java   Source Code and License Vote up 5 votes
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 9
Project: incubator-netbeans   File: CloseProjectsTest.java   Source Code and License Vote up 5 votes
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 10
Project: incubator-netbeans   File: ActionFilterNode.java   Source Code and License Vote up 5 votes
private void initChildren() {
    Node node = getOriginal();
    node.addNodeListener(WeakListeners.create(NodeListener.class, this, node));
    final boolean leaf = node.isLeaf();
    if (!leaf) {
        setChildren(children);
    }
}
 
Example 11
Project: incubator-netbeans   File: MenuBar.java   Source Code and License Vote up 5 votes
/** 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 12
Project: incubator-netbeans   File: DataEditorSupport.java   Source Code and License Vote up 5 votes
/** 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 13
Project: incubator-netbeans   File: TopComponent.java   Source Code and License Vote up 5 votes
/** 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
Project: incubator-netbeans   File: CookieAction.java   Source Code and License Vote up 5 votes
/** 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 15
Project: incubator-netbeans   File: CookieAction.java   Source Code and License Vote up 5 votes
/** 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 16
Project: incubator-netbeans   File: ViewTest.java   Source Code and License Vote up 5 votes
@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 17
Project: incubator-netbeans   File: ProjectsRootNode.java   Source Code and License Vote up 4 votes
@NonNull
final Node logicalViewForProject(
        @NonNull final Project project,
        final Union2<LogicalViewProvider,org.openide.util.Pair<Sources,SourceGroup[]>> data,
        final boolean[] projectInLookup) {
    Node node;            
    if (!data.hasFirst()) {
        LOG.log(
                Level.WARNING,
                "Warning - project of {0} in {1} failed to supply a LogicalViewProvider in its lookup",  // NOI18N
                new Object[]{
                    project.getClass(),
                    FileUtil.getFileDisplayName(project.getProjectDirectory())
                });
        final Sources sources = data.second().first();
        final SourceGroup[] groups = data.second().second();
        sources.removeChangeListener(this);
        sources.addChangeListener(this);
        if (groups.length > 0) {
            node = PhysicalView.createNodeForSourceGroup(groups[0], project);
        } else {
            node = Node.EMPTY;
        }
    } else {
        final LogicalViewProvider lvp = data.first();
        node = lvp.createLogicalView();
        if (!project.equals(node.getLookup().lookup(Project.class))) {
            // Various actions, badging, etc. are not going to work.
            LOG.log(
                    Level.WARNING,
                    "Warning - project {0} failed to supply itself in the lookup of the root node of its own logical view",  // NOI18N
                    ProjectUtils.getInformation(project).getName());
            //#114664
            if (projectInLookup != null) {
                projectInLookup[0] = false;
            }
        }
    }                        
    node.addNodeListener(WeakListeners.create(NodeListener.class, this, node));
    return node;
}
 
Example 18
Project: incubator-netbeans   File: FolderChildrenTest.java   Source Code and License Vote up 4 votes
/** #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 19
Project: incubator-netbeans   File: DataFolderTimeOrderTest.java   Source Code and License Vote up 4 votes
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 20
Project: incubator-netbeans   File: Install.java   Source Code and License Vote up 4 votes
/** 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;
}