Java Code Examples for org.openide.util.lookup.InstanceContent#add()

The following examples show how to use org.openide.util.lookup.InstanceContent#add() . 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: RestServiceNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private RestServiceNode(Project project, RestServicesModel model,
        final RestServiceDescription desc, InstanceContent content) {
    super(new RestServiceChildren(project, model, desc.getName()), new AbstractLookup(content));
    this.serviceName = desc.getName();
    this.uriTemplate = desc.getUriTemplate();
    this.className = desc.getClassName();
    
    content.add(this);
    content.add(desc);
    content.add(new ResourceUriProvider() {
        public String getResourceUri() {
            return desc.getUriTemplate();
        }           
    });
    content.add(project);
    content.add(OpenCookieFactory.create(project, className));
    editorDrop = new ResourceToEditorDrop(this);
}
 
Example 2
Source File: FolderRenameHandlerImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRename(DataFolder folder, String newName) {
    InstanceContent ic = new InstanceContent();
    ic.add(folder.getNodeDelegate());
    ExplorerContext d = new ExplorerContext();
    d.setNewName(newName);
    ic.add(d);
    final Lookup l = new AbstractLookup(ic);
    if (ActionsImplementationFactory.canRename(l)) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Action a = RefactoringActionsFactory.renameAction().createContextAwareInstance(l);
                a.actionPerformed(RefactoringActionsFactory.DEFAULT_EVENT);
            }
        });
    } else {
        FileObject fo = folder.getPrimaryFile();
        try {
            folder.rename(newName);
        } catch (IOException ioe) {
            ErrorManager.getDefault().notify(ioe);
        }
    }
}
 
Example 3
Source File: GraphNode.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private GraphNode(final InputGraph graph, InstanceContent content) {
    super(Children.LEAF, new AbstractLookup(content));
    this.graph = graph;
    this.setDisplayName(graph.getName());
    content.add(graph);

    final GraphViewer viewer = Lookup.getDefault().lookup(GraphViewer.class);

    if (viewer != null) {
        // Action for opening the graph
        content.add(new OpenCookie() {

            public void open() {
                viewer.view(graph);
            }
        });
    }

    // Action for removing a graph
    content.add(new RemoveCookie() {

        public void remove() {
            graph.getGroup().removeGraph(graph);
        }
    });
}
 
Example 4
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static String getWebPageMimeType(SyntaxAnalyzerResult result) {
    InstanceContent ic = new InstanceContent();
    ic.add(result);
    WebPageMetadata wpmeta = WebPageMetadata.getMetadata(new AbstractLookup(ic));

    if (wpmeta != null) {
        //get an artificial mimetype for the web page, this doesn't have to be equal
        //to the fileObjects mimetype.
        String mimeType = (String) wpmeta.value(WebPageMetadata.MIMETYPE);
        if (mimeType != null) {
            return mimeType;
        }
    }

    FileObject fo = result.getSource().getSourceFileObject();
    if(fo != null) {
        return fo.getMIMEType();
    } else {
        //no fileobject?
        return result.getSource().getSnapshot().getMimeType();
    }

}
 
Example 5
Source File: CallbackActionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testCopyLikeProblem() throws Exception {
    FileObject fo = folder.getFileObject("testCopyLike.instance");

    Object obj = fo.getAttribute("instanceCreate");
    if (!(obj instanceof Action)) {
        fail("Shall create an action: " + obj);
    }

    InstanceContent ic = new InstanceContent();
    AbstractLookup l = new AbstractLookup(ic);
    ActionMap map = new ActionMap();
    map.put("copy-to-clipboard", new MyAction());
    ic.add(map);

    CntListener list = new CntListener();
    Action clone = ((ContextAwareAction)obj).createContextAwareInstance(l);
    clone.addPropertyChangeListener(list);
    assertTrue("Enabled", clone.isEnabled());

    ic.remove(map);
    assertFalse("Disabled", clone.isEnabled());
    list.assertCnt("one change", 1);
}
 
Example 6
Source File: ElementNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@NonNull
private static Lookup prepareLookup(@NonNull final Description d) {
    final InstanceContent ic = new InstanceContent();
    ic.add(d, ConvertDescription2FileObject);
    ic.add(d, ConvertDescription2DataObject);
    if (d.handle != null) {
        ic.add(d, ConvertDescription2TreePathHandle);
    }
    return new AbstractLookup(ic);
}
 
