Java Code Examples for org.openide.util.Lookup#lookupAll()

The following examples show how to use org.openide.util.Lookup#lookupAll() . 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: CompositeFCSTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testColoringsForMimeType() throws Exception {
    final String mimeType = "text/x-orig";
    
    Lookup lookup = MimeLookup.getLookup(MimePath.parse(mimeType));
    
    // Check the API class
    Collection<? extends FontColorSettings> c = lookup.lookupAll(FontColorSettings.class);
    assertEquals("Wrong number of fcs", 1, c.size());
    
    FontColorSettings fcs = c.iterator().next();
    assertNotNull("FCS should not be null", fcs);
    assertTrue("Wrong fcs impl", fcs instanceof CompositeFCS);
    
    CompositeFCS compositeFcs = (CompositeFCS) fcs;
    assertEquals("CompositeFCS using wrong profile", EditorSettingsImpl.DEFAULT_PROFILE, compositeFcs.profile);
}
 
Example 2
Source File: DeleteProfilingPointAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup actionContext) {
    if (!ProfilingPointsManager.getDefault().isProfilingSessionInProgress()) {
        Collection<? extends CodeProfilingPoint.Annotation> anns = actionContext.lookupAll(CodeProfilingPoint.Annotation.class);
        if (anns.size() == 1) {
            final CodeProfilingPoint pp = anns.iterator().next().profilingPoint();
            return new AbstractAction(getName()) {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    ProfilingPointsManager.getDefault().removeProfilingPoint(pp);
                }
            };
        }
    }
    return this;
}
 
Example 3
Source File: NamedServiceProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testNamedDefinition() throws Exception {
    System.setProperty("executed", "false");
    String content = "import " + RunTestReg.class.getCanonicalName() + ";\n"
        + "@RunTestReg(position=10,when=\"now\")\n"
        + "public class Test implements Runnable {\n"
        + "  public void run() { System.setProperty(\"executed\", \"true\"); }\n"
        + "}\n";
    AnnotationProcessorTestUtils.makeSource(getWorkDir(), "x.Test", content);
    assertTrue("Compiles OK",
        AnnotationProcessorTestUtils.runJavac(getWorkDir(), null, getWorkDir(), null, System.err)
        );
    
    URLClassLoader l = new URLClassLoader(new URL[] { getWorkDir().toURI().toURL() }, NamedServiceProcessorTest.class.getClassLoader());
    Lookup lkp = Lookups.metaInfServices(l, "META-INF/namedservices/runtest/now/below/");
    for (Runnable r : lkp.lookupAll(Runnable.class)) {
        r.run();
    }
    assertEquals("Our runnable was executed", "true", System.getProperty("executed"));
}
 
Example 4
Source File: CustomizeProfilingPointAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup actionContext) {
    if (!ProfilingPointsManager.getDefault().isProfilingSessionInProgress()) {
        Collection<? extends CodeProfilingPoint.Annotation> anns = actionContext.lookupAll(CodeProfilingPoint.Annotation.class);
        if (anns.size() == 1) {
            final CodeProfilingPoint pp = anns.iterator().next().profilingPoint();
            return new AbstractAction(getName()) {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    pp.customize(false, true);
                }
            };
        }
    }
    return this;
}
 
Example 5
Source File: CPActionsImplementationProvider.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean canRefactor(Lookup lookup) {
    Collection<? extends Node> nodes = lookup.lookupAll(Node.class);
    if (nodes.size() != 1) {
        return false;
    }
    Node node = nodes.iterator().next();

    //can refactor only in less/sass files
    FileObject file = getFileObjectFromNode(node);
    if (file != null) {
        String mimeType = file.getMIMEType();
        if (LessLanguage.getLanguageInstance().mimeType().equals(mimeType) || ScssLanguage.getLanguageInstance().mimeType().equals(mimeType)) {
            return isRefactorableEditorElement(node);
        }
    }
    return false;
}
 
Example 6
Source File: SystemOpenAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ContextAction(Lookup context) {
    super(NbBundle.getMessage(SystemOpenAction.class, "CTL_SystemOpenAction"));
    putValue(DynamicMenuContent.HIDE_WHEN_DISABLED, true);
    files = new HashSet<>();
    for (DataObject d : context.lookupAll(DataObject.class)) {
        File f = FileUtil.toFile(d.getPrimaryFile());
        if (f == null || /* #144575 */Utilities.isWindows() && f.isFile() && !f.getName().contains(".")) {
            files.clear();
            break;
        }
        files.add(f);
    }
}
 
