Java 类org.openide.util.Pair 实例源码

项目:incubator-netbeans    文件:CssPreprocessorUtilsTest.java   
@Test
public void testInvalidMappingsFormat() {
    File root = new File("/root");
    Pair<String, String> mapping1 = Pair.of("/sc" + CssPreprocessorUtils.MAPPING_DELIMITER + "ss", "/css");
    Pair<String, String> mapping2 = Pair.of("/scss", "   ");
    Pair<String, String> mapping3 = Pair.of("/scss", "/my.css");
    List<Pair<String, String>> mappings = Arrays.asList(mapping1, mapping2, mapping3);
    ValidationResult validationResult = new CssPreprocessorUtils.MappingsValidator("scss")
            .validate(root, mappings)
            .getResult();
    assertEquals(0, validationResult.getWarnings().size());
    assertEquals(3, validationResult.getErrors().size());
    ValidationResult.Message error1 = validationResult.getErrors().get(0);
    assertEquals("mapping." + mapping1.first(), error1.getSource());
    assertTrue(error1.getMessage(), error1.getMessage().contains(mapping1.first()));
    ValidationResult.Message error2 = validationResult.getErrors().get(1);
    assertEquals("mapping." + mapping2.second(), error2.getSource());
    assertEquals(Bundle.MappingsValidator_warning_output_empty(), error2.getMessage());
    ValidationResult.Message error3 = validationResult.getErrors().get(2);
    assertEquals("mapping.io." + mapping3.second(), error3.getSource());
    assertEquals(Bundle.MappingsValidator_warning_io_conflict(mapping3.first(), mapping3.second()), error3.getMessage());
}
项目:incubator-netbeans    文件:TaskProcessor.java   
private static @NonNull Collection<? extends Request> toRequests (
        final @NonNull Collection<Pair<SchedulerTask,Class<? extends Scheduler>>> tasks,
        final @NonNull SourceCache cache,
        final boolean bridge) {
    Parameters.notNull("task", tasks);   //NOI18N
    Parameters.notNull("cache", cache);   //NOI18N
    List<Request> _requests = new ArrayList<Request> ();
    for (Pair<SchedulerTask,Class<? extends Scheduler>> task : tasks) {
        final String taskClassName = task.first().getClass().getName();
        if (excludedTasks != null && excludedTasks.matcher(taskClassName).matches()) {
            if (includedTasks == null || !includedTasks.matcher(taskClassName).matches())
                continue;
        }
        _requests.add (new Request (task.first(), cache, bridge ? ReschedulePolicy.ON_CHANGE : ReschedulePolicy.CANCELED, task.second()));
    }
    return _requests;
}
项目:incubator-netbeans    文件:DefaultCssModuleTest.java   
public void testGetDeclarationForURIUnquoted() {
    BaseDocument document = getDocument("div { background: url(hello.png); } ");
    //                                   01234567890123456789012345678901234567890123456789
    //                                   0         1         2         3
    DefaultCssEditorModule dm = new DefaultCssEditorModule();
    Pair<OffsetRange, FutureParamTask<DeclarationFinder.DeclarationLocation, EditorFeatureContext>> declaration = dm.getDeclaration(document, 25);
    assertNotNull(declaration);
    OffsetRange range = declaration.first();
    assertNotNull(range);
    assertEquals(22, range.getStart());
    assertEquals(31, range.getEnd());

    FutureParamTask<DeclarationFinder.DeclarationLocation, EditorFeatureContext> task = declaration.second();
    assertNotNull(task);

}
项目:incubator-netbeans    文件:MultiModuleNodeFactory.java   
private void updateFileStatusListeners() {
    final Collection<FileSystem> fileSystems = new HashSet<>();
    for (FileObject fo : getFileObjects()) {
        try {
            fileSystems.add(fo.getFileSystem());
        } catch (FileStateInvalidException e) {
            LOG.log(
                    Level.WARNING,
                    "Ignoring invalid file: {0}",   //NOI18N
                    FileUtil.getFileDisplayName(fo));
        }
    }
    synchronized (this) {
        for (Pair<FileSystem,FileStatusListener> p : fsListensOn) {
            p.first().removeFileStatusListener(p.second());
        }
        final List<Pair<FileSystem,FileStatusListener>> newFsListensOn = new ArrayList<>();
        for (FileSystem fs : fileSystems) {
            FileStatusListener l = FileUtil.weakFileStatusListener(this, fs);
            fs.addFileStatusListener(l);
            newFsListensOn.add(Pair.of(fs,l));
        }
        fsListensOn = newFsListensOn;
    }
}
项目:incubator-netbeans    文件:AnnotationHolder.java   
private Pair<FixData, String> buildUpFixDataForLine(Position line) {
    List<ErrorDescription> errorDescriptions = getErrorsForLine(line, true);
    if (errorDescriptions.isEmpty()) {
        return null;
    }

    List<ErrorDescription> trueErrors = filter(errorDescriptions, true);
    List<ErrorDescription> others = filter(errorDescriptions, false);

    //build up the description of the annotation:
    StringBuffer description = new StringBuffer();

    concatDescription(trueErrors, description);

    if (!trueErrors.isEmpty() && !others.isEmpty()) {
        description.append("\n\n"); //NOI18N
    }

    concatDescription(others, description);

    return Pair.of(new FixData(computeFixes(trueErrors), computeFixes(others)), description.toString());
}
项目:incubator-netbeans    文件:ClusteredIndexablesCacheTest.java   
@Override
public void publish(LogRecord record) {
    final Convertor<Pair<URL,String>,Boolean> action = beforeScanFinishedAction;
    final String message = record.getMessage();
    if (action != null && "scanFinishing:{0}:{1}".equals(message)) {    //NOI18N
        try {
            Boolean tmpRes = action.convert(
                Pair.<URL,String>of(
                    new URL ((String)record.getParameters()[1]),
                    (String)record.getParameters()[0]));
            if (tmpRes != null) {
                res = tmpRes;
            }
        } catch (MalformedURLException ex) {
            Exceptions.printStackTrace(ex);
        }
    }
    super.publish(record);
}
项目:incubator-netbeans    文件:LogContext.java   
void checkAndReport(long now, int minutes, int treshold) {
    long minTime = now - fromMinutes(historyLimit);
    Pair<Integer, Integer> found = findHigherRate(minTime, minutes, treshold);
    if (found == null) {
        return;
    }
    if (closing || RepositoryUpdater.getDefault().getState() == RepositoryUpdater.State.STOPPED) {
        return;
    }

    LOG.log(Level.WARNING, "Excessive indexing rate detected: " + dataSize(found.first(), found.second()) + " in " + minutes + "mins, treshold is " + treshold +
            ". Dumping suspicious contexts");
    int index;

     for (index = found.first(); index != found.second(); index = (index + 1) % times.length) {
        contexts[index].log(false, false);
    }
    LOG.log(Level.WARNING, "=== End excessive indexing");
    this.reportedEnd = index;
}
项目:incubator-netbeans    文件:J2SEActionProvider.java   
private CosAction(
        @NonNull final J2SEActionProvider owner,
        @NonNull final PropertyEvaluator eval,
        @NonNull final SourceRoots src,
        @NonNull final SourceRoots tests) {
    this.owner = owner;
    this.eval = eval;
    this.src = src;
    this.tests = tests;
    this.mapper = new BuildArtifactMapper();
    this.currentListeners = new HashMap<>();
    this.cs = new ChangeSupport(this);
    this.importantFilesCache = new AtomicReference<>(Pair.of(null,null));
    this.eval.addPropertyChangeListener(WeakListeners.propertyChange(this, this.eval));
    this.src.addPropertyChangeListener(WeakListeners.propertyChange(this, this.src));
    this.tests.addPropertyChangeListener(WeakListeners.propertyChange(this, this.tests));
    updateRootsListeners();
    instances.put(owner.getProject(), new WeakReference<>(this));
}
项目:incubator-netbeans    文件:PinWatchValueProvider.java   
@Override
public Action[] getTailActions(Watch watch) {
    Pair<ObjectVariable, ValueListeners> varVl = getObjectVariable(watch);
    if (varVl == null) {
        return null;
    }
    ObjectVariable var = varVl.first();
    if (!ValuePropertyEditor.hasPropertyEditorFor(var)) {
        return null;
    }
    final Object mirror = var.createMirrorObject();
    if (mirror == null) {
        return null;
    }
    ValuePropertyEditor ped = new ValuePropertyEditor(lookupProvider);
    ped.setValueWithMirror(var, mirror);
    return new Action[] { null, getPropertyEditorAction(ped, var, varVl.second(), watch.getExpression()) };
}
项目:incubator-netbeans    文件:JPDAThreadImpl.java   
private Pair<List<JPDAThread>, List<JPDAThread>> updateLockerThreads(
        Map<ThreadReference, ObjectReference> lockedThreadsWithMonitors,
        ObjectReference waitingMonitor) throws InternalExceptionWrapper,
                                               VMDisconnectedExceptionWrapper,
                                               ObjectCollectedExceptionWrapper,
                                               IllegalThreadStateExceptionWrapper {
    List<JPDAThread> oldLockerThreadsList;
    List<JPDAThread> newLockerThreadsList;
    synchronized (lockerThreadsLock) {
        oldLockerThreadsList = lockerThreadsList;
        if (lockedThreadsWithMonitors != null) {
            //lockerThreads2 = lockedThreadsWithMonitors;
            lockerThreadsMonitor = waitingMonitor;
            if (!submitMonitorEnteredFor(waitingMonitor)) {
                submitCheckForMonitorEntered(waitingMonitor);
            }
            lockerThreadsList = new ThreadListDelegate(debugger, new ArrayList(lockedThreadsWithMonitors.keySet()));
        } else {
            //lockerThreads2 = null;
            lockerThreadsMonitor = null;
            lockerThreadsList = null;
        }
        newLockerThreadsList = lockerThreadsList;
    }
    return Pair.of(oldLockerThreadsList, newLockerThreadsList);
}
项目:incubator-netbeans    文件:DocumentUtil.java   
private static Query binaryNameSourceNamePairQuery (final Pair<String,String> binaryNameSourceNamePair) {
    assert binaryNameSourceNamePair != null;
    final String binaryName = binaryNameSourceNamePair.first();
    final String sourceName = binaryNameSourceNamePair.second();
    assert binaryName != null || sourceName != null;
    Query query = null;
    if (binaryName != null) {
        query = binaryNameQuery(binaryName);
    }
    if (sourceName != null) {
        if (query == null) {
           query = new TermQuery(new Term (FIELD_SOURCE,sourceName));
        } else {
            assert query instanceof BooleanQuery : "The DocumentUtil.binaryNameQuery was incompatibly changed!";        //NOI18N
            final BooleanQuery bq = (BooleanQuery) query;
            bq.add(new TermQuery(new Term (FIELD_SOURCE,sourceName)), BooleanClause.Occur.MUST);
        }
    }
    assert query != null;
    return query;
}
项目:incubator-netbeans    文件:HierarchyTopComponent.java   
private void schedule(@NonNull final Callable<Pair<URI,ElementHandle<TypeElement>>> resolver) {
    showBusy();
    assert resolver != null;
    final RunnableFuture<Pair<URI,ElementHandle<TypeElement>>> becomesType = new FutureTask<Pair<URI,ElementHandle<TypeElement>>>(resolver);
    jdocTask.cancel();
    jdocFinder.cancel();
    RP.execute(becomesType);
    Object selItem = viewTypeCombo.getSelectedItem();
    if (!(selItem instanceof ViewType)) {
        selItem = ViewType.SUPER_TYPE;
    }
    final Runnable refreshTask = new RefreshTask(becomesType,(ViewType)selItem);
    jdocTask.cancel();
    jdocFinder.cancel();
    RP.execute(refreshTask);
}
项目:incubator-netbeans    文件:Utilities.java   
public static ClassPath getSourceClassPathFor(FileObject file) {
    Pair<FileObject,Reference<ClassPath>> ce = rootCache;
    ClassPath cp;
    if (ce != null &&
        (cp = ce.second().get()) != null &&
        ce.first().equals(cp.findOwnerRoot(file))) {
        return cp;
    }
    for (String sourceCP : PathRecognizerRegistry.getDefault().getSourceIds()) {
        cp = ClassPath.getClassPath(file, sourceCP);
        if (cp != null) {
            final FileObject root = cp.findOwnerRoot(file);
            if (root != null) {
                rootCache = Pair.<FileObject,Reference<ClassPath>>of(
                    root,
                    new WeakReference<ClassPath>(cp));
            }
            return cp;
        }
    }
    return null;
}
项目:incubator-netbeans    文件:ActionsUtil.java   
/**
 * split getProjectsFromLookup( Lookup lookup, String command ) into 2 calls
 * to allow FOQ.getOwner to be called outside of AWT
 * @return 
 */
