Java Code Examples for org.openide.util.Lookup#Item

The following examples show how to use org.openide.util.Lookup#Item . 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: CookieSet.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static void enhancedQueryMode(Lookup lookup, Class<?> clazz) {
    Object type = QUERY_MODE.get();
    if (type != clazz) {
        return;
    }
    Collection<? extends Lookup.Item<?>> items = lookup.lookupResult(clazz).allItems();
    if (items.size() == 0) {
        return;
    }
    AbstractLookup.Pair[] arr = new AbstractLookup.Pair[items.size()];
    Iterator<? extends Lookup.Item> it = items.iterator();
    for (int i = 0; i < arr.length; i++) {
        arr[i] = new PairWrap(it.next());
    }
    QUERY_MODE.set(arr);
}
 
Example 2
Source File: AbstractLookupBaseHid.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Items are the same as results.
 */
public void testItemsAndIntances () {
    addInstances (INSTANCES);
    
    Lookup.Result<Object> r = lookup.lookupResult(Object.class);
    Collection<? extends Lookup.Item<?>> items = r.allItems();
    Collection<?> insts = r.allInstances();
    
    if (items.size () != insts.size ()) {
        fail ("Different size of sets");
    }

    for (Lookup.Item<?> item : items) {
        if (!insts.contains (item.getInstance ())) {
            fail ("Intance " + item.getInstance () + " is missing in " + insts);
        }
    }
}
 
Example 3
Source File: DefaultEMLookup.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Collection<? extends Item<T>> allItems() {
    Collection<? extends Item<T>> c = delegate.allItems();
    List<Item<T>> ret = new ArrayList<Item<T>>(c.size()); // upper bound

    for (Lookup.Item<T> i : c) {
        if (Node.class.isAssignableFrom(i.getType())) 
        {
            if (verboten.containsKey(i.getInstance())) {
                continue;
            }
        }
        ret.add(i);
    }

    return ret;
}
 
Example 4
Source File: ToolsAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
static List<Action> getToolActions() {
    ActionManager am = ActionManager.getDefault();
    List<Action> arr = new ArrayList<Action>();
    arr.addAll(Arrays.<Action>asList(am.getContextActions()));

    String pref = arr.isEmpty() ? null : "";
    for (Lookup.Item<Action> item : gl().result.allItems()) {
        final Action action = item.getInstance();
        if (action == null) {
            continue;
        }
        String where = item.getId().replaceFirst("[^/]*$", ""); // NOI18N
        if (pref != null && !pref.equals(where)) {
            arr.add(null);
        }
        pref = where;
        arr.add(action);
    }
    return arr;
}
 
Example 5
Source File: DelegatingLookupImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean isAllJustLookupProviders(Lookup lkp) {
    for (Lookup.Item<?> item : lkp.lookupResult(Object.class).allItems()) {
        Class<?> clzz = item.getType();
        if (!LookupProvider.class.isAssignableFrom(clzz) && !MetaLookupMerger.class.isAssignableFrom(clzz)) {
            LOG.log(Level.WARNING, "{0} from {1} is not a LookupProvider", new Object[] {clzz.getName(), item.getId()});
        }
    }
    return true; // always just print warnings
}
 
Example 6
Source File: J2SEPlatformCustomizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void initComponents () {
    this.getAccessibleContext().setAccessibleName (NbBundle.getMessage(J2SEPlatformCustomizer.class,"AN_J2SEPlatformCustomizer"));
    this.getAccessibleContext().setAccessibleDescription (NbBundle.getMessage(J2SEPlatformCustomizer.class,"AD_J2SEPlatformCustomizer"));
    this.addTab(NbBundle.getMessage(J2SEPlatformCustomizer.class,"TXT_Classes"), createPathTab(CLASSPATH));
    this.addTab(NbBundle.getMessage(J2SEPlatformCustomizer.class,"TXT_Sources"), createPathTab(SOURCES));
    this.addTab(NbBundle.getMessage(J2SEPlatformCustomizer.class,"TXT_Javadoc"), createPathTab(JAVADOC));
    final Lookup lkp = Lookups.forPath(CUSTOMIZERS_PATH);
    final boolean isDefaultPlatform = platform instanceof DefaultPlatformImpl;
    for (Lookup.Item<? extends Customizer> li : lkp.lookupResult(Customizer.class).allItems()) {
        final Customizer c = li.getInstance();
        if (!(c instanceof Component)) {
            continue;
        }
        String name = li.getId();
        final FileObject fo = FileUtil.getConfigFile(String.format("%s.instance",name));    //NOI18N
        if (fo != null) {
            try {
                name = fo.getFileSystem().getDecorator().annotateName(fo.getName(), Collections.<FileObject>singleton(fo));
            } catch (FileStateInvalidException ex) {
                name = fo.getName();
            }
            if (isDefaultPlatform &&
                fo.getAttribute(SUPPORTS_DEFAULT_PLATFORM) == Boolean.FALSE) {
                continue;
            }
        }
        c.setObject(platform);
        this.addTab(name, (Component)c);
    }
}
 