Example 7
Source File: MultiViewEditorElementTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLookupProvidersAreConsistent() throws Exception {
    InstanceContent ic = new InstanceContent();
    Lookup context = new AbstractLookup(ic);

    CloneableEditorSupport ces = createSupport(context);
    ic.add(ces);
    ic.add(10);

    final CloneableTopComponent tc = MultiViews.createCloneableMultiView("text/plaintest", new LP(context));
    final CloneableEditorSupport.Pane p = (CloneableEditorSupport.Pane) tc;
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            tc.open();
            tc.requestActive();
            p.updateName();
        }
    });

    assertNull("No icon yet", tc.getIcon());
    MultiViewHandler handler = MultiViews.findMultiViewHandler(tc);
    final MultiViewPerspective[] one = handler.getPerspectives();
    assertEquals("Two elements only" + Arrays.asList(one), 2, handler.getPerspectives().length);
    assertEquals("First one is source", "source", one[0].preferredID());
    assertEquals("Second one is also source", "source", one[1].preferredID());
    handler.requestVisible(one[0]);
    
    List<Lookup.Provider> arr = new ArrayList<Provider>();
    findProviders(tc, arr);
    assertEquals("Two providers: " + arr, 2, arr.size());

    assertSame("Both return same lookup", arr.get(0).getLookup(), arr.get(1).getLookup());
}
 
Example 8
Source File: HtmlRefactoringGlobalAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected Lookup getLookup(Node[] n) {
    InstanceContent ic = new InstanceContent();
    for (Node node:n)
        ic.add(node);
    if (n.length>0) {
        EditorCookie tc = getTextComponent(n[0]);
        if (tc != null) {
            ic.add(tc);
        }
    }
    ic.add(new Hashtable(0));
    return new AbstractLookup(ic);
}
 
Example 9
Source File: JAXBWizardRootNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private JAXBWizardRootNode(Project prj, InstanceContent content) {
    super(new JAXBWizardRootNodeChildren(prj), 
            new AbstractLookup(content));
    // adds the node to our own lookup
    content.add (this);
    // adds additional items to the lookup
    content.add (prj);
}
 
Example 10
Source File: HttpMethodNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private HttpMethodNode(Project project, RestServiceDescription desc, HttpMethod method,
        InstanceContent content) {
    super(Children.LEAF, new AbstractLookup(content));
    this.methodName = method.getName();
    this.produceMime = method.getProduceMime();
    this.consumeMime = method.getConsumeMime();
    this.returnType = method.getReturnType();
    content.add(this);
    // enable Test method Uri action only for GET methods
    if ("GET".equals(method.getType())) { //NOI18N
        content.add(new MethodUriProvider(desc.getUriTemplate(), method.getPath()));
    }
    content.add(project);
    content.add(OpenCookieFactory.create(project, desc.getClassName(), methodName));
}
 
Example 11
Source File: MethodNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private MethodNode(ClasspathInfo cpInfo, MethodModel method, String implBean, ComponentMethodViewStrategy cmvs, InstanceContent ic) {
        super(Children.LEAF, new AbstractLookup(ic));
        ic.add(this);
        ic.add(method);
//        disableDelegation(FilterNode.DELEGATE_DESTROY);
        this.cpInfo = cpInfo;
        this.method = method;
        this.implBean = implBean;
        this.cmvs = cmvs;
        this.implBeanFO = getFileObject(cpInfo, implBean);
        
        // TODO: listeners - WeakListener was used here before change to JMI, how to use it now?
        // unregister in appropriate point or play with ActiveQueue (openide utilities)
//        ((MDRChangeSource) method).addListener(this);  
    }
 
Example 12
Source File: RepositoryComboSupportTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private TestLookup(InstanceContent ic) {
    super(ic);
    ic.add(new DummyKenaiRepositories());
    ic.add(new DummyBugtrackingConnector());
    ic.add(new DummyWindowManager());
    ic.add(new DummyBugtrackingOwnerSupport());
}
 
Example 13
Source File: CallbackActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testWithFallback() throws Exception {
    MyAction myAction = new MyAction();
    MyAction fallAction = new MyAction();
    
    ActionMap other = new ActionMap();
    ActionMap tc = new ActionMap();
    tc.put("somekey", myAction);
    
    InstanceContent ic = new InstanceContent();
    AbstractLookup al = new AbstractLookup(ic);
    ic.add(tc);
    
    ContextAwareAction a = callback("somekey", fallAction, al, false);
    CntListener l = new CntListener();
    a.addPropertyChangeListener(l);

    assertTrue("My action is on", myAction.isEnabled());
    assertTrue("Callback is on", a.isEnabled());
    
    l.assertCnt("No change yet", 0);
    
    ic.remove(tc);
    assertTrue("fall is on", fallAction.isEnabled());
    assertTrue("My is on as well", a.isEnabled());

    l.assertCnt("Still enabled, so no change", 0);
    
    fallAction.setEnabled(false);
    
    l.assertCnt("Now there was one change", 1);
    
    assertFalse("fall is off", fallAction.isEnabled());
    assertFalse("My is off as well", a.isEnabled());
    
    
    Action a2 = a.createContextAwareInstance(Lookup.EMPTY);
    assertEquals("Both actions are equal", a, a2);
    assertEquals("and have the same hash", a.hashCode(), a2.hashCode());
}
 
