Java Code Examples for com.intellij.openapi.vfs.VirtualFileManager#getInstance()

The following examples show how to use com.intellij.openapi.vfs.VirtualFileManager#getInstance() . 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: TemplateUtils.java    From code-generator with Apache License 2.0 6 votes vote down vote up
private static void generateSourceFile(String source, String baseDir) {
    String packageName = extractPackage(source);
    String className = extractClassName(source);
    String sourcePath = buildSourcePath(baseDir, className, packageName);
    VirtualFileManager manager = VirtualFileManager.getInstance();
    VirtualFile virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
    if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride(className)) {
        ApplicationManager.getApplication().runWriteAction(() -> {
            try {
                if (virtualFile != null && virtualFile.exists()) {
                    virtualFile.setBinaryContent(source.getBytes("utf8"));

                } else {
                    File file = new File(sourcePath);
                    FileUtils.writeStringToFile(file, source, "utf8");
                    manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
                }
            } catch (IOException e) {
                log.error(e);
            }
        });
    }
}
 
Example 2
Source File: DirectoryUrl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Object[] createPath(final Project project) {
  if (moduleName != null) {
    final Module module = ApplicationManager.getApplication().runReadAction(new Computable<Module>() {
      @Nullable
      @Override
      public Module compute() {
        return ModuleManager.getInstance(project).findModuleByName(moduleName);
      }
    });
    if (module == null) return null;
  }
  final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
  final VirtualFile file = virtualFileManager.findFileByUrl(url);
  if (file == null) return null;
  final PsiDirectory directory = ApplicationManager.getApplication().runReadAction(new Computable<PsiDirectory>() {
    @Nullable
    @Override
    public PsiDirectory compute() {
      return PsiManager.getInstance(project).findDirectory(file);
    }
  });
  if (directory == null) return null;
  return new Object[]{directory};
}
 
Example 3
Source File: PersistentFileSetManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void loadState(Element state) {
  final VirtualFileManager vfManager = VirtualFileManager.getInstance();
  for (Object child : state.getChildren(FILE_ELEMENT)) {
    if (child instanceof Element) {
      final Element fileElement = (Element)child;
      final Attribute filePathAttr = fileElement.getAttribute(PATH_ATTR);
      if (filePathAttr != null) {
        final String filePath = filePathAttr.getValue();
        VirtualFile vf = vfManager.findFileByUrl(filePath);
        if (vf != null) {
          myFiles.add(vf);
        }
      }
    }
  }
}
 
Example 4
Source File: LightFilePointer.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void refreshFile() {
  VirtualFile file = myFile;
  if (file != null && file.isValid()) return;
  VirtualFileManager vfManager = VirtualFileManager.getInstance();
  VirtualFile virtualFile = vfManager.findFileByUrl(myUrl);
  if (virtualFile == null && !myRefreshed) {
    myRefreshed = true;
    Application application = ApplicationManager.getApplication();
    if (application.isDispatchThread() || !application.isReadAccessAllowed()) {
      virtualFile = vfManager.refreshAndFindFileByUrl(myUrl);
    }
    else {
      application.executeOnPooledThread(() -> vfManager.refreshAndFindFileByUrl(myUrl));
    }
  }

  myFile = virtualFile != null && virtualFile.isValid() ? virtualFile : null;
}
 
Example 5
Source File: RefreshSessionImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void fireEventsInWriteAction(List<? extends VFileEvent> events, @Nullable List<? extends AsyncFileListener.ChangeApplier> appliers) {
  final VirtualFileManagerEx manager = (VirtualFileManagerEx)VirtualFileManager.getInstance();

  manager.fireBeforeRefreshStart(myIsAsync);
  try {
    AsyncEventSupport.processEvents(events, appliers);
  }
  catch (AssertionError e) {
    if (FileStatusMap.CHANGES_NOT_ALLOWED_DURING_HIGHLIGHTING.equals(e.getMessage())) {
      throw new AssertionError("VFS changes are not allowed during highlighting", myStartTrace);
    }
    throw e;
  }
  finally {
    try {
      manager.fireAfterRefreshFinish(myIsAsync);
    }
    finally {
      if (myFinishRunnable != null) {
        myFinishRunnable.run();
      }
    }
  }
}
 
Example 6
Source File: LocalHistoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void initHistory() {
  ChangeListStorage storage;
  try {
    storage = new ChangeListStorageImpl(getStorageDir());
  }
  catch (Throwable e) {
    LocalHistoryLog.LOG.warn("cannot create storage, in-memory  implementation will be used", e);
    storage = new InMemoryChangeListStorage();
  }
  myChangeList = new ChangeList(storage);
  myVcs = new LocalHistoryFacade(myChangeList);

  myGateway = new IdeaGateway();

  myEventDispatcher = new LocalHistoryEventDispatcher(myVcs, myGateway);

  CommandProcessor.getInstance().addCommandListener(myEventDispatcher, this);

  myConnection = myBus.connect();
  myConnection.subscribe(VirtualFileManager.VFS_CHANGES, myEventDispatcher);

  VirtualFileManager fm = VirtualFileManager.getInstance();
  fm.addVirtualFileManagerListener(myEventDispatcher, this);
}
 