@NonNull
public static Project[] getProjects( Pair<List<Project>, List<FileObject>> data ) {    
    // First find out whether there is a project directly in the Lookup
    Set<Project> result = new LinkedHashSet<Project>(); // XXX or use OpenProjectList.projectByDisplayName?
    result.addAll(data.first());
    // Now try to guess the project from dataobjects
    for (FileObject fObj : data.second()) {
        Project p = FileOwnerQuery.getOwner(fObj);
        if ( p != null ) {
            result.add( p );
        }
    }
    Project[] projectsArray = result.toArray(new Project[result.size()]);
    return projectsArray;
}
项目:incubator-netbeans    文件:CachingArchiveClassLoader.java   
public static ClassLoader forURLs(
        @NonNull final URL[] urls,
        @NullAllowed final ClassLoader parent,
        @NullAllowed final Consumer<? super URL> usedRoots) {
    Parameters.notNull("urls", urls);       //NOI18N
    final List<Pair<URL,Archive>> archives = new ArrayList<>(urls.length);
    for (URL url : urls) {
        final Archive arch = CachingArchiveProvider.getDefault().getArchive(url, false);
        if (arch != null) {
            archives.add(Pair.of(url,arch));
        }
    }
    return new CachingArchiveClassLoader(
            archives,
            parent,
            usedRoots);
}
项目:incubator-netbeans    文件:SourceAnalyzerFactory.java   
@Override
@CheckForNull
public Void visitMethod(@NonNull final MethodTree node, @NonNull final Map<Pair<BinaryName,String>, UsagesData<String>> p) {
    Element old = enclosingElement;
    try {
        enclosingElement = ((JCTree.JCMethodDecl) node).sym;
        if (enclosingElement != null && enclosingElement.getKind() == ElementKind.METHOD) {
            mainMethod |= SourceUtils.isMainMethod((ExecutableElement) enclosingElement);
            // do not add idents for constructors, they always match their class' name, which is added as an ident separately
            addIdent(activeClass.peek(), node.getName(), p, true);
        }
        return super.visitMethod(node, p);
    } finally {
        enclosingElement = old;
    }
}
项目:incubator-netbeans    文件:ScanStartedTest.java   
public void testScanFinishedAfterScanStartedWithInternalException() throws Exception {
    assertTrue(GlobalPathRegistry.getDefault().getPaths(FOO_SOURCES).isEmpty());

    handler.internalException = Pair.<String,RuntimeException>of(
            factory2.getIndexerName(),
            new RuntimeException());    //Symulate internal exception

    //Testing classpath registration
    globalPathRegistry_register(FOO_SOURCES,new ClassPath[]{cp1});
    assertFalse(handler.await(RepositoryUpdaterTest.NEGATIVE_TIME));
    assertEquals(0, handler.getBinaries().size());
    assertNull(handler.getSources());
    assertEquals(1, factory1.scanStartedCount.get());
    assertEquals(0, factory2.scanStartedCount.get());
    assertEquals(0, factory3.scanStartedCount.get());
    assertEquals(1, factory1.scanFinishedCount.get());
    assertEquals(0, factory2.scanFinishedCount.get());
    assertEquals(0, factory3.scanFinishedCount.get());
}
项目:incubator-netbeans    文件:CachingFileManagerTest.java   
public void testGetFileForInputWithCachingArchive() throws  Exception {
    final File wd = getWorkDir();
    final File archiveFile = new File (wd, "src.zip");
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(archiveFile));
    try {
        out.putNextEntry(new ZipEntry("org/me/resources/test.txt"));
        out.write("test".getBytes());
    } finally {
        out.close();
    }
    final URL archiveRoot = FileUtil.getArchiveRoot(Utilities.toURI(archiveFile).toURL());
    final URI expectedURI = new URL (archiveRoot.toExternalForm()+"org/me/resources/test.txt").toURI();
    doTestGetFileForInput(ClassPathSupport.createClassPath(archiveRoot),
    Arrays.asList(
        Pair.<Pair<String,String>,URI>of(Pair.<String,String>of("","org/me/resources/test.txt"), expectedURI),
        Pair.<Pair<String,String>,URI>of(Pair.<String,String>of("org.me","resources/test.txt"), expectedURI),
        Pair.<Pair<String,String>,URI>of(Pair.<String,String>of("org.me","resources/doesnotexist.txt"), null)
    ));

}
项目:incubator-netbeans    文件:RepositoryUpdater.java   
Pair<URL, FileObject> getOwningBinaryRoot(final FileObject fo) {
    if (fo == null) {
        return null;
    }
    final String foPath = fo.toURL().getPath();
    List<URL> clone = new ArrayList<>(this.scannedBinaries2InvDependencies.keySet());
    for (URL root : clone) {
        URL fileURL = FileUtil.getArchiveFile(root);
        boolean archive = true;
        if (fileURL == null) {
            fileURL = root;
            archive = false;
        }
        String filePath = fileURL.getPath();
        if (filePath.equals(foPath)) {
            return Pair.of(root, null);
        }
        if (!archive && foPath.startsWith(filePath)) {
            return Pair.of(root, null);
        }
    }

    return null;
}
项目:incubator-netbeans    文件:CompilerOptionsQueryMerger.java   
private void checkProviders() {
    synchronized (this) {
        if (currentResults != null) {
            for (Pair<Result,ChangeListener> res : currentResults) {
                res.first().removeChangeListener(res.second());
            }
            currentResults = null;
        }
    }
    final List<Pair<Result,ChangeListener>> newResults = providers.allInstances().stream()
            .map((p) -> p.getOptions(artifact))
            .filter((r) -> r != null)
            .map((r) -> {
                final ChangeListener cl = WeakListeners.change(this, r);
                r.addChangeListener(cl);
                return Pair.of(r,cl);
                })
            .collect(Collectors.toList());
    final List<String> newArgs = newResults.stream()
            .flatMap((p) -> p.first().getArguments().stream())
            .collect(Collectors.toList());
    synchronized (this) {
        currentResults = newResults;
        currentArgs = Collections.unmodifiableList(newArgs);
    }
}
项目:incubator-netbeans    文件:FindUsagesFilterTest.java   
@SuppressWarnings("NestedAssignment")
public void testArrayReadWrite() throws Exception {
    String source;
    writeFilesAndWaitForScan(src, new RefactoringTestBase.File("t/A.java", source = "package t;\n"
            + "public class A {\n"
            + "    \n"
            + "    public static void main(String... args) {\n"
            + "        int[] lijst = new int[10];\n"
            + "        lijst[0] = 1;\n"
            + "        int a = lijst[1];\n"
            + "        lijst[2]++;\n"
            + "        ++lijst[3];\n"
            + "        lijst[4] = lijst[5];\n"
            + "        lijst = null;\n"
            + "    }\n"
            + "}\n"));
    performFind(src.getFileObject("t/A.java"), source.indexOf("lijst") + 1, true, false, false,
            Pair.of("lijst[0] = 1;", JavaWhereUsedFilters.ReadWrite.WRITE),
            Pair.of("int a = lijst[1];", JavaWhereUsedFilters.ReadWrite.READ),
            Pair.of("lijst[2]++;", JavaWhereUsedFilters.ReadWrite.READ_WRITE),
            Pair.of("++lijst[3];", JavaWhereUsedFilters.ReadWrite.READ_WRITE),
            Pair.of("lijst[4] = lijst[5];", JavaWhereUsedFilters.ReadWrite.WRITE),
            Pair.of("lijst[4] = lijst[5];", JavaWhereUsedFilters.ReadWrite.READ),
            Pair.of("lijst = null;", JavaWhereUsedFilters.ReadWrite.WRITE));
}
项目:incubator-netbeans    文件:FileObjectCrawlerTest.java   
public void testSymLinksFromRoot() throws Exception {
    final File workDir = getWorkDir();
    final FileObject wd = FileUtil.toFileObject(workDir);
    final FileObject cycleTarget= wd.createFolder("cycleTarget");
    final FileObject rootWithCycle = cycleTarget.createFolder("rootWithExtLink");
    final FileObject folder1 = rootWithCycle.createFolder("folder1");
    final FileObject folder2 = rootWithCycle.createFolder("folder2");
    final FileObject inFolder1 = folder1.createFolder("infolder1");
    final FileObject inFolder2 = folder2.createFolder("cycleTarget");
    folder1.createData("data1.txt");
    inFolder1.createData("data2.txt");
    folder2.createData("data3.txt");
    inFolder2.createData("data4.txt");
    final Map<Pair<FileObject,FileObject>,Boolean> linkMap = new HashMap<>();
    linkMap.put(
        Pair.<FileObject,FileObject>of(cycleTarget, inFolder2), Boolean.TRUE
    );
    FileObjectCrawler.mockLinkTypes = linkMap;
    final FileObjectCrawler c = new FileObjectCrawler(rootWithCycle, EnumSet.<Crawler.TimeStampAction>of(Crawler.TimeStampAction.UPDATE), null, CR, SuspendSupport.NOP);
    final Collection<Indexable> indexables = c.getAllResources();
    assertCollectedFiles("Wring collected files", indexables,
            "folder1/data1.txt",
            "folder1/infolder1/data2.txt",
            "folder2/data3.txt");
}
项目:incubator-netbeans    文件:Models.java   
@Override
public void add(Collection<? extends T> values) {
    for (T value : values) {
        if (value instanceof AsyncDescriptor) {
            ((AsyncDescriptor)value).addDescriptorChangeListener(this);
        }
    }
    boolean success;
    do {
        final Pair<List<T>,List<T>> data = getData();
        data.second().addAll(values);
        if (comparator != null) {
            Collections.sort(data.second(), comparator);
        }
        success = casData(data.first(), data.second());
    } while (!success);
}
项目:incubator-netbeans    文件:ModuleInfoAccessibilityQueryImpl.java   
@NonNull
private static Optional<Pair<Set<FileObject>,Set<FileObject>>> readExports(
        @NonNull final FileObject[] roots,
        @NonNull final Set<? super FileObject> rootsCollector) {
    Collections.addAll(rootsCollector, roots);
    final Optional<FileObject> moduleInfo = Arrays.stream(roots)
            .map((root) -> root.getFileObject(MODULE_INFO_JAVA))
            .filter((mi) -> mi != null)
            .findFirst();
    if (!moduleInfo.isPresent()) {
        return Optional.empty();
    }
    final Set<FileObject> rootsSet = new HashSet<>();
    Collections.addAll(rootsSet, roots);
    final Set<FileObject> exportsSet = readExports(moduleInfo.get(), rootsSet);
    return Optional.of(Pair.of(rootsSet, exportsSet));
}
项目:incubator-netbeans    文件:FileObjectCrawlerTest.java   
public void testSymLinksInRoot() throws Exception {
    final File workDir = getWorkDir();
    final FileObject wd = FileUtil.toFileObject(workDir);
    final FileObject rootWithCycle = wd.createFolder("rootWithCycle");
    final FileObject folder1 = rootWithCycle.createFolder("folder1");
    final FileObject folder2 = rootWithCycle.createFolder("folder2");
    final FileObject inFolder1 = folder1.createFolder("infolder1");
    final FileObject inFolder2 = folder2.createFolder("folder2");
    folder1.createData("data1.txt");
    inFolder1.createData("data2.txt");
    folder2.createData("data3.txt");
    inFolder2.createData("data4.txt");
    final Map<Pair<FileObject,FileObject>,Boolean> linkMap = new HashMap<>();
    linkMap.put(
        Pair.<FileObject,FileObject>of(folder2,inFolder2), Boolean.TRUE
    );
    FileObjectCrawler.mockLinkTypes = linkMap;
    final FileObjectCrawler c = new FileObjectCrawler(rootWithCycle, EnumSet.<Crawler.TimeStampAction>of(Crawler.TimeStampAction.UPDATE), null, CR, SuspendSupport.NOP);
    final Collection<Indexable> indexables = c.getAllResources();
    assertCollectedFiles("Wring collected files", indexables,
            "folder1/data1.txt",
            "folder1/infolder1/data2.txt",
            "folder2/data3.txt");
}
项目:incubator-netbeans    文件:ClassPath.java   
private void listenOnRoots (final List<Pair<ClassPath.Entry,Pair<FileObject,File>>> roots) {
    final Set<File> listenOn = new HashSet<>();
    for (Pair<ClassPath.Entry,Pair<FileObject,File>> p : roots) {
        final ClassPath.Entry entry = p.first();
        final FileObject fo = p.second().first();
        if (fo != null) {
            root2Filter.put(fo, entry.filter);
        }
        final File file = p.second().second();
        if (file != null) {
            listenOn.add(file);
        }
    }
    final RootsListener rL = this.getRootsListener();
    if (rL != null) {
        rL.addRoots (listenOn);
    }
}
项目:incubator-netbeans    文件:CachingArchiveProvider.java   
@NonNull
private Pair<File,String> mapJarToCtSym(
    @NonNull final File file) {
    if (USE_CT_SYM && NAME_RT_JAR.equals(file.getName())) {
        final FileObject fo = FileUtil.toFileObject(file);
        if (fo != null) {
            for (JavaPlatform jp : JavaPlatformManager.getDefault().getInstalledPlatforms()) {
                for (FileObject jdkFolder : jp.getInstallFolders()) {
                    if (FileUtil.isParentOf(jdkFolder, fo)) {
                        final FileObject ctSym = jdkFolder.getFileObject(PATH_CT_SYM);
                        File ctSymFile;
                        if (ctSym != null && (ctSymFile = FileUtil.toFile(ctSym)) != null) {
                            return Pair.<File,String>of(ctSymFile,PATH_RT_JAR_IN_CT_SYM);
                        }
                    }
                }
            }
        }
    }
    return Pair.<File,String>of(file, null);
}
项目:incubator-netbeans    文件:CachingArchiveClassLoader.java   
@Override
protected Enumeration<URL> findResources(final String name) throws IOException {
    try {
        return readAction(new Callable<Enumeration<URL>>(){
            @Override
            public Enumeration<URL> call() throws Exception {
                @SuppressWarnings("UseOfObsoleteCollectionType")
                final Vector<URL> v = new Vector<URL>();
                for (final Pair<URL,Archive> p : archives) {
                    final Archive archive = p.second();
                    final FileObject file = archive.getFile(name);
                    if (file != null) {
                        v.add(file.toUri().toURL());
                        usedRoots
                                .map((c) -> RES_PROCESSORS.equals(name) ? null : c)
                                .ifPresent((c) -> c.accept(p.first()));
                    }
                }
                return v.elements();
            }
        });
    } catch (Exception ex) {
        throw new IOException(ex);
    }
}
项目:incubator-netbeans    文件:LibrariesNode.java   
LibrariesChildren (
        @NonNull final Project project,
        @NonNull final PropertyEvaluator eval,
        @NonNull final UpdateHelper helper,
        @NonNull final ReferenceHelper refHelper,
        @NonNull final List<String> classPathProperties,
        @NonNull final Collection<String> classPathIgnoreRef,
        @NullAllowed final Pair<Pair<String,String>, ClassPath> boot,
        @NullAllowed final Pair<Set<String>,ClassPath> modulePath,
        @NonNull final Collection<String> modulePathIgnoreRef,
        @NullAllowed final String webModuleElementName,
        @NonNull final ClassPathSupport cs,
        @NullAllowed final Callback extraKeys,
        @NullAllowed final ClassPath sourcePath,
        @NullAllowed final ClassPath moduleSourcePath) {
    this.eval = eval;
    this.helper = helper;
    this.refHelper = refHelper;
    this.classPathProperties = new LinkedHashSet<>(classPathProperties);
    this.classPathIgnoreRef = new HashSet<String>(classPathIgnoreRef);
    this.boot = boot;
    this.modulePath = modulePath != null ?
            modulePath :
            Pair.<Set<String>,ClassPath>of(Collections.emptySet(), null);
    this.modulePathIgnoreRef = new HashSet<>(modulePathIgnoreRef);
    this.webModuleElementName = webModuleElementName;
    this.cs = cs;
    this.extraKeys = extraKeys;
    this.project = project;
    this.slResult = SourceLevelQuery.getSourceLevel2(
            this.helper.getAntProjectHelper().getProjectDirectory());
    this.sourcePath = sourcePath;
    this.moduleSourcePath = moduleSourcePath;
    this.coResult = new AtomicReference<>();
    this.sourceRootsListener = new AtomicReference<>();
}
项目:incubator-netbeans    文件:PlatformNode.java   
@Override
public boolean hasJavadoc() {
    Pair<String,JavaPlatform> platHolder = platformProvider.getPlatform();
    if (platHolder == null || platHolder.second() == null) {
        return false;
    }
    URL[] javadocRoots = getJavadocRoots(platHolder.second());
    return javadocRoots.length > 0;
}
项目:incubator-netbeans    文件:CssPreprocessorUtilsTest.java   
@Test
public void testResolveTargetOutsideWebRoot() {
    File root = new File("/root");
    File webRoot = new File(root, "web");
    List<Pair<String, String>> mappings = Collections.singletonList(Pair.of("../scss", "/css"));
    File input1 = new File(root, "scss/file1.scss");
    assertEquals(new File(webRoot, "css/file1.css"), CssPreprocessorUtils.resolveTarget(webRoot, mappings, input1));
    File input2 = new File(root, "scss/subdir/file2.scss");
    assertEquals(new File(webRoot, "css/subdir/file2.css"), CssPreprocessorUtils.resolveTarget(webRoot, mappings, input2));
}
项目:incubator-netbeans    文件:GoToPanel.java   
private boolean boundScrollingKey(KeyEvent ev) {
    final Pair<String,JComponent> p = listActionFor(ev);
    if (p == null) {
        return false;
    }
    String action = p.first();
    // See BasicListUI, MetalLookAndFeel:
    return "selectPreviousRow".equals(action) || // NOI18N
    "selectNextRow".equals(action) || // NOI18N
    "selectPreviousRowExtendSelection".equals(action) ||    //NOI18N
    "selectNextRowExtendSelection".equals(action) || //NOI18N
    "scrollUp".equals(action) || // NOI18N
    "scrollDown".equals(action); // NOI18N
}
项目:incubator-netbeans    文件:DocumentStoreTest.java   
private Pair<Collection<? extends IndexDocument>,Convertor<IndexDocument, Document>> createPackedData (
        final int size) {
    final Collection<IndexDocument> toAdd = new ClusteredIndexables.DocumentStore(CACHE_SIZE);
    for (int i=0; i < size; i++) {
        final IndexDocument doc = ClusteredIndexables.createDocument(Integer.toString(i));
        toAdd.add(fill(doc,i));
    }
    return Pair.<Collection<? extends IndexDocument>,Convertor<IndexDocument, Document>>of(
        toAdd,
        ClusteredIndexables.createDocumentIndexCache().createAddConvertor());
}
项目:incubator-netbeans    文件:PinWatchValueProvider.java   
@Override
public Action[] getHeadActions(Watch watch) {
    if (headAction == null) {
        return null;
    }
    Pair<ObjectVariable, ValueListeners> varVl = getObjectVariable(watch);
    if (varVl == null) {
        return null;
    }
    ObjectVariable expandableVar = varVl.first();
    return new Action[] { new ExpandAction(headAction, watch.getExpression(), expandableVar) };
}
项目:incubator-netbeans    文件:ProjectOperations.java   
Operations(
    @NonNull final Project project,
    @NonNull final PropertyEvaluator eval,
    @NonNull final UpdateHelper helper,
    @NonNull final ReferenceHelper refHelper,
    @NonNull final SourceRoots sources,
    @NonNull final SourceRoots tests,
    @NonNull final String buildScriptProperty,
    @NonNull final List<? extends String> additionalMetadataFiles,
    @NonNull final List<? extends String> additionalDataFiles,
    @NonNull final List<? extends String> cleanTargets,
    @NonNull final Set<? extends String> privateProps,
    @NonNull final Map<String,Pair<String,Boolean>> updatedProps,
    @NullAllowed final Callback callback) {
    Parameters.notNull("project", project); //NOI18N
    Parameters.notNull("eval", eval);   //NOI18N
    Parameters.notNull("helper", helper);   //NOI18N
    Parameters.notNull("refHelper", refHelper); //NOI18N
    Parameters.notNull("sources", sources); //NOI18N
    Parameters.notNull("tests", tests); //NOI18N
    Parameters.notNull("buildScriptProperty", buildScriptProperty); //NOI18N
    Parameters.notNull("additionalMetadataFiles", additionalMetadataFiles); //NOI18N
    Parameters.notNull("additionalDataFiles", additionalDataFiles); //NOI18N
    Parameters.notNull("cleanTargets", cleanTargets);   //NOI18N
    Parameters.notNull("privateProps", privateProps);   //NOI18N
    Parameters.notNull("updatedProps", updatedProps);   //NOI18N
    this.project = project;
    this.eval = eval;
    this.helper = helper;
    this.refHelper = refHelper;
    this.sources = sources;
    this.tests = tests;
    this.buildScriptProperty = buildScriptProperty;
    this.additionalMetadataFiles = additionalMetadataFiles;
    this.additionalDataFiles = additionalDataFiles;
    this.cleanTargets = cleanTargets;
    this.privateProps = privateProps;
    this.updatedProps = updatedProps;
    this.callback = callback;
}
项目:incubator-netbeans    文件:GsfHintsManager.java   
/** Read rules from system filesystem */
    private static List<Pair<Rule,FileObject>> readRules( FileObject folder ) {

        List<Pair<Rule,FileObject>> rules = new LinkedList<Pair<Rule,FileObject>>();

        if (folder == null) {
            return rules;
        }

        //HashMap<FileObject,DefaultMutableTreeNode> dir2node = new HashMap<FileObject,DefaultMutableTreeNode>();

//        // XXX Probably not he best order
//        Enumeration e = folder.getData( true );

        Enumeration<FileObject> e = Collections.enumeration(getSortedDataRecursively(folder));
        while( e.hasMoreElements() ) {
            FileObject o = e.nextElement();
            String name = o.getNameExt().toLowerCase();

            if ( o.canRead() ) {
                Rule r = null;
                if ( name.endsWith( INSTANCE_EXT ) ) {
                    r = instantiateRule(o);
                }
                if ( r != null ) {
                    rules.add( Pair.<Rule,FileObject>of( r, o ) );
                }
            }
        }
        Collections.sort(rules, new Comparator<Pair<Rule,FileObject>>() {
            @Override
            public int compare(Pair<Rule,FileObject> p1, Pair<Rule,FileObject> p2) {
                return p1.first().getDisplayName().compareTo(p2.first().getDisplayName());
            }
        });
        return rules;
    }