Example 14
Source File: NavigatorTCTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ActNodeLookupProvider () {
    this.node1 = new AbstractNode(Children.LEAF);
    this.node1.setDisplayName(FIRST_NAME);
    this.node2 = new AbstractNode(Children.LEAF);
    this.node2.setDisplayName(SECOND_NAME);
    
    ic = new InstanceContent();
    ic.add(node1);
    lookup = new AbstractLookup(ic);
}
 
Example 15
Source File: ActionProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCallbackAction() throws Exception {
    Callback.cnt = 0;
    ContextAwareAction a = (ContextAwareAction) Actions.forID("Tools", "my.action");

    class MyAction extends AbstractAction {
        int cnt;
        @Override
        public void actionPerformed(ActionEvent e) {
            cnt += e.getID();
        }
    }
    MyAction my = new MyAction();
    ActionMap m = new ActionMap();
    m.put("klic", my);

    InstanceContent ic = new InstanceContent();
    AbstractLookup lkp = new AbstractLookup(ic);
    Action clone = a.createContextAwareInstance(lkp);
    ic.add(m);

    assertEquals("I am context", clone.getValue(Action.NAME));
    clone.actionPerformed(new ActionEvent(this, 300, ""));
    assertEquals("Local Action called", 300, my.cnt);
    assertEquals("Global Action not called", 0, Callback.cnt);

    ic.remove(m);
    clone.actionPerformed(new ActionEvent(this, 200, ""));
    assertEquals("Local Action stays", 300, my.cnt);
    assertEquals("Global Action ncalled", 200, Callback.cnt);
}
 
Example 16
Source File: ArtifactMultiViewFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Lookup createPomEditorLookup(final Project prj, @NonNull Artifact artifact) {
    final InstanceContent ic = new InstanceContent();
    AbstractLookup lookup = new AbstractLookup(ic);
    ic.add(artifact);
    if (prj != null) {
        ic.add(prj);
        //lookup for project non null means we are part of pom editor
        RP.post(new Runnable() {
            @Override
            public void run() {
                NbMavenProject im = prj.getLookup().lookup(NbMavenProject.class);
                MavenProject mvnprj = im.getMavenProject();
                DependencyNode tree = DependencyTreeFactory.createDependencyTree(mvnprj, EmbedderFactory.getProjectEmbedder(), Artifact.SCOPE_TEST);
                FileObject fo = prj.getLookup().lookup(FileObject.class);
                POMModel pommodel = null;
                if (fo != null) {
                    ModelSource ms = Utilities.createModelSource(fo);
                    if (ms.isEditable()) {
                        POMModel model = POMModelFactory.getDefault().getModel(ms);
                        if (model != null) {
                            pommodel = model;
                        }
                    }
                }
                //add all in one place to prevent large time delays between additions
                if (pommodel != null) {
                    ic.add(pommodel);
                }
                ic.add(tree);
                ic.add(mvnprj);
            }
        });
    }
    Action[] toolbarActions = new Action[] {
        new AddAsDependencyAction(artifact),
        CommonArtifactActions.createScmCheckoutAction(lookup),
        CommonArtifactActions.createLibraryAction(lookup)
    };
    ic.add(toolbarActions);
    
    return lookup;
}
 
Example 17
Source File: NavigatorTCTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/** Test for IZ feature #93711. It tests ability of NavigatorPanel implementors
 * to provide activated nodes for whole navigator panel TopComponent.
 * 
 * See inner class ActNodeLookupProvider, especially getLookup method to get
 * inspiration how to write providers that provide also activated nodes.
 */