Example 7
Source File: FileHandlingFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public RefactoringPlugin createInstance(AbstractRefactoring refactoring) {
    Lookup look = refactoring.getRefactoringSource();
    Collection<? extends FileObject> o = look.lookupAll(FileObject.class);
    NonRecursiveFolder folder = look.lookup(NonRecursiveFolder.class);
    if (refactoring instanceof RenameRefactoring) {
        if (!o.isEmpty()) {
            return new FileRenamePlugin((RenameRefactoring) refactoring);
        }
    } else if (refactoring instanceof MoveRefactoring) {
        if (!o.isEmpty()) {
            return new FileMovePlugin((MoveRefactoring) refactoring);
        }
    } else if (refactoring instanceof SafeDeleteRefactoring) {
        if (folder != null) {
            //Safe delete package
            return new PackageDeleteRefactoringPlugin((SafeDeleteRefactoring)refactoring);
        }
        if (! o.isEmpty()) {
            FileObject fObj = o.iterator().next();
            if (fObj.isFolder()) {
                return new PackageDeleteRefactoringPlugin((SafeDeleteRefactoring)refactoring);
            } else {
                return new FileDeletePlugin((SafeDeleteRefactoring) refactoring);
            }
        }
    } else if (refactoring instanceof SingleCopyRefactoring || refactoring instanceof CopyRefactoring) {
        if (!o.isEmpty()) {
            return new FilesCopyPlugin(refactoring);
        }
    }
    return null;
}
 
Example 8
Source File: EnableDisableProfilingPointAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Action createContextAwareInstance(Lookup actionContext) {
    if (!ProfilingPointsManager.getDefault().isProfilingSessionInProgress()) {
        Collection<? extends CodeProfilingPoint.Annotation> anns = actionContext.lookupAll(CodeProfilingPoint.Annotation.class);
        if (anns.size() == 1) {
            CodeProfilingPoint pp = anns.iterator().next().profilingPoint();
            
            action.setProfilingPoint(pp);
            action.setBooleanState(pp.isEnabled());
            return action;
        }
    }
    return this;
}
 
Example 9
Source File: FolderPathLookupTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddingFolders() throws Exception {
    // Create lookup over a non-existing folder
    Lookup lookup = new FolderPathLookup(new String [] { "Tmp/A/B/C/D" });
    Collection instances = lookup.lookupAll(Class2LayerFolder.class);

    assertEquals("Wrong number of instances", 0, instances.size());

    // Create the folder and the instance
    TestUtilities.createFile(getWorkDir(), "Tmp/A/B/C/D/org-netbeans-modules-editor-mimelookup-impl-DummySettingImpl.instance");

    instances = lookup.lookupAll(DummySetting.class);
    assertEquals("Wrong number of instances", 1, instances.size());
    assertEquals("Wrong instance", DummySettingImpl.class, instances.iterator().next().getClass());
}
 
Example 10
Source File: JaxWsClientNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void addFromLayers(ArrayList<Action> actions, String path) {
    Lookup look = Lookups.forPath(path);
    for (Object next : look.lookupAll(Object.class)) {
        if (next instanceof Action) {
            actions.add((Action) next);
        } else if (next instanceof javax.swing.JSeparator) {
            actions.add(null);
        }
    }
}
 
Example 11
Source File: LazyLookupProvidersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testMultiplyImplementedService() throws Exception {
    TrackingLoader l = new TrackingLoader();
    MockLookup.setInstances(l);
    l.assertLoadedClasses();
    Lookup all = LookupProviderSupport.createCompositeLookup(Lookup.EMPTY, "Projects/y/Lookup");
    l.assertLoadedClasses();
    Collection<?> instances = all.lookupAll(l.loadClass(Service3.class.getName()));
    assertEquals(1, instances.size());
    l.assertLoadedClasses("Service3", "Service34Impl", "Service4");
    assertEquals(instances, all.lookupAll(l.loadClass(Service4.class.getName())));
    l.assertLoadedClasses("Service3", "Service34Impl", "Service4");
}
 
Example 12
Source File: NbMavenProjectImplTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public @Override I merge(final Lookup lookup) {
    return new I() {
        public @Override String m() {
            Set<String> results = new TreeSet<String>();
            for (I i : lookup.lookupAll(I.class)) {
                results.add(i.m());
            }
            return results.toString();
        }
    };
}
 