项目:incubator-netbeans    文件:ProjectOperations.java   
private void rememberDependencies() {
    final AntArtifactProvider aap = project.getLookup().lookup(AntArtifactProvider.class);
    if (aap == null) {
        return;
    }
    final Map<URI,Pair<AntArtifact,URI>> artifacts = createArtifactsMap(aap);
    final Set<Project> dependencies = new HashSet<>();
    for (Project prj : OpenProjects.getDefault().getOpenProjects()) {
        final SubprojectProvider spp = prj.getLookup().lookup(SubprojectProvider.class);
        if (spp != null && spp.getSubprojects().contains(project)) {
            dependencies.add(prj);
        }
    }
    Collection<Dependency> toFix = new ArrayList<>();
    for (Project depProject : dependencies) {
        for (SourceGroup sg : ProjectUtils.getSources(depProject).getSourceGroups(JavaProjectConstants.SOURCES_TYPE_JAVA)) {
            Set<URI> roots = classPathURIs(ClassPath.getClassPath(sg.getRootFolder(), ClassPath.COMPILE));
            for (Map.Entry<URI,Pair<AntArtifact,URI>> e : artifacts.entrySet()) {
                if (roots.contains(e.getKey())) {
                    final Dependency dep = new Dependency(
                            depProject,
                            sg,
                            e.getValue().first(),
                            e.getValue().second());
                    if (dep.remove()) {
                        toFix.add(dep);
                    }
                }
            }
        }
    }
    dependenciesToFix = toFix;
}
项目:incubator-netbeans    文件:SourceAnalyzerFactory.java   
/**
 * Analyzes given compilation unit and returns the result of analyzes.
 * @param cu the java compilation unit to be analyzed
 * @param jt the {@link JavacTaskImpl} providing the context
 * @param manager the {@link JavaFileManager} used to infer binary names
 * @return the result of analyzes encoded as list of tuples {{fqn,relative_source_path_or_null},usages_data}
 * @throws IOException in case of IO error
 */