Example 7
Source File: HaxeFileUtil.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 * Find a file, given a path.  If the path is not absolute, then try as relative
 * to other given paths.
 *
 * @param path Path to test.  Null or empty path is not an error, but will return a null result.
 * @param rootPaths Variable number of other root paths to search.
 * @return null if the file could not be located; a VirtualFile if it could.
 */
@Nullable
public static VirtualFile locateFile(String path, String... rootPaths) {
  if (null == path || path.isEmpty()) {
    return null;
  }

  String tryPath = fixUrl(path);

  VirtualFileManager vfs = VirtualFileManager.getInstance();
  VirtualFile file = vfs.findFileByUrl(tryPath);
  if (null == file && !isAbsolutePath(tryPath)) {
    String nonUrlPath = vfs.extractPath(path);
    for (String root : rootPaths) {
      if (null != root && !root.isEmpty()) {
        tryPath = fixUrl(joinPath(root, nonUrlPath));
        file = vfs.findFileByUrl(tryPath);
        if (null != file) {
          break;
        }
      }
    }
  }

  return file;
}
 
Example 8
Source File: HaxeFileUtil.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
/**
 * Get the canonical name of a file, even when the directories are symlinks.
 *
 * @param file
 * @return
 */
public static VirtualFile getCanonicalFile(VirtualFile file) {
  try {
    java.io.File f = new java.io.File(file.getPath());
    java.io.File absolute = null == f ? null : f.getCanonicalFile();
    if (null != absolute) {
      // Of course, IDEA's notion of a URI requires "://" after the protocol separator
      // (as opposed to Java's ":").  So we can't just use the Java URI.
      VirtualFileManager vfm = VirtualFileManager.getInstance();
      String ideaUri = vfm.constructUrl(absolute.toURI().getScheme(), absolute.getPath());
      return VirtualFileManager.getInstance().findFileByUrl(ideaUri);
    }
  } catch(IOException e) {
    ; // Swallow
  }
  return null;
}
 
Example 9
Source File: CodeMakerAction.java    From CodeMaker with Apache License 2.0 6 votes vote down vote up
private void saveToFile(AnActionEvent anActionEvent, String language, String className, String content, ClassEntry currentClass, DestinationChooser.FileDestination destination, String encoding) {
    final VirtualFile file = destination.getFile();
    final String sourcePath = file.getPath() + "/" + currentClass.getPackageName().replace(".", "/");
    final String targetPath = CodeMakerUtil.generateClassPath(sourcePath, className, language);

    VirtualFileManager manager = VirtualFileManager.getInstance();
    VirtualFile virtualFile = manager
            .refreshAndFindFileByUrl(VfsUtil.pathToUrl(targetPath));

    if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride()) {
        // async write action
        ApplicationManager.getApplication().runWriteAction(
                new CreateFileAction(targetPath, content, encoding, anActionEvent
                        .getDataContext()));
    }
}
 
Example 10
Source File: BuckCellManagerImplTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  Project project = getProject();
  virtualFileManager = VirtualFileManager.getInstance();
  pathMacroManager = PathMacroManager.getInstance(project);
  buckCellSettingsProvider = BuckCellSettingsProvider.getInstance(project);
}
 
Example 11
Source File: VirtualFileWithDependenciesState.java    From consulo with Apache License 2.0 5 votes vote down vote up
public boolean isUpToDate(@Nonnull VirtualFile sourceFile) {
  if (sourceFile.getTimeStamp() != mySourceTimestamp) {
    return false;
  }

  VirtualFileManager manager = VirtualFileManager.getInstance();
  for (Map.Entry<String, Long> entry : myDependencies.entrySet()) {
    final VirtualFile file = manager.findFileByUrl(entry.getKey());
    if (file == null || file.getTimeStamp() != entry.getValue()) {
      return false;
    }
  }
  return true;
}
 
Example 12
Source File: HaxelibClasspathUtils.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
/**
 * Workhorse for findFileOnClasspath.
 * @param cp
 * @param filePath
 * @return
 */
@Nullable
private static VirtualFile findFileOnOneClasspath(@NotNull HaxeClasspath cp, @NotNull final String filePath) {
  final VirtualFileManager vfmInstance = VirtualFileManager.getInstance();

  class MyLambda implements HaxeClasspath.Lambda {
    public VirtualFile found = null;
    public boolean processEntry(HaxeClasspathEntry entry) {
      String dirUrl = entry.getUrl();
      if (!URLUtil.containsScheme(dirUrl)) {
        dirUrl = vfmInstance.constructUrl(URLUtil.FILE_PROTOCOL, dirUrl);
      }
      VirtualFile dirName = vfmInstance.findFileByUrl(dirUrl);
      if (null != dirName && dirName.isDirectory()) {
        // XXX: This is wrong if filePath is already an absolute file name.
        found = dirName.findFileByRelativePath(filePath);
        if (null != found) {
          return false;  // Stop the search.
        }
      }
      return true;
    }
  }

  MyLambda lambda = new MyLambda();
  cp.iterate(lambda);
  return lambda.found;
}
 
