Java Code Examples for org.openide.filesystems.FileObject.isValid()

The following are Jave code examples for showing how to use isValid() of the org.openide.filesystems.FileObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 6 votes
public static void openLocation(CodeProfilingPoint.Location location) {
    File file = FileUtil.normalizeFile(new File(location.getFile()));
    final FileObject fileObject = FileUtil.toFileObject(file);

    if ((fileObject == null) || !fileObject.isValid()) {
        return;
    }

    final int documentOffset = getDocumentOffset(location);

    if (documentOffset == -1) {
        ProfilerDialogs.displayError(Bundle.Utils_CannotOpenSourceMsg());
        return;
    }

    GoToSource.openFile(fileObject, documentOffset);
}
 
Example 2
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 6 votes
public static int getDocumentOffset(CodeProfilingPoint.Location location) {
    File file = FileUtil.normalizeFile(new File(location.getFile()));
    FileObject fileObject = FileUtil.toFileObject(file);

    if ((fileObject == null) || !fileObject.isValid()) return -1;

    int linePosition = EditorSupport.getOffsetForLine(fileObject, location.getLine() - 1); // Line is 1-based, needs to be 0-based
    if (linePosition == -1) return -1;
    
    int lineOffset;
    if (location.isLineStart()) {
        lineOffset = 0;
    } else if (location.isLineEnd()) {
        lineOffset = EditorSupport.getOffsetForLine(fileObject, location.getLine()) - linePosition - 1; // TODO: workaround to get line length, could fail at the end of last line!!!
        if (lineOffset == -1) return -1;
    } else {
        lineOffset = location.getOffset();
    }

    return linePosition + lineOffset;
}
 
Example 3
Project: incubator-netbeans   File: NbModuleProjectGenerator.java   View Source Code Vote up 6 votes
/**
 * Detects whether <code>projectDir</code> is relative to
 * <code>suiteDir</code> and creates <em>nbproject/suite.properties</em> or
 * <em>nbproject/private/suite-private.properties</em> with
 * <em>suite.dir</em> appropriately set.
 */
public static void createSuiteProperties(FileObject projectDir, File suiteDir) throws IOException {
    File projectDirF = FileUtil.toFile(projectDir);
    String suiteLocation;
    String suitePropertiesLocation;
    //mkleint: removed CollocationQuery.areCollocated() reference
    // when AlwaysRelativeCQI gets removed the condition resolves to false more frequently.
    // that might not be desirable.
    String rel = PropertyUtils.relativizeFile(projectDirF, suiteDir);
    if (rel != null) {
        suiteLocation = "${basedir}/" + rel; // NOI18N
        suitePropertiesLocation = "nbproject/suite.properties"; // NOI18N
    } else {
        suiteLocation = suiteDir.getAbsolutePath();
        suitePropertiesLocation = "nbproject/private/suite-private.properties"; // NOI18N
    }
    EditableProperties props = new EditableProperties(true);
    props.setProperty("suite.dir", suiteLocation); // NOI18N
    FileObject suiteProperties = projectDir.getFileObject(suitePropertiesLocation);
    if (suiteProperties == null || !suiteProperties.isValid()) {
        suiteProperties = createFileObject(projectDir, suitePropertiesLocation);
    }
    Util.storeProperties(suiteProperties, props);
}
 
Example 4
Project: incubator-netbeans   File: Utils.java   View Source Code Vote up 6 votes
public static String getClassName(CodeProfilingPoint.Location location) {
    File file = FileUtil.normalizeFile(new File(location.getFile()));
    FileObject fileObject = FileUtil.toFileObject(file);

    if ((fileObject == null) || !fileObject.isValid()) {
        return null;
    }

    int documentOffset = getDocumentOffset(location);

    if (documentOffset == -1) {
        return null;
    }
    // FIXME - optimize
    JavaProfilerSource src = JavaProfilerSource.createFrom(fileObject);
    if (src == null) return null;
    SourceClassInfo sci = src.getEnclosingClass(documentOffset);
    if (sci == null) return null;
    return sci.getQualifiedName();
}
 
Example 5
Project: incubator-netbeans   File: GoToSupport.java   View Source Code Vote up 5 votes
private static void openLocation(DeclarationLocation location) {
    FileObject f = location.getFileObject();
    int offset = location.getOffset();

    if (f != null && f.isValid()) {
        UiUtils.open(f, offset);
    }
}
 