Example 7
Source File: RecognizeInstanceFilesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testNumericOrdering() throws Exception {
    class Tst implements FileSystem.AtomicAction {
        public void run() throws IOException {
            init();
        }
        
        void init() throws IOException {
            FileObject inst = FileUtil.createData(root, "inst/positional/X.instance");
            inst.setAttribute("instanceCreate", Long.valueOf(1000));
            inst.setAttribute("position", 3);
            FileObject inst2 = FileUtil.createData(root, "inst/positional/A.instance");
            inst2.setAttribute("instanceCreate", Long.valueOf(500));
            inst2.setAttribute("position", 1);
            FileObject inst3 = FileUtil.createData(root, "inst/positional/B.instance");
            inst3.setAttribute("instanceCreate", Long.valueOf(1500));
            inst3.setAttribute("position", 4);
            FileObject inst4 = FileUtil.createData(root, "inst/positional/C.instance");
            inst4.setAttribute("instanceCreate", Long.valueOf(700));
            inst4.setAttribute("position", 2);
        }
        
        void verify() {
            Lookup l = Lookups.forPath("inst/positional");
            Iterator<? extends Long> lng = l.lookupAll(Long.class).iterator();
            assertEquals(Long.valueOf(500), lng.next());
            assertEquals(Long.valueOf(700), lng.next());
            assertEquals(Long.valueOf(1000), lng.next());
            assertEquals(Long.valueOf(1500), lng.next());
            Iterator<? extends Lookup.Item<Long>> items = l.lookupResult(Long.class).allItems().iterator();
            assertEquals("inst/positional/A", items.next().getId());
            assertEquals("inst/positional/C", items.next().getId());
            assertEquals("inst/positional/X", items.next().getId());
            assertEquals("inst/positional/B", items.next().getId());
        }
    }
    
    Tst tst = new Tst();
    root.getFileSystem().runAtomicAction(tst);
    tst.verify();
}
 
Example 8
Source File: ObjectEditor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Searches between items whether there is one with the same display name.
 * @param str item name
 */
@Override
public void setAsText(java.lang.String str) throws java.lang.IllegalArgumentException {
    if (nullValue != null && nullValue.equals (str)) {
        setValue (null);
        return;
    }
    
    
    Collection allItems = lookup ().lookup (template ()).allItems ();
    
    Iterator it = allItems.iterator ();
    while (it.hasNext ()) {
        Lookup.Item item = (Lookup.Item)it.next ();
        
        if (item.getDisplayName().equals (str)) {
            setValue (item.getInstance ());
            firePropertyChange();
            return;
        }
    }
    IllegalArgumentException iae = new IllegalArgumentException (str);
    String msg = MessageFormat.format(
        NbBundle.getMessage(
            ObjectEditor.class, "FMT_EXC_GENERIC_BAD_VALUE"),  //NOI18N
            new Object[] {str});
    UIExceptions.annotateUser(iae, str, msg, null, new Date());
    throw iae;        
}
 
Example 9
Source File: HtmlBrowser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void setAsText (java.lang.String str) throws java.lang.IllegalArgumentException {
          try {
              if (NbBundle.getMessage (FactoryEditor.class, "CTL_UnspecifiedBrowser").equals (str) //NOI18N
              ||  str == null) {
                  setValue (null);
                  return;
              }
              Lookup.Result<org.openide.awt.HtmlBrowser.Factory> r = Lookup.getDefault().lookupResult(org.openide.awt.HtmlBrowser.Factory.class);
for (Lookup.Item<org.openide.awt.HtmlBrowser.Factory> i: r.allItems()) {
                  if (str.equals(i.getDisplayName())) {
                      setValue (i.getInstance());
                      return;
                  }
              }
          }
          catch (Exception e) {
          IllegalArgumentException iae = new IllegalArgumentException (e.getMessage());
          String msg = e.getLocalizedMessage();
          if (msg == null) {
              msg = MessageFormat.format(
                  NbBundle.getMessage(
                  HtmlBrowser.class, "FMT_EXC_GENERIC_BAD_VALUE"), //NOI18N
                  new Object[] {str}); 
          }
          UIExceptions.annotateUser(iae, str, msg, e, new java.util.Date());
          throw iae;
          }
      }
 
