Java Code Examples for com.intellij.openapi.vfs.VirtualFile#exists()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#exists() . 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: AbstractConfigSource.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the target/classes/$configFile and null otherwise.
 * 
 * <p>
 * Using this file instead of using src/main/resources/$configFile gives the
 * capability to get the filtered value.
 * </p>
 * 
 * @return the target/classes/$configFile and null otherwise.
 */
private VirtualFile getConfigFile() {
	if (configFile != null && configFile.exists()) {
		return configFile;
	}
	if (javaProject.isLoaded()) {
		VirtualFile[] sourceRoots = ModuleRootManager.getInstance(javaProject).getSourceRoots();
		for (VirtualFile sourceRoot : sourceRoots) {
			VirtualFile file = sourceRoot.findFileByRelativePath(configFileName);
			if (file != null && file.exists()) {
				return file;
			}
		}
		return null;
	}
	return null;
}
 
Example 2
Source File: ModuleEditorImpl.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static void removeImlFile(final File imlFile) {
  final VirtualFile imlVirtualFile = VfsUtil.findFileByIoFile(imlFile, true);
  if (imlVirtualFile != null && imlVirtualFile.exists()) {
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                try {
                  imlVirtualFile.delete(this);
                } catch (IOException e) {
                  logger.warn(
                      String.format(
                          "Could not delete file: %s, will try to continue anyway.",
                          imlVirtualFile.getPath()),
                      e);
                }
              }
            });
  }
}
 
Example 3
Source File: AddDirectoryToProjectAction.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected ValidationInfo doValidate() {
  VirtualFile selectedFile = fileTextField.getSelectedFile();
  if (selectedFile == null || !selectedFile.exists()) {
    return new ValidationInfo("File does not exist", fileTextField.getField());
  } else if (!selectedFile.isDirectory()) {
    return new ValidationInfo("File is not a directory", fileTextField.getField());
  }

  WorkspacePath workspacePath =
      workspacePathResolver.getWorkspacePath(new File(selectedFile.getPath()));
  if (workspacePath == null) {
    return new ValidationInfo("File is not in workspace", fileTextField.getField());
  }

  if (Blaze.getBuildSystem(project) == BuildSystem.Blaze && workspacePath.isWorkspaceRoot()) {
    return new ValidationInfo(
        String.format(
            "Cannot add the workspace root '%s' to the project.\n"
                + "This will destroy performance.",
            selectedFile.getPath()));
  }

  ImportRoots importRoots = ImportRoots.builder(project).add(projectView).build();
  if (importRoots.containsWorkspacePath(workspacePath)) {
    return new ValidationInfo("This directory is already included in your project");
  }

  return null;
}
 
Example 4
Source File: TFSRollbackEnvironment.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private void undoPendingChanges(final List<FilePath> localPaths,
                                final List<VcsException> errors,
                                @NotNull final RollbackProgressListener listener) {
    logger.info("undoPendingChanges started");
    try {
        List<TfsPath> localFiles = localPaths.stream()
                .map(TfsFileUtil::createLocalPath)
                .collect(Collectors.toList());

        // Call the undo command synchronously
        final ServerContext context = vcs.getServerContext(true);
        final List<TfsLocalPath> filesUndone = TfvcClient.getInstance(project).undoLocalChanges(context, localFiles);

        // Trigger the accept callback and build up our refresh list
        final List<VirtualFile> refresh = new ArrayList<VirtualFile>(filesUndone.size());
        for (final TfsLocalPath path : filesUndone) {
            // Call the accept method on the listener to indicate progress
            final File fileUndone = new File(path.getPath());
            listener.accept(fileUndone);

            // Add the parent folder of the file to our refresh list
            final VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(fileUndone);
            final VirtualFile parent = file != null ? file.getParent() : null;
            if (parent != null && parent.exists()) {
                refresh.add(file);
            }
        }

        // Refresh all the folders that changed
        TfsFileUtil.refreshAndMarkDirty(project, refresh, true);
    } catch (final Throwable e) {
        logger.warn("undoPendingChanges: Errors caught: " + e.getMessage(), e);
        errors.add(new VcsException("Cannot undo pending changes", e));
    }
    logger.info("undoPendingChanges ended");
}
 