public void testFeature93711_ActivatedNodes () throws Exception {
    System.out.println("Testing feature #93711, providing activated nodes...");

    InstanceContent ic = getInstanceContent();
    
    TestLookupHint actNodesHint = new TestLookupHint("actNodes/tester");
    ic.add(actNodesHint);
        
    NavigatorTC navTC = NavigatorTC.getInstance();
    NavigatorTCHandle navTCH = new NavigatorTCHandle(navTC);
    try {
        navTCH.open();
        waitForProviders(navTC);
        List<? extends NavigatorPanel> panels = navTC.getPanels();
        assertNotNull("Selected panel should not be null", navTC.getSelectedPanel());
        assertTrue("Expected 1 provider panel, but got " + panels.size(), panels != null && panels.size() == 1);
        assertTrue("Panel class not expected", panels.get(0) instanceof ActNodeLookupProvider);
        ActNodeLookupProvider provider = (ActNodeLookupProvider)panels.get(0);

        // wait for selected node change to be applied, because changes are
        // reflected with little delay
        waitForChange();

        // test if lookup content from provider propagated correctly to the
        // activated nodes of navigator TopComponent
        Node[] actNodes = navTC.getActivatedNodes();
        Collection<? extends Node> lookupNodes = navTC.getLookup().lookupAll(Node.class);
        Node realContent = provider.getCurLookupContent();
        String tcDisplayName = navTC.getDisplayName();
        String providerDisplayName = provider.getDisplayName();

        assertNotNull("Activated nodes musn't be null", actNodes);
        assertTrue("Expected 1 activated node, but got " + actNodes.length, actNodes.length == 1);
        assertTrue("Expected 1 node in lookup, but got " + lookupNodes.size(), lookupNodes.size() == 1);
        assertTrue("Incorrect instance of activated node " + actNodes[0].getName(), actNodes[0] == realContent);
        assertTrue("Different node in lookup than the activated node", realContent == lookupNodes.iterator().next());
        assertTrue("Expected display name starting with '" + providerDisplayName +
                    "', but got '" + tcDisplayName + "'",
                    (tcDisplayName != null) && tcDisplayName.startsWith(providerDisplayName));

        // change provider's lookup content and check again, to test infrastructure
        // ability to listen to client's lookup content change
        provider.changeLookup();
        waitForChange();
        
        actNodes = navTC.getActivatedNodes();
        realContent = provider.getCurLookupContent();
        tcDisplayName = navTC.getDisplayName();
        providerDisplayName = provider.getDisplayName();

        assertNotNull("Activated nodes musn't be null", actNodes);
        assertTrue("Expected 1 activated node, but got " + actNodes.length, actNodes.length == 1);
        assertTrue("Incorrect instance of activated node " + actNodes[0].getName(), actNodes[0] == realContent);
        assertTrue("Expected display name starting with '" + providerDisplayName +
                    "', but got '" + tcDisplayName + "'",
                    (tcDisplayName != null) && tcDisplayName.startsWith(providerDisplayName));
    } finally {
        // cleanup
        navTCH.close();
        ic.remove(actNodesHint);
    }
}
 
Example 18
Source File: TopComponentGetLookupTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testNodesAreThereEvenIfTheyAreNotContainedInTheirOwnLookup () {
        Lookup.Result res = lookup.lookup(new Lookup.Template(Node.class));
        
        AbstractNode n1 = new AbstractNode(Children.LEAF, Lookup.EMPTY);
        
        InstanceContent content = new InstanceContent ();
        AbstractNode n2 = new AbstractNode(Children.LEAF, new AbstractLookup(content));
        
        assertNull ("Not present in its lookup", n1.getLookup ().lookup (n1.getClass ()));
        assertNull ("Not present in its lookup", n2.getLookup ().lookup (n2.getClass ()));
        
        top.setActivatedNodes (new AbstractNode[] { n1 });
        assertEquals ("But node is in the lookup", n1, lookup.lookup (n1.getClass ()));
        
        assertEquals ("One item there", 1, res.allInstances ().size ());
        
        L listener = new L ();
        res.addLookupListener(listener);
        
        top.setActivatedNodes (new AbstractNode[] { n2 });
        assertEquals ("One node there", 1, get.getActivatedNodes ().length);
        assertEquals ("n2", n2, get.getActivatedNodes ()[0]);
        
//MK - here it changes twice.. because the setAtivatedNodes is trigger on inner TC, then lookup of MVTC contains old activated node..
        // at this monent the merged lookup contains both items.. later it gets synchronized by setting the activated nodes on the MVTC as well..
        // then it contains only the one correct node..
        listener.check ("Node changed", 1);
        
        Collection addedByTCLookup = res.allInstances();
        assertEquals ("One item still", 1, addedByTCLookup.size ());
        
        content.add (n2);
        assertEquals ("After the n2.getLookup starts to return itself, there is no change", 
            addedByTCLookup, res.allInstances ());

        // this could be commented out if necessary:
        listener.check ("And nothing is fired", 0);
        
        content.remove (n2);
        assertEquals ("After the n2.getLookup stops to return itself, there is no change", 
            addedByTCLookup, res.allInstances ());
        // this could be commented out if necessary:
        listener.check ("And nothing is fired", 0);
        
        content.add (n1);
        // this could be commented out if necessary:
        listener.check ("And nothing is fired", 0);
        // Change from former behavior (#36336): we don't *want* n1 in res.
        Collection one = res.allInstances();
        assertEquals("Really just the activated node", 1, one.size());
        Iterator it = one.iterator();
        assertEquals("It is the one added by the TC lookup", n2, it.next());
    }
 