Example 13
Source File: DefaultReplaceTokenProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static FileObject[] extractFileObjectsfromLookup(Lookup lookup) {
    List<FileObject> files = new ArrayList<FileObject>(lookup.lookupAll(FileObject.class));
    if (files.isEmpty()) { // fallback to old nodes
        for (DataObject d : lookup.lookupAll(DataObject.class)) {
            files.add(d.getPrimaryFile());
        }
    }
    Collection<? extends SingleMethod> methods = lookup.lookupAll(SingleMethod.class);
    if (methods.size() == 1) {
        SingleMethod method = methods.iterator().next();
        files.add(method.getFile());
    }

    return files.toArray(new FileObject[files.size()]);
}
 
Example 14
Source File: ProjectActionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean isActionEnabled( String command, Lookup context) throws IllegalArgumentException {
    
    if ( COMMAND.equals( command ) ) {
        for (DataObject dobj : context.lookupAll(DataObject.class)) {
            if ( !dobj.getPrimaryFile().getNameExt().endsWith( ".java" ) ) {
                return false;
            }                    
        }
        return true;
    }            
    else {
        throw new IllegalArgumentException();
    }
    
}
 
Example 15
Source File: RunSeleniumAction.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@CheckForNull
private FileObject[] lookupSeleniumTestOnly(Lookup context) {
    Collection<? extends FileObject> fileObjects = context.lookupAll(FileObject.class);
    if (fileObjects.isEmpty()) {
        return null;
    }
    Project p = null;
    Iterator<? extends FileObject> iterator = fileObjects.iterator();
    while (iterator.hasNext()) {
        FileObject fo = iterator.next();
        Project project = FileOwnerQuery.getOwner(fo);
        if (project == null) {
            return null;
        }
        if(p == null) {
            p = project;
        }
        if(!p.equals(project)) { // selected FileObjects belong to different projects
            return null;
        }
        Sources sources = ProjectUtils.getSources(project);
        SourceGroup[] sourceGroups = sources.getSourceGroups(WebClientProjectConstants.SOURCES_TYPE_HTML5_TEST_SELENIUM);
        if (sourceGroups.length != 1) { // no Selenium Tests Folder set yet
            return null;
        }
        FileObject rootFolder = sourceGroups[0].getRootFolder();
        if (!FileUtil.isParentOf(rootFolder, fo)) { // file in not under Selenium Tests Folder
            return null;
        }
    }
    return fileObjects.toArray(new FileObject[fileObjects.size()]);
}
 
Example 16
Source File: WebActionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static FileObject[] findSelectedFilesByMimeType(Lookup context, FileObject dir, String mimeType, String suffix, boolean strict) {
    if (dir != null && !dir.isFolder()) {
        throw new IllegalArgumentException("Not a folder: " + dir); // NOI18N
    }

    List<FileObject> files = new ArrayList<FileObject>();
    for (DataObject d : context.lookupAll(DataObject.class)) {
        FileObject f = d.getPrimaryFile();
        boolean matches = FileUtil.toFile(f) != null;
        if (dir != null) {
            matches &= (FileUtil.isParentOf(dir, f) || dir == f);
        }
        if (mimeType != null) {
            matches &= f.getMIMEType().equals(mimeType);
        }
        if (suffix != null) {
            matches &= !f.getNameExt().endsWith(suffix);
        }
        // Generally only files from one project will make sense.
        // Currently the action UI infrastructure (PlaceHolderAction)
        // checks for that itself. Should there be another check here?
        if (matches) {
            files.add(f);
        } else if (strict) {
            return null;
        }
    }
    if (files.isEmpty()) {
        return null;
    }
    return files.toArray(new FileObject[files.size()]);
}
 
Example 17
Source File: RefactoringActionsProvider.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private FileObject getFileObject(Lookup lookup) {
    Collection<? extends Node> nodes = lookup.lookupAll(Node.class);
    Node n = (nodes.size() == 1) ? nodes.iterator().next() : null;
    DataObject dob = (n != null) ? n.getLookup().lookup(DataObject.class) : null;
    return (dob != null) ? dob.getPrimaryFile() : null;
}
 