@CheckForNull
public List<Pair<Pair<BinaryName, String>, Object[]>> analyseUnit (
        @NonNull final CompilationUnitTree cu,
        @NonNull final JavacTaskImpl jt) throws IOException {
    if (used) {
        throw new IllegalStateException("Trying to reuse SimpleAnalyzer");  //NOI18N
    }
    used = true;
    try {
        final Map<Pair<BinaryName,String>,UsagesData<String>> usages = new HashMap<> ();
        final Set<Pair<String,String>> topLevels = new HashSet<>();
        final JavaFileManager jfm = jt.getContext().get(JavaFileManager.class);
        final UsagesVisitor uv = new UsagesVisitor (jt, cu, jfm, cu.getSourceFile(), topLevels);
        uv.scan(cu,usages);
        for (Map.Entry<Pair<BinaryName,String>,UsagesData<String>> oe : usages.entrySet()) {
            final Pair<BinaryName,String> key = oe.getKey();
            final UsagesData<String> data = oe.getValue();
            addClassReferences (key,data);
        }
        //this.writer.deleteEnclosedAndStore(this.references, topLevels);
        return this.references;
    } catch (IllegalArgumentException iae) {
        Exceptions.printStackTrace(iae);
        return null;
    }catch (OutputFileManager.InvalidSourcePath e) {
        return null;
    }
}
项目:incubator-netbeans    文件:ToolTipAnnotation.java   
@Override
protected Pair<String, Object> evaluate(String expression, DebuggerEngine engine) throws CancellationException {
    Session session = engine.lookupFirst(null, Session.class);
    if (engine != session.getEngineForLanguage(JSUtils.JS_STRATUM)) {
        return null;
    }
    JPDADebugger d = engine.lookupFirst(null, JPDADebugger.class);
    if (d == null) {
        return null;
    }
    CallStackFrame frame = d.getCurrentCallStackFrame();
    if (frame == null) {
        return null;
    }
    String toolTipText;
    JSVariable jsresult = null;
    try {
        Variable result = DebuggerSupport.evaluate(d, frame, expression);
        if (result == null) {
            throw new CancellationException();
        }
        if (result instanceof ObjectVariable) {
            jsresult = JSVariable.createIfScriptObject(d, (ObjectVariable) result, expression);
        }
        if (jsresult != null) {
            toolTipText = expression + " = " + jsresult.getValue();
        } else {
            toolTipText = expression + " = " + DebuggerSupport.getVarValue(d, result);
        }
    } catch (InvalidExpressionException ex) {
        toolTipText = expression + " = >" + ex.getMessage () + "<";
    }
    return Pair.of(toolTipText, (Object) jsresult);
}
项目:incubator-netbeans    文件:CancelSupportTest.java   
public void testCancel_cancel_before_should_run() throws Exception {
    final AtomicBoolean added = new AtomicBoolean();
    tpHandler.on(
        "Set current request to: {0}",  //NOI18N
        new Action() {
            @Override
            public void run(final Object[] params) throws Exception {
                if (getTaskFromRequest((TaskProcessor.Request)params[0]) == task) {
                    if (added.compareAndSet(false, true)) {
                        RP.submit(new Runnable() {
                            @Override
                            public void run() {
                                TaskProcessor.addPhaseCompletionTasks(
                                    Collections.singleton(Pair.<SchedulerTask,Class<? extends Scheduler>>of(
                                        cancelTask,
                                        cancelTask.getSchedulerClass())),
                                    cache,
                                    false);
                                }
                        }).get();
                    } else {
                        task.setRerun(true);
                    }
                }
            }
        });
    TaskProcessor.addPhaseCompletionTasks(
        Collections.singleton(Pair.<SchedulerTask,Class<? extends Scheduler>>of(
            task,
            task.getSchedulerClass())),
        cache,
        false);
    assertFalse("TestTask started.", task.awaitStart(false));  //NOI18N
}