Example 6
Project: incubator-netbeans   File: FolderActionsImplementationProvider.java   View Source Code Vote up 5 votes
@Override
public boolean canRename(Lookup lookup) {
    Collection<? extends Node> nodes = lookup.lookupAll(Node.class);
    //we are able to rename only one node selection [at least for now ;-) ]
    if (nodes.size() != 1) {
        return false;
    }

    //apply only on supported mimetypes and if not invoked in editor context
    Node node = nodes.iterator().next();
    EditorCookie ec = getEditorCookie(node);
    if (ec == null || !isFromEditor(ec)) {
        FileObject fo = getFileObjectFromNode(node);
        if (fo != null && fo.isValid() && fo.isFolder()) {
            //check if the folder is a part of a web-like project using the
            //web root query
            if (ProjectWebRootQuery.getWebRoot(fo) != null) {

                // In Maven based projects the rename action need to do something different
                // See issue #219887
                FileObject pom = fo.getFileObject("pom.xml"); //NOI18N
                if (pom != null) {
                    return false;
                }

                //looks like the file is a web like project
                try {
                    return !fo.getFileSystem().isReadOnly();
                } catch (FileStateInvalidException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    }

    return false;

}
 
Example 7
Project: incubator-netbeans   File: DialogBinding.java   View Source Code Vote up 5 votes
/**
 * Bind given component and given file together.
 *
 * @param fileObject to bind
 * @param offset position at which content of the component will be virtually placed
 * @param length how many characters replace from the original file
 * @param component component to bind
 */
public static void bindComponentToFile(FileObject fileObject, int offset, int length, JTextComponent component) {
    Parameters.notNull("fileObject", fileObject); //NOI18N
    Parameters.notNull("component", component); //NOI18N
    if (!fileObject.isValid() || !fileObject.isData()) {
        return;
    }
    if (offset < 0 || offset > fileObject.getSize()) {
        throw new IllegalArgumentException("Invalid offset=" + offset + "; file.size=" + fileObject.getSize()); //NOI18N
    }
    if (length < 0 || offset + length > fileObject.getSize()) {
        throw new IllegalArgumentException("Invalid lenght=" + length + "; offset=" + offset + ", file.size=" + fileObject.getSize()); //NOI18N
    }
    bind(component, null, fileObject, offset, -1, -1, length, fileObject.getMIMEType());
}
 
Example 8
Project: incubator-netbeans   File: AbstractFSTestCase.java   View Source Code Vote up 5 votes
protected FileObject getVersionedFolder() throws IOException {
    if (versionedFolder == null) {
        versionedFolder = createFolder(versionedPath);
        FileObject md = versionedFolder.getFileObject(TestVCS.TEST_VCS_METADATA);
        if(md == null || !md.isValid()) {
            createFolder(versionedPath + "/" + TestVCS.TEST_VCS_METADATA);
        }
        // cleanup the owner cache, this folder just became versioned 
        VersioningManager.getInstance().flushNullOwners(); 
    }
    return versionedFolder;
}
 
Example 9
Project: incubator-netbeans   File: BackupFacility2.java   View Source Code Vote up 5 votes
/**
 * restore file, which was stored by backup(file)
 *
 * @param id identification of backup transaction
 * @throws java.io.IOException if restore failed.
 */
void restore(long id) throws IOException {
    BackupEntry entry = map.get(id);
    if (entry == null) {
        throw new IllegalArgumentException("Backup with id " + id + "does not exist"); // NOI18N
    }
    File backup = File.createTempFile("nbbackup", null); //NOI18N
    backup.deleteOnExit();
    boolean exists = false;
    FileObject fo = entry.orig;
    if(!fo.isValid()) { // Try to restore FO
        FileObject file = FileUtil.toFileObject(FileUtil.toFile(fo));
        fo = file == null? fo : file;
    }
    if (exists = fo.isValid()) {
        backup.createNewFile();
        copy(fo, backup);
    } else {
        fo = createNewFile(fo);
    }
    if (entry.exists) {
        if (!tryUndoOrRedo(fo, entry)) {
            copy(entry.file, fo);
        }
    } else {
        fo.delete();
    }
    entry.exists = exists;
    entry.file.delete();
    if (backup.exists()) {
        entry.file = backup;
    } else {
        map.remove(id);
    }
}
 
Example 10
Project: incubator-netbeans   File: SourceMapsScanner.java   View Source Code Vote up 5 votes
private void registerIfSourceMap(FileObject fo) {
    if (!fo.isValid() || !fo.isData() ||
        !fo.getExt().equalsIgnoreCase(SRC_MAP_EXT) ||
        !fo.canRead()) {

        return ;
    }
    LOG.log(Level.FINE, "  found source map (?) {0}", fo);
    SourceMap sm;
    try {
        sm = SourceMap.parse(fo.asText("UTF-8"));
    } catch (IOException | IllegalArgumentException ex) {
        return ;
    }
    FileObject compiledFO;
    String compiledFile = sm.getFile();
    if (compiledFile == null) {
        compiledFO = findCompiledFile(fo);
    } else {
        compiledFO = fo.getParent().getFileObject(compiledFile);
    }
    LOG.log(Level.FINE, "  have source map for generated file {0}", compiledFO);
    if (compiledFO != null) {
        synchronized (sourceMaps) {
            sourceMaps.put(fo, sm);
        }
        smt.registerTranslation(compiledFO, sm);
    }
}
 
Example 11
Project: incubator-netbeans   File: JpaControllerGenerator.java   View Source Code Vote up 5 votes
private static FileObject addImplementsClause(FileObject fileObject, final String className, final String interfaceName) throws IOException {
    JavaSource javaSource = JavaSource.forFileObject(fileObject);
    if(javaSource == null){
        if (!fileObject.isValid()) {
            fileObject.getParent().refresh();	//Maybe fo.refresh() is enough
            fileObject = FileUtil.toFileObject(FileUtil.toFile(fileObject));
            if (fileObject != null) {
                javaSource = JavaSource.forFileObject(fileObject);
            }
        } 
    }
    if(javaSource == null){
        Logger.getLogger(JpaControllerGenerator.class.getName()).log(Level.WARNING, "Can''t find JavaSource for {0}", fileObject.getPath());
        return fileObject;//just return, no need in npe next step
    }
    final boolean[] modified = new boolean[] { false };
    ModificationResult modificationResult = javaSource.runModificationTask(new Task<WorkingCopy>() {
        @Override
        public void run(WorkingCopy workingCopy) throws Exception {
            workingCopy.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
            TypeElement typeElement = workingCopy.getElements().getTypeElement(className);
            TypeMirror interfaceType = workingCopy.getElements().getTypeElement(interfaceName).asType();
            if (!workingCopy.getTypes().isSubtype(typeElement.asType(), interfaceType)) {
                ClassTree classTree = workingCopy.getTrees().getTree(typeElement);
                ClassTree newClassTree = GenerationUtils.newInstance(workingCopy).addImplementsClause(classTree, interfaceName);
                modified[0] = true;
                workingCopy.rewrite(classTree, newClassTree);
            }
        }
    });
    if (modified[0]) {
        modificationResult.commit();
    }
    return fileObject;
}
 
Example 12
Project: incubator-netbeans   File: CoverageSideBar.java   View Source Code Vote up 5 votes
public void setCoverage(FileCoverageDetails details) {
    if (details != null) {
        FileCoverageSummary summary = details.getSummary();
        float coverage = summary.getCoveragePercentage();

        if (coverage >= 0.0) {
            coverageBar.setCoveragePercentage(coverage);
        }
        //coverageBar.setStats(summary.getLineCount(), summary.getExecutedLineCount(),
        //        summary.getInferredCount(), summary.getPartialCount());

        long dataModified = details.lastUpdated();
        FileObject fo = details.getFile();
        boolean tooOld = false;
        if (fo != null && dataModified > 0 && dataModified < fo.lastModified().getTime()) {
            tooOld = true;
        } else if (fo != null && fo.isValid()) {
            try {
                DataObject dobj = DataObject.find(fo);
                tooOld = dobj.isModified();
            } catch (DataObjectNotFoundException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        if (tooOld) {
            warningsLabel.setText(NbBundle.getMessage(CoverageSideBar.class, "DataTooOld"));
        } else {
            warningsLabel.setText("");
        }
    } else {
        coverageBar.setCoveragePercentage(0.0f);
        warningsLabel.setText("");
    }
}
 
Example 13
Project: incubator-netbeans   File: JavadocAndSourceRootDetection.java   View Source Code Vote up 5 votes
/**
 * Finds Java sources roots inside of given folder.
 *
 * @param folder to start search in; routine will traverse subfolders
 *  to find a Java file to detect package root; cannot be null; must be folder
 * @param canceled if set to true the method immediately returns roots it has already found,
 * may be null
 * @return {@link Collection} of found package roots
 * @since 1.31
 */
public static Set<? extends FileObject> findSourceRoots(final @NonNull FileObject folder, final @NullAllowed AtomicBoolean canceled) {
    Parameters.notNull("folder", folder);   //NOI18N
    if (!folder.isValid()) {
        throw new IllegalArgumentException("Folder: " + FileUtil.getFileDisplayName(folder)+" is not valid.");  //NOI18N
    }
    if (!folder.isFolder()) {
        throw new IllegalArgumentException("The parameter: " + FileUtil.getFileDisplayName(folder) + " has to be a directory.");    //NOI18N
    }
    final Set<FileObject> result = new HashSet<FileObject>();
    findAllSourceRoots(folder, result, canceled, 0);
    return Collections.unmodifiableSet(result);
}
 
Example 14
Project: incubator-netbeans   File: FileMoveBreakpointsHandler.java   View Source Code Vote up 5 votes
void removed() {
    lb.removePropertyChangeListener(LineBreakpoint.PROP_URL, this);
    FileObject theFO;
    boolean valid;
    synchronized (this) {
        theFO = fo;
        if (theFO == null) {
            return ;
        }
        valid = theFO.isValid();
        if (valid) {  // Removed from a non-deleted file, abandon listening on DataObject
            if (dobjRef != null) {
                DataObject dobj = dobjRef.get();
                if (dobj != null) {
                    dobj.removePropertyChangeListener(dobjwl);
                }
                dobjRef = null;
                dobjwl = null;
            }
            if (registryListener != null) {
                DataObject.getRegistry().removeChangeListener(registryListener);
                registryListener = null;
            }
        } else {    // Breakpoint was removed on file deletion, keep listening on DataObject, it can get a new primary file
            fileWasDeleted = true;
        }
    }
}
 
Example 15
Project: incubator-netbeans   File: J2SEModularPersistenceProvider.java   View Source Code Vote up 5 votes
private PersistenceScope getPersistenceScope(FileObject root) {
    Pair<PersistenceScope, EntityClassScope> scope = scopes.get(root);
    final FileObject persistenceXml = scope != null ? scope.first().getPersistenceXml() : null;
    if (persistenceXml != null && persistenceXml.isValid()) {
        return scope.first();
    }
    return null;
}
 
Example 16
Project: incubator-netbeans   File: PersistenceScopeProviderImpl.java   View Source Code Vote up 5 votes
/**
 * validated access to the current PersistenceScope instance by checking
 * the presence of a persistence.xml file
 * @param fileObject file to check for persistence scope, not used !
 * @return a valid PersistenceScope instance or null
 */
@Override public synchronized PersistenceScope findPersistenceScope(FileObject fileObject)
{
    if (persistenceScope == null) {
        ProjectSourcesClassPathProvider classpath = project.getLookup().lookup(ProjectSourcesClassPathProvider.class);
        PersistenceScopeImplementation persistenceScopeImpl = new PersistenceScopeImpl(locProvider, classpath);
        persistenceScope = PersistenceScopeFactory.createPersistenceScope(persistenceScopeImpl);
    }
    FileObject persistenceXml = persistenceScope.getPersistenceXml();
    if (persistenceXml != null && persistenceXml.isValid()) {
        return persistenceScope;
    }
    return null;
}
 
Example 17
Project: incubator-netbeans   File: SourceUtils.java   View Source Code Vote up 4 votes
/**
 * Returns classes declared in the given source file which have the main method.
 * @param fo source file
 * @return the classes containing main method
 * @throws IllegalArgumentException when file does not exist or is not a java source file.
 */
public static Collection<ElementHandle<TypeElement>> getMainClasses (final @NonNull FileObject fo) {
    Parameters.notNull("fo", fo);   //NOI18N
    if (!fo.isValid()) {
        throw new IllegalArgumentException ("FileObject : " + FileUtil.getFileDisplayName(fo) + " is not valid.");  //NOI18N
    }
    if (fo.isVirtual()) {
        throw new IllegalArgumentException ("FileObject : " + FileUtil.getFileDisplayName(fo) + " is virtual.");  //NOI18N
    }
    final JavaSource js = JavaSource.forFileObject(fo);        
    if (js == null) {
        throw new IllegalArgumentException ();
    }
    try {
        final LinkedHashSet<ElementHandle<TypeElement>> result = new LinkedHashSet<> ();
        js.runUserActionTask(new Task<CompilationController>() {            
            @Override
            public void run(final CompilationController control) throws Exception {
                if (control.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED).compareTo (JavaSource.Phase.ELEMENTS_RESOLVED)>=0) {
                    final List<TypeElement>  types = new ArrayList<>();
                    final ElementScanner6<Void,Void> visitor = new ElementScanner6<Void, Void>() {
                        @Override
                        public Void visitType(TypeElement e, Void p) {
                            if (e.getEnclosingElement().getKind() == ElementKind.PACKAGE
                               || e.getModifiers().contains(Modifier.STATIC)) {
                                types.add(e);
                                return super.visitType(e, p);
                            } else {
                                return null;
                            }
                        }
                    };
                    visitor.scan(control.getTopLevelElements(), null);
                    for (TypeElement type : types) {
                        for (ExecutableElement exec :  ElementFilter.methodsIn(control.getElements().getAllMembers(type))) {
                            if (SourceUtils.isMainMethod(exec)) {
                                result.add (ElementHandle.create(type));
                            }
                        }
                    }
                }
            }                

        }, true);
        return result;
    } catch (IOException ioe) {
        Exceptions.printStackTrace(ioe);
        return Collections.<ElementHandle<TypeElement>>emptySet();
    }		
}
 
Example 18
Project: incubator-netbeans   File: TreeRootNode.java   View Source Code Vote up 4 votes
public boolean acceptFileObject(FileObject fo) {
    return fo.isValid() && g.contains(fo) && VisibilityQuery.getDefault().isVisible(fo);
}
 
Example 19
Project: incubator-netbeans   File: JavaSourceTaskFactory.java   View Source Code Vote up 4 votes
private void stateChangedImpl(List<FileObject> currentFiles) {
    LOG.log(Level.FINEST, BEFORE_ADDING_REMOVING_TASKS);
    synchronized (this.filesLock) {                
        List<FileObject> addedFiles = new ArrayList<FileObject>(currentFiles);
        List<FileObject> removedFiles = new ArrayList<FileObject>(file2Task.keySet());
        
        addedFiles.removeAll(file2Task.keySet());
        removedFiles.removeAll(currentFiles);
        
        //remove old tasks:
        for (FileObject r : removedFiles) {
            JavaSource source = file2JS.remove(r);
            
            if (source == null) {
                //TODO: log
                continue;
            }
            ACCESSOR2.removePhaseCompletionTask(source, file2Task.remove(r));
        }
        
        //add new tasks:
        for (FileObject a : addedFiles) {
            if (a == null)
                continue;
            if (!a.isValid()) {
                continue;
            }
            JavaSource js = JavaSource.forFileObject(a);
            
            if (js != null) {
                CancellableTask<CompilationInfo> task = createTask(a);

                if (task == null) {
                    throw new IllegalStateException("createTask(FileObject) returned null for factory: " + getClass().getName());
                }                    
                ACCESSOR2.addPhaseCompletionTask(js, task, phase, priority, taskIndexingMode);                    
                file2Task.put(a, task);
                file2JS.put(a, js);
            }
        }
    }
}
 
Example 20
Project: incubator-netbeans   File: TestUtil.java   View Source Code Vote up 4 votes
/**
 * Returns full names of all primary Java classes
 * withing the specified folder (non-recursive).
 *
 * @param  packageFolder  folder to search
 * @param  classPath  classpath to be used for the search
 * @return  list of full names of all primary Java classes
 *          within the specified package
 */
public static List<String> getJavaFileNames(FileObject packageFolder, ClasspathInfo cpInfo) {
    FileObject[] children = packageFolder.getChildren();
    if (children.length == 0) {
        return Collections.<String>emptyList();
    }
    
    final Collection<FileObject> javaFiles = new ArrayList<FileObject>(children.length);
    for (FileObject child : children) {
        if (!child.isFolder()
                && child.isValid()
                && child.getMIMEType().equals(JAVA_MIME_TYPE)) {
            javaFiles.add(child);
        }
    }
    if (javaFiles.isEmpty()) {
        return Collections.<String>emptyList();
    }

    FileObject[] javaFilesArr = (javaFiles.size() == children.length)
                                ? children
                                : javaFiles.toArray(new FileObject[javaFiles.size()]);
    final JavaSource source = JavaSource.create(cpInfo, javaFilesArr);
    if (source == null) {
        ErrorManager.getDefault().log(
                ErrorManager.EXCEPTION,
                "Could not get JavaSource for files "               //NOI18N
                        + javaFilesArr);
        return Collections.<String>emptyList();
    }

    List<ElementHandle<TypeElement>> topClasses;
    try {
        topClasses = TopClassFinder.findMainTopClasses(source);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        topClasses = null;
    }
    if ((topClasses == null) || topClasses.isEmpty()) {
        return Collections.<String>emptyList();
    }
        
    final List<String> result = new ArrayList<String>(topClasses.size());
    for (ElementHandle<TypeElement> topClassHandle : topClasses) {
        result.add(topClassHandle.getQualifiedName());
    }
    return result.isEmpty() ? Collections.<String>emptyList() : result;
}