Example 18
Source File: ActionProviderImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void invokeAction(String command, Lookup context) throws IllegalArgumentException {
    if (COMMAND_PROFILE_TEST_SINGLE.equals(command)) {
        for (ActionProvider ap : Lookup.getDefault().lookupAll(ActionProvider.class)) {
            if (new HashSet<>(Arrays.asList(ap.getSupportedActions())).contains(COMMAND_PROFILE_TEST_SINGLE) && ap.isActionEnabled(COMMAND_PROFILE_TEST_SINGLE, context)) {
                ap.invokeAction(COMMAND_PROFILE_TEST_SINGLE, context);
                return ;
            }
        }
    }
    FileObject scriptFO = script;
    Settings settings = project.getLookup().lookup(Settings.class);
    Properties props = new Properties();
    if (settings.isUseAntBuild()) {
        props.put("langtools.build.location", settings.getAntBuildLocation());
    } else {
        scriptFO = genericScript;
        if (COMMAND_BUILD_FAST.equals(command)) {
            command = COMMAND_BUILD_GENERIC_FAST;
        }
    }
    if (COMMAND_BUILD_GENERIC_FAST.equals(command)) {
        switch (settings.getRunBuildSetting()) {
            case NEVER:
                ActionProgress.start(context).finished(true);
                return;
            case ALWAYS:
            default:
                break;
        }
        scriptFO = genericScript;
        command = COMMAND_BUILD_FAST; //XXX: should only do this if genericScript supports it
    }
    FileObject basedirFO = project.currentModule != null ? scriptFO == genericScript ? project.moduleRepository.getJDKRoot()
                                                                                     : repository
                                                         : repository.getParent();
    props.put("basedir", FileUtil.toFile(basedirFO).getAbsolutePath());
    props.put("CONF", project.configurations.getActiveConfiguration().getLocation().getName());
    props.put("nb.jdk.project.target.java.home", BuildUtils.findTargetJavaHome(project.getProjectDirectory()).getAbsolutePath());
    RootKind kind = getKind(context);
    RunSingleConfig singleFileProperty = command2Properties.get(Pair.of(command, kind));
    if (singleFileProperty != null) {
        String srcdir = "";
        String moduleName = "";
        StringBuilder value = new StringBuilder();
        String sep = "";
        for (FileObject file : context.lookupAll(FileObject.class)) {
            value.append(sep);
            ClassPath sourceCP;
            switch (kind) {
                case SOURCE:
                    sourceCP = ClassPath.getClassPath(file, ClassPath.SOURCE);
                    break;
                case TEST:
                    sourceCP = ClassPathSupport.createClassPath(BuildUtils.getFileObject(project.getProjectDirectory(), "../../test"));
                    break;
                default:
                    throw new IllegalStateException(kind.name());
            }
            value.append(singleFileProperty.valueType.convert(sourceCP, file));
            sep = singleFileProperty.separator;
            FileObject ownerRoot = sourceCP.findOwnerRoot(file);
            srcdir = FileUtil.getRelativePath(BuildUtils.getFileObject(project.getProjectDirectory(), "../.."), ownerRoot);
            moduleName = ownerRoot.getParent().getParent().getNameExt();
        }
        props.put(singleFileProperty.propertyName, value.toString());
        props.put("srcdir", srcdir);
        props.put("module.name", moduleName);
    }
    final ActionProgress progress = ActionProgress.start(context);
    try {
        ActionUtils.runTarget(scriptFO, command2Targets.get(Pair.of(command, kind)), props)
                   .addTaskListener(new TaskListener() {
            @Override
            public void taskFinished(Task task) {
                progress.finished(((ExecutorTask) task).result() == 0);
            }
        });
    } catch (IOException ex) {
        //???
        Exceptions.printStackTrace(ex);
        progress.finished(false);
    }
}
 