Example 10
Source File: HtmlBrowser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public String getAsText () {
    try {
        org.openide.awt.HtmlBrowser.Factory f = (org.openide.awt.HtmlBrowser.Factory)getValue ();
        
        Lookup.Item<org.openide.awt.HtmlBrowser.Factory> i = Lookup.getDefault().lookupItem(
            new Lookup.Template<org.openide.awt.HtmlBrowser.Factory> (org.openide.awt.HtmlBrowser.Factory.class, null, f)
        );
        if (i != null)
            return i.getDisplayName();
    }
    catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
    return NbBundle.getMessage (FactoryEditor.class, "CTL_UnspecifiedBrowser"); //NOI18N
}
 
Example 11
Source File: NbStartStop.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void initialize() {
    for (Lookup.Item<Runnable> item : onStart().allItems()) {
        synchronized (onStart) {
            RequestProcessor.Task already = onStart.get(item.getId());
            if (already == null) {
                Runnable r = item.getInstance();
                if (r != null) {
                    onStart.put(item.getId(), RP.post(r));
                }
            }
        }
    }
    
}
 
Example 12
Source File: RecognizeInstanceFilesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void doTestAvoidStackTraces() throws Exception {
    CharSequence log = Log.enable(RecognizeInstanceFiles.class.getName(), Level.INFO);
    Lookup lkp = Lookups.forPath("d");
    assertEquals(null, lkp.lookup(Runnable.class));
    Collection<? extends Lookup.Item<Object>> items = lkp.lookupResult(Object.class).allItems();
    if (!items.isEmpty()) {
        assertEquals(1, items.size());
        Lookup.Item<Object> item = items.iterator().next();
        assertEquals(Void.class, item.getType());
        assertEquals(null, item.getInstance());
    }
    assertEquals("", log.toString());
    // this ignores instanceOf (probably OK) and does print a CNFE stack (also probably OK):
    assertEquals(null, FileUtil.getConfigObject("d/meaningless-name.instance", Object.class));
}
 
Example 13
Source File: SimpleLookupTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testLookupItem() {
    SomeInst inst = new SomeInst();
    Lookup.Item item = Lookups.lookupItem(inst, "XYZ");
    
    assertTrue("Wrong instance", item.getInstance() == inst);
    assertTrue("Wrong instance class", item.getType() == inst.getClass());
    assertEquals("Wrong id", "XYZ", item.getId());

    item = Lookups.lookupItem(inst, null);
    assertNotNull("Id must never be null", item.getId());
}
 
Example 14
Source File: ExcludingLookup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Lookup.Item<T> lookupItem(Lookup.Template<T> template) {
    if (areSubclassesOfThisClassAlwaysExcluded(template.getType())) {
        return null;
    }

    Lookup.Item<T> retValue = delegate.lookupItem(template);

    if (isObjectAccessible(template.getType(), retValue, 2)) {
        return retValue;
    } else {
        return null;
    }
}
 
Example 15
Source File: NodeLookupTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testItIsPossibleToWrapACookieSet () {
    final int[] cnt = { 0, 0 };
    CookieNode n = new CookieNode () {
        {
            class F implements CookieSet.Factory, org.openide.cookies.OpenCookie {
                public Node.Cookie createCookie(Class klass) {
                    return this;
                }

                public void open () {
                    cnt[1]++;
                }
            }
            getCookieSet ().add (org.openide.cookies.OpenCookie.class, new F ());
        }
        public Node.Cookie getCookie (Class c) {
            if (org.openide.cookies.OpenCookie.class == c) {
                return new org.openide.cookies.OpenCookie () {
                    public void open () {
                        Object s = getCookieSet ().getCookie (org.openide.cookies.OpenCookie.class);
                        cnt[0]++;
                        ((org.openide.cookies.OpenCookie)s).open ();
                    }
                };
            }
            return super.getCookie (c);
        }
    };
    
    Lookup.Item item = n.getLookup().lookupItem (new Lookup.Template (org.openide.cookies.OpenCookie.class));
    assertNotNull (item);
    assertEquals ("No factory", 0, cnt[1]);
    assertEquals ("No call", 0, cnt[0]);
    
    org.openide.cookies.OpenCookie oc = (org.openide.cookies.OpenCookie)item.getInstance ();
    assertEquals ("No factory", 0, cnt[1]);
    assertEquals ("No call", 0, cnt[0]);
    
    oc.open ();
    assertEquals ("Once factory", 1, cnt[1]);
    assertEquals ("Once call", 1, cnt[0]);
    
}
 