Example 13
Source File: CreateFileAction.java    From CodeMaker with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        VirtualFileManager manager = VirtualFileManager.getInstance();
        VirtualFile virtualFile = manager
                .refreshAndFindFileByUrl(VfsUtil.pathToUrl(outputFile));

        if (virtualFile != null && virtualFile.exists()) {
            virtualFile.setBinaryContent(content.getBytes(fileEncoding));
        } else {
            File file = new File(outputFile);
            FileUtils.writeStringToFile(file, content, fileEncoding);
            virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(outputFile));
        }
        VirtualFile finalVirtualFile = virtualFile;
        Project project = DataKeys.PROJECT.getData(dataContext);
        if (finalVirtualFile == null || project == null) {
            LOGGER.error(this);
            return;
        }
        ApplicationManager.getApplication()
                .invokeLater(
                        () -> FileEditorManager.getInstance(project).openFile(finalVirtualFile, true,
                                true));

    } catch (UnsupportedCharsetException ex) {
        ApplicationManager.getApplication().invokeLater(() -> Messages.showMessageDialog("Unknown Charset: " + fileEncoding + ", please use the correct charset", "Generate Failed", null));
    } catch (Exception e) {
        LOGGER.error("Create file failed", e);
    }

}
 
Example 14
Source File: NewFileTracker.java    From consulo with Apache License 2.0 5 votes vote down vote up
private NewFileTracker() {
  final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
  virtualFileManager.addVirtualFileListener(new VirtualFileAdapter() {
    @Override
    public void fileCreated(@Nonnull VirtualFileEvent event) {
      if (event.isFromRefresh()) return;
      newFiles.add(event.getFile());
    }
  });
}
 
Example 15
Source File: ContentEntriesEditor.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ContentEntriesEditor(String moduleName, final ModuleConfigurationState state) {
  super(state);
  myState = state;
  myModuleName = moduleName;
  myModulesProvider = state.getModulesProvider();
  final VirtualFileManagerAdapter fileManagerListener = new VirtualFileManagerAdapter() {
    @Override
    public void afterRefreshFinish(boolean asynchronous) {
      if (state.getProject().isDisposed()) {
        return;
      }
      final Module module = getModule();
      if (module == null || module.isDisposed()) return;
      for (final ContentEntryEditor editor : myEntryToEditorMap.values()) {
        editor.update();
      }
    }
  };
  final VirtualFileManager fileManager = VirtualFileManager.getInstance();
  fileManager.addVirtualFileManagerListener(fileManagerListener);
  registerDisposable(new Disposable() {
    @Override
    public void dispose() {
      fileManager.removeVirtualFileManagerListener(fileManagerListener);
    }
  });
}
 
Example 16
Source File: HaxelibClasspathUtils.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
/**
 * Given a module and a list of files, find the first one that occurs on the
 * classpath.
 *
 * @param module - Module from which to obtain the classpath.
 * @param files - a list of files to check.
 * @return the first of the list of files that occurs on the classpath, or
 *         null if none appear there.
 */
@Nullable
public static VirtualFile findFirstFileOnClasspath(@NotNull final Module module,
                                                   @NotNull final java.util.Collection<VirtualFile> files) {
  if (files.isEmpty()) {
    return null;
  }

  final VirtualFileManager vfmInstance = VirtualFileManager.getInstance();
  final HaxeClasspath cp = ApplicationManager.getApplication().runReadAction(new Computable<HaxeClasspath>() {
    @Override
    public HaxeClasspath compute() {
      return getFullClasspath(module);
    }
  });

  class MyLambda implements HaxeClasspath.Lambda {
    public VirtualFile found;
    public boolean processEntry(HaxeClasspathEntry entry) {
      String dirUrl = entry.getUrl();
      if (!URLUtil.containsScheme(dirUrl)) {
        dirUrl = vfmInstance.constructUrl(URLUtil.FILE_PROTOCOL, dirUrl);
      }
      VirtualFile dirName = vfmInstance.findFileByUrl(dirUrl);
      if (null != dirName && dirName.isDirectory()) {
        String dirPath = dirName.getPath();
        for (VirtualFile f : files) {
          if (f.exists()) {
            // We have a complete path, compare the leading paths.
            String filePath = f.getPath();
            if (filePath.startsWith(dirPath)) {
              found = f;
            }
          } else {
            // We have a partial path, search the path for a matching file.
            found = dirName.findFileByRelativePath(f.toString());
          }
          if (null != found) {
            return false;
          }
        }
      }
      return true;
    }
  }

  MyLambda lambda = new MyLambda();
  cp.iterate(lambda);
  return lambda.found;
}
 
Example 17
Source File: FileMonitor.java    From spring-javaformat with Apache License 2.0 4 votes vote down vote up
public static Factory factory() {
	return (project, trigger) -> new FileMonitor(project, trigger, VirtualFileManager.getInstance());
}