Example 19
Source File: ActionUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Convenience method to find a file selection in a selection (context).
 * All files must exist on disk (according to {@link FileUtil#toFile}).
 * If a constraining directory is supplied, they must also be contained in it.
 * If a constraining file suffix is supplied, the base names of the files
 * must end with that suffix.
 * The return value is null if there are no matching files; or if the strict
 * parameter is true and some of the files in the selection did not match
 * the constraints (disk files, directory, and/or suffix).
 * <p class="nonnormative">
 * Typically {@link org.openide.loaders.DataNode}s will form a node selection
 * which will be placed in the context. This method does <em>not</em> directly
 * look for nodes in the selection; but generally the lookups of the nodes in
 * a node selection are spliced into the context as well, so the {@link FileObject}s
 * should be available. A corollary of not checking nodes directly is that any
 * nodes in the context which do not correspond to files at all (i.e. do not have
 * {@link FileObject} in their lookup) are ignored, even with the strict parameter on;
 * and that multiple nodes in the context with the same associated file are treated
 * as a single entry.
 * </p>
 * @param context a selection as provided to e.g. <code>ActionProvider.isActionEnabled(...)</code>
 * @param dir a constraining parent directory, or null to not check for a parent directory
 * @param suffix a file suffix (e.g. <samp>.java</samp>) to constrain files by,
 *               or null to not check suffixes
 * @param strict if true, all files in the selection have to be accepted
 * @return a nonempty selection of disk files, or null
 * @see <a href="@org-netbeans-modules-projectapi@/org/netbeans/spi/project/ActionProvider.html#isActionEnabled(java.lang.String,%20org.openide.util.Lookup)"><code>ActionProvider.isActionEnabled(...)</code></a>
 */
public static FileObject[] findSelectedFiles(Lookup context, FileObject dir, String suffix, boolean strict) {
    if (dir != null && !dir.isFolder()) {
        throw new IllegalArgumentException("Not a folder: " + dir); // NOI18N
    }
    if (suffix != null && suffix.indexOf('/') != -1) {
        throw new IllegalArgumentException("Cannot includes slashes in suffix: " + suffix); // NOI18N
    }
    Collection<? extends FileObject> candidates = context.lookupAll(FileObject.class);
    if (candidates.isEmpty()) { // should not be for DataNode selections, but for compatibility
        Collection<? extends DataObject> compatibilityCandidates = context.lookupAll(DataObject.class);
        if (compatibilityCandidates.isEmpty()) {
            return null; // shortcut - just not a file selection at all
        }
        List<FileObject> _candidates = new ArrayList<FileObject>();
        for (DataObject d : compatibilityCandidates) {
            _candidates.add(d.getPrimaryFile());
        }
        candidates = _candidates;
    }
    Collection<FileObject> files = new LinkedHashSet<FileObject>(); // #50644: remove dupes
    for (FileObject f : candidates) {
        if (f.hasExt("form")) {
            continue; // #206309
        }
        boolean matches = FileUtil.toFile(f) != null;
        if (dir != null) {
            matches &= (FileUtil.isParentOf(dir, f) || dir == f);
        }
        if (suffix != null) {
            matches &= f.getNameExt().endsWith(suffix);
        }
        // Generally only files from one project will make sense.
        // Currently the action UI infrastructure (PlaceHolderAction)
        // checks for that itself. Should there be another check here?
        if (matches) {
            files.add(f);
        } else if (strict) {
            return null;
        }
    }
    if (files.isEmpty()) {
        return null;
    }
    return files.toArray(new FileObject[files.size()]);
}
 
Example 20
Source File: SimpleProxyLookupSpeedIssue42244Test.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testCompareTheSpeed () {
    String content1 = "String1";
    String content2 = "String2";
    
    Lookup fixed1 = Lookups.singleton(content1);
    Lookup fixed2 = Lookups.singleton(content2);
    
    MyProvider provider = new MyProvider();
    provider.setLookup(fixed1);
    
    Lookup top = Lookups.proxy(provider);

    Lookup.Result<String> r0 = top.lookupResult(String.class);
    r0.allInstances();

    long time = System.currentTimeMillis();
    top.lookupAll(String.class);
    long withOneResult = System.currentTimeMillis() - time;

 
    Set<Object> results = new HashSet<Object>();
    for (int i=0; i<10000; i++) {
        Lookup.Result<String> res = top.lookupResult(String.class);
        results.add (res);
        res.allInstances();
    }
    
    provider.setLookup(fixed2);

    time = System.currentTimeMillis();
    top.lookupAll(String.class);
    long withManyResults = System.currentTimeMillis() - time;
    
    // if the measurement takes less then 10ms, pretend 10ms
    if (withManyResults < 10) {
        withManyResults = 10;
    }
    if (withOneResult < 10) {
        withOneResult = 10;
    }

    if (withManyResults >= 10 * withOneResult) {
        fail ("With many results the test runs too long.\n With many: " + withManyResults + "\n With one : " + withOneResult);
    }
}