Example 19
Source File: TopComponentGetLookupTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void doTestNoChangeWhenSomethingIsChangedOnNotActivatedNode(int initialSize) {
    Object obj = new OpenCookie() { public void open() {} };
    
    Lookup.Result<OpenCookie> res = lookup.lookup(new Lookup.Template<OpenCookie>(OpenCookie.class));
    Lookup.Result<Node> nodeRes = lookup.lookup(new Lookup.Template<Node>(Node.class));
    
    InstanceContent ic = new InstanceContent();
    CountingLookup cnt = new CountingLookup(ic);
    AbstractNode ac = new AbstractNode(Children.LEAF, cnt);
    for (int i = 0; i < initialSize; i++) {
        ic.add(new Integer(i));
    }
    
    top.setActivatedNodes(new Node[] { ac });
    assertEquals("One node there", 1, get.getActivatedNodes().length);
    assertEquals("It is the ac one", ac, get.getActivatedNodes()[0]);
    ic.add(obj);
    
    L listener = new L();
    
    res.allItems();
    nodeRes.allItems();
    res.addLookupListener(listener);
    
    Collection allListeners = cnt.listeners;
    
    assertEquals("Has the cookie", 1, res.allItems().size());
    listener.check("No changes yet", 0);
    
    ic.remove(obj);
    
    assertEquals("Does not have the cookie", 0, res.allItems().size());
    listener.check("One change", 1);
    
    top.setActivatedNodes(new N[0]);
    assertEquals("The nodes are empty", 0, get.getActivatedNodes().length);
    listener.check("No change", 0);
    
    cnt.queries = 0;
    ic.add(obj);
    ic.add(ac);
    listener.check("Removing the object or node from not active node does not send any event", 0);
    
    nodeRes.allItems();
    listener.check("Queriing for node does generate an event", 0);
    assertEquals("No Queries to the not active node made", 0, cnt.queries);
    assertEquals("No listeneners on cookies", allListeners, cnt.listeners);
}
 
Example 20
Source File: GlassfishInstance.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("LeakingThisInConstructor")
private GlassfishInstance(Map<String, String> ip, GlassFishVersion version,
        GlassfishInstanceProvider instanceProvider, boolean prepareProperties) {
    this.version = version;
    this.process = null;
    ic = new InstanceContent();
    localLookup = new AbstractLookup(ic);
    full = localLookup;
    this.instanceProvider = instanceProvider;
    String domainDirPath = ip.get(GlassfishModule.DOMAINS_FOLDER_ATTR);
    String domainName = ip.get(GlassfishModule.DOMAIN_NAME_ATTR);
    if (null != domainDirPath && null != domainName) {
        File domainDir = new File(domainDirPath,domainName);
        PortCollection pc = new PortCollection();
        if (Util.readServerConfiguration(domainDir, pc)) {
            ip.put(GlassfishModule.ADMINPORT_ATTR,
                    Integer.toString(pc.getAdminPort()));
            ip.put(GlassfishModule.HTTPPORT_ATTR,
                    Integer.toString(pc.getHttpPort()));
        }
        domainXMLListener = new DomainXMLChangeListener(this, 
                ServerUtils.getDomainConfigFile(domainDirPath, domainName));
    } else {
        domainXMLListener = null;
    }
    if (prepareProperties) {
        this.properties = prepareProperties(ip);
    } else {
        this.properties = new Props(ip);
    }
    if (!isPublicAccess()) {
        // Add this instance into local lookup (to find instance from
        // node lookup).
        ic.add(this); 
        commonInstance = ServerInstanceFactory.createServerInstance(this);
    }
    // Warn when creating instance of unknown version.
    if (this.version == null) {
        String installroot = ip.get(GlassfishModule.GLASSFISH_FOLDER_ATTR);
        String displayName = ip.get(GlassfishModule.DISPLAY_NAME_ATTR);
        WarnPanel.gfUnknownVersionWarning(displayName, installroot);
        LOGGER.log(Level.INFO, NbBundle.getMessage(
                GlassfishInstance.class,
                "GlassfishInstance.init.versionNull",
                new String[] {displayName, installroot}));
    }
    this.commonSupport = new CommonServerSupport(this);
}