Example 16
Source File: ModuleManagerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testLookup() throws Exception {
    MockModuleInstaller installer = new MockModuleInstaller();
    MockEvents ev = new MockEvents();
    ModuleManager mgr = new ModuleManager(installer, ev);
    mgr.mutexPrivileged().enterWriteAccess();
    Module m1, m2;
    try {
        m2 = mgr.create(new File(jars, "depends-on-simple-module.jar"), null, false, false, false);
        m1 = mgr.create(new File(jars, "simple-module.jar"), null, false, false, false);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
    Lookup l = mgr.getModuleLookup();
    assertNull(l.lookup(String.class));
    Object random = l.lookup(ModuleInfo.class);
    assertTrue(random == m1 || random == m2);
    random = l.lookup(Module.class);
    assertTrue(random == m1 || random == m2);
    Lookup.Result<ModuleInfo> resultAll = l.lookupResult(ModuleInfo.class);
    assertEquals("finding all instances works", new HashSet<Module>(Arrays.asList(m1, m2)), new HashSet<ModuleInfo>(resultAll.allInstances()));
    Lookup.Result<Module> resultInstance2 = l.lookup(new Lookup.Template<Module>(null, null, m2));
    assertEquals("finding one specific instance works", Collections.singleton(m2), new HashSet<Module>(resultInstance2.allInstances()));
    Collection<? extends Lookup.Item<Module>> items = resultInstance2.allItems();
    assertTrue(items.size() == 1);
    Lookup.Item<Module> item = items.iterator().next();
    assertEquals(m2, item.getInstance());
    Util.err.log(Level.INFO, "Item ID: {0}", item.getId());
    assertTrue("Item class is OK: " + item.getType(), item.getType().isAssignableFrom(Module.class));
    assertEquals("finding by ID works", Collections.singleton(m2),
            new HashSet<Module>(l.lookup(new Lookup.Template<Module>(null, item.getId(), null)).allInstances()));
    final boolean[] waiter = new boolean[] {false};
    resultAll.addLookupListener(new LookupListener() {
        public @Override void resultChanged(LookupEvent lev) {
            Util.err.log(Level.INFO, "Got event: {0}", lev);
            synchronized (waiter) {
                waiter[0] = true;
                waiter.notify();
            }
        }
    });
    Module m3;
    mgr.mutexPrivileged().enterWriteAccess();
    try {
        m3 = mgr.create(new File(jars, "cyclic-1.jar"), null, false, false, false);
        mgr.delete(m2);
    } finally {
        mgr.mutexPrivileged().exitWriteAccess();
    }
    assertEquals("results changed", new HashSet<ModuleInfo>(Arrays.asList(m1, m3)), new HashSet<ModuleInfo>(resultAll.allInstances()));
    synchronized (waiter) {
        if (! waiter[0]) {
            waiter.wait(5000);
        }
    }
    assertTrue("got lookup changes within 5 seconds", waiter[0]);
}
 
Example 17
Source File: GlobalContextImplTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void doRequestVisibleBlinksTheActionMapForAWhile(TopComponent my, boolean requestVisible, final boolean recursive) throws Exception {
    final org.openide.nodes.Node n = new org.openide.nodes.AbstractNode (org.openide.nodes.Children.LEAF);
    tc.setActivatedNodes(new Node[] { n });
    
    assertActionMap ();
    
    class L implements org.openide.util.LookupListener {
        Lookup.Result<ActionMap> res = lookup.lookup (new Lookup.Template<ActionMap> (ActionMap.class));
        ArrayList<ActionMap> maps = new ArrayList<ActionMap> ();
        int cnt;
        
        public void resultChanged (org.openide.util.LookupEvent ev) {
            assertTrue("Changes are comming from AWT thread only", EventQueue.isDispatchThread());
            assertEquals ("Still only one", 1, res.allItems ().size ());
            Lookup.Item<ActionMap> i = res.allItems ().iterator ().next ();
            assertNotNull (i);
            
            maps.add (i.getInstance ());
            
            assertNode ();

            if (recursive && cnt++ == 0) {
                GlobalActionContextImpl.blickActionMap(new ActionMap());
            }
        }
        
        public void assertNode () {
            assertEquals ("The node is available", n, lookup.lookup (Node.class));
        }
    }
    L myListener = new L ();
    assertEquals ("One action map", 1, myListener.res.allItems ().size ());
    myListener.assertNode ();
    
    ActionMap m1, m2;
    myListener.res.addLookupListener (myListener);
    try {
        if (requestVisible) {
            my.requestVisible ();
        } else {
            my.getActionMap().setParent(new ActionMap());
        }
        waitEQ();
        if (recursive) {
            return;
        }

        if (myListener.maps.size () != 2) {
            fail ("Expected two changes in the ActionMaps: " + myListener.maps);
        }

        myListener.assertNode ();

        m1 = myListener.maps.get(0);
        m2 = myListener.maps.get(1);

        assertNull ("Our action is not in first map", m1.get (KEY));
        assertEquals ("Our action is in second map", sampleAction, m2.get (KEY));

        assertActionMap ();
    } finally {
        myListener.res.removeLookupListener(myListener);
    }

    my.close();
    
 //   new TopComponent ().open();
    
    Reference<Object> ref = new WeakReference<Object>(my);
    my = null;
    m1 = null;
    m2 = null;
    myListener.maps.clear();

    //this.tc = null;
    //this.lookup = null;
    //this.result = null;
    //myListener.res = null;
    //myListener = null;
    //this.sampleAction = null;
    
    assertGC("Can be GCed", ref);
}
 
Example 18
Source File: StartupExtender.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Returns all registered {@link StartupExtender}s for the given start mode.
 * <p>
 * The contents of the {@code context} parameter will depend on the kind of
 * execution. For a simple Java SE program being run in the Java launcher,
 * a {@code org.netbeans.api.project.Project} can be expected; where available,
 * a {@code org.netbeans.api.java.platform.JavaPlatform} will be present as well.
 * For a Java EE program being run in an application server,
 * a {@code org.netbeans.api.server.ServerInstance} can be expected in the
 * context. Other kinds of API objects may be present according to contracts
 * not specified here.
 * <p>This method should not be called unless and until the program is really
 * about to be run, i.e. all known preconditions have been satisfied.
 * @param context the lookup providing the contract between client
 *             and provider
 * @param mode the startup mode the client is going to use
 * @return the extenders representing all registered
 *             {@link StartupExtenderImplementation}
 */
@NonNull
public static List<StartupExtender> getExtenders(
        @NonNull Lookup context, @NonNull StartMode mode) {
    Parameters.notNull("context", context);
    Parameters.notNull("mode", mode);
    LOG.log(Level.FINE, "getExtenders: context={0} mode={1}", new Object[] {context, mode});

    Lookup lkp = Lookups.forPath(StartupExtenderRegistrationProcessor.PATH);

    List<StartupExtender> res = new ArrayList<StartupExtender>();
    for (Lookup.Item<StartupExtenderImplementation> item : lkp.lookupResult(StartupExtenderImplementation.class).allItems()) {
        StartupExtender extender = new StartupExtender(item.getDisplayName(),
                                   item.getInstance().getArguments(context, mode));
        LOG.log(Level.FINE, " {0} => {1}", new Object[] {extender.description, extender.getArguments()});
        res.add(extender);
    }
    return res;
}
 
Example 19
Source File: Lookups.java    From netbeans with Apache License 2.0 2 votes vote down vote up
/** Creates <code>Lookup.Item</code> representing the instance passed in.
 *
 * @param instance the object for which Lookup.Item should be creted
 * @param id unique identification of the object, for details see {@link org.openide.util.Lookup.Item#getId},
 * can be <code>null</code>
 * @return lookup item representing instance
 * @since 4.8
 */
public static <T> Lookup.Item<T> lookupItem(T instance, String id) {
    return new LookupItem<T>(instance, id);
}
 
Example 20
Source File: WaitableResult.java    From netbeans with Apache License 2.0 votes vote down vote up
protected abstract Collection<? extends Lookup.Item<T>> allItems(boolean callBeforeLookup);