Example 5
Source File: DocumentAPI.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a document for the given file.
 *
 * @param virtualFile the <code>VirtualFile</code> for which the document is requested
 * @return a <code>Document</code> for the given file or <code>null</code> if the file does not
 *     exist, could not be read, is a directory, or is to large
 */
@Nullable
public static Document getDocument(@NotNull final VirtualFile virtualFile) {
  if (!virtualFile.exists()) {
    return null;
  }

  return FilesystemRunner.runReadAction(() -> fileDocumentManager.getDocument(virtualFile));
}
 
Example 6
Source File: FlutterModuleBuilder.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
private static VirtualFile findAndroidModuleFile(@NotNull VirtualFile baseDir, String flutterModuleName) {
  baseDir.refresh(false, false);
  for (String name : asList(flutterModuleName + "_android.iml", "android.iml")) {
    final VirtualFile candidate = baseDir.findChild(name);
    if (candidate != null && candidate.exists()) {
      return candidate;
    }
  }
  return null;
}
 
Example 7
Source File: FlutterModuleBuilder.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nullable
private static VirtualFile findAndroidModuleFile(@NotNull VirtualFile baseDir, String flutterModuleName) {
  baseDir.refresh(false, false);
  for (String name : asList(flutterModuleName + "_android.iml", "android.iml")) {
    final VirtualFile candidate = baseDir.findChild(name);
    if (candidate != null && candidate.exists()) {
      return candidate;
    }
  }
  return null;
}
 
Example 8
Source File: InspectorSourceLocation.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public VirtualFile getFile() {
  String fileName = getPath();
  if (fileName == null) {
    return parent != null ? parent.getFile() : null;
  }

  fileName = InspectorService.fromSourceLocationUri(fileName, project);

  final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(fileName);
  if (virtualFile != null && !virtualFile.exists()) {
    return null;
  }
  return virtualFile;
}
 
Example 9
Source File: HaxelibMetadata.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
public static HaxelibMetadata load(@NotNull VirtualFile libRoot) {
  String mdfile = HaxeFileUtil.joinPath(libRoot.getUrl(), "haxelib.json");
  VirtualFile metadatafile = VirtualFileManager.getInstance().findFileByUrl(mdfile);
  if (null == metadatafile || !metadatafile.exists()) {
    return EMPTY_METADATA;
  }
  return new HaxelibMetadata(metadatafile);
}
 
Example 10
Source File: OpenBlazeWorkspaceFileAction.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected ValidationInfo doValidate() {
  VirtualFile selectedFile = fileTextField.getSelectedFile();
  if (selectedFile == null || !selectedFile.exists()) {
    return new ValidationInfo("File does not exist", fileTextField.getField());
  } else if (selectedFile.isDirectory()) {
    return new ValidationInfo("Directories can not be opened", fileTextField.getField());
  } else {
    return null;
  }
}
 
Example 11
Source File: LanguageServerWrapper.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 *
 * @param document
 * @return null if not connection has happened, a future tracking the connection state otherwise
 * @throws IOException
 */
public @Nullable CompletableFuture<LanguageServer> connect(Document document) throws IOException {
    VirtualFile file = LSPIJUtils.getFile(document);

    if (file != null && file.exists()) {
        return connect(file, document);
    } else {
        URI uri = LSPIJUtils.toUri(document);
        if (uri != null) {
            return connect(uri, document);
        }
    }
    return null;
}
 
Example 12
Source File: FreelineUtil.java    From freeline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 正则二次判断是否存在Freeline classpath
 *
 * @param file
 * @return
 */
public static boolean regularExistFreelineClassPath(VirtualFile file) {
    try {
        if (file.exists()) {
            String content = FileUtils.readFileToString(new File(file.getPath()));
            Matcher matcher = PATTERN_CLASSPATH.matcher(content);
            return matcher.find();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 13
Source File: InspectorSourceLocation.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public VirtualFile getFile() {
  String fileName = getPath();
  if (fileName == null) {
    return parent != null ? parent.getFile() : null;
  }

  fileName = InspectorService.fromSourceLocationUri(fileName, project);

  final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(fileName);
  if (virtualFile != null && !virtualFile.exists()) {
    return null;
  }
  return virtualFile;
}
 
Example 14
Source File: RequirejsProjectComponent.java    From WebStormRequireJsPlugin with MIT License 5 votes vote down vote up
public void contentsChanged(@NotNull VirtualFileEvent event) {
            VirtualFile confFile = findPathInWebDir(settings.configFilePath);
            if (confFile == null || !confFile.exists() || !event.getFile().equals(confFile)) {
                return;
            }
            LOG.debug("RequireConfigVfsListener contentsChanged");
//            RequirejsProjectComponent.this.project.getComponent(RequirejsProjectComponent.class).parseRequirejsConfig();
            RequirejsProjectComponent.this.parseRequirejsConfig();
        }
 
Example 15
Source File: LocalEditorManipulator.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Opens an editor for the passed file.
 *
 * <p>If the editor is a text editor, it is also added to the pool of currently open editors and
 * {@link EditorManager#startEditor(Editor)} is called with it.
 *
 * <p><b>Note:</b> This does only work for shared resources.
 *
 * @param file the file to open
 * @param activate activate editor after opening
 * @return the editor for the given file, or <code>null</code> if the file does not exist or is
 *     not shared or can not be represented by a text editor
 */
public Editor openEditor(@NotNull IFile file, boolean activate) {
  if (!sarosSession.isShared(file)) {
    log.warn("Ignored open editor request for file " + file + " as it is not shared");

    return null;
  }

  VirtualFile virtualFile = VirtualFileConverter.convertToVirtualFile(file);

  if (virtualFile == null || !virtualFile.exists()) {
    log.warn(
        "Could not open Editor for file "
            + file
            + " as a matching virtual file does not exist or could not be found");

    return null;
  }

  Project project = ((IntellijReferencePoint) file.getReferencePoint()).getProject();

  Editor editor = ProjectAPI.openEditor(project, virtualFile, activate);

  if (editor == null) {
    log.debug("Ignoring non-text editor for file " + virtualFile);

    return null;
  }

  manager.startEditor(editor);
  editorPool.add(file, editor);

  log.debug("Opened Editor " + editor + " for file " + virtualFile);

  return editor;
}
 
Example 16
Source File: QuarkusLanguageClient.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
private void filter(VFileEvent event, Set<String> uris) {
  VirtualFile file = event.getFile();
  if (file != null && file.exists() && "java".equalsIgnoreCase(file.getExtension())) {
    Module module = ProjectFileIndex.getInstance(getProject()).getModuleForFile(file);
    if (module != null && (event instanceof VFileCreateEvent || event instanceof VFileContentChangeEvent || event instanceof VFileDeleteEvent)) {
      uris.add(PsiUtilsImpl.getProjectURI(module));
    }
  }
}
 
Example 17
Source File: IntellijFile.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates this file in the local filesystem with the given content.
 *
 * @param input an input stream to write into the file
 * @throws FileAlreadyExistsException if a resource with the same name already exists
 * @throws FileNotFoundException if the parent directory of this file does not exist
 */
private void createInternal(@Nullable InputStream input) throws IOException {
  IResource parent = getParent();

  VirtualFile parentFile = referencePoint.findVirtualFile(parent.getReferencePointRelativePath());

  if (parentFile == null || !parentFile.exists()) {
    throw new FileNotFoundException(
        "Could not create "
            + this
            + " as its parent folder "
            + parent
            + " does not exist or is not valid");
  }

  VirtualFile virtualFile = parentFile.findChild(getName());

  if (virtualFile != null && virtualFile.exists()) {
    throw new FileAlreadyExistsException(
        "Could not create "
            + this
            + " as a resource with the same name already exists: "
            + virtualFile);
  }

  parentFile.createChildData(this, getName());

  if (input != null) {
    setContents(input);
  }
}
 
Example 18
Source File: FastpassUpdater.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private static <T> Optional<T> readJsonFile(Path path, Class<T> cls) {
  VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(path.toFile());
  if (virtualFile != null && virtualFile.exists()) {
    try {
      String content = new String(virtualFile.contentsToByteArray());
      T parsed = new Gson().fromJson(content, cls);
      return Optional.of(parsed);
    }
    catch (Exception e) {
      LOG.warn("Failed to read and parse as json: " + path, e);
    }
  }
  return Optional.empty();
}
 
Example 19
Source File: TestFileSystem.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public boolean exists(File file) {
  VirtualFile vf = getVirtualFile(file);
  return vf != null && vf.exists();
}
 
Example 20
Source File: FlutterUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static boolean exists(@Nullable VirtualFile file) {
  return file != null && file.exists();
}