Java Code Examples for com.intellij.openapi.vfs.LocalFileSystem

The following examples show how to use com.intellij.openapi.vfs.LocalFileSystem. These examples are extracted from open source projects. 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 Project: p4ic4idea   Source File: IdeaLightweightExtension.java    License: Apache License 2.0 6 votes vote down vote up
private void setupLocalFileSystem(LocalFileSystem lfs) {
    // Strong arm the LocalFileSystem
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = ClassLoader.getSystemClassLoader();
    }
    try {
        Class<?> holder = classLoader.loadClass(
                "com.intellij.openapi.vfs.LocalFileSystem$LocalFileSystemHolder");
        for (Field field: holder.getDeclaredFields()) {
            if (LocalFileSystem.class.isAssignableFrom(field.getType())) {
                field.setAccessible(true);
                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
                field.set(null, lfs);
                break;
            }
        }
    } catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) {
        fail(e);
    }
}
 
Example 2
Source Project: markdown-image-kit   Source File: AbstractUploadCloudActionTest.java    License: MIT License 6 votes vote down vote up
/**
 * 获取 VirtualFile 的几种方式
 *
 * @param e the e
 */
private void getVirtualFile(AnActionEvent e) {
    // 获取 VirtualFile 方式一:
    VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    // 获取多个 VirtualFile
    VirtualFile[] virtualFiles = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
    // 方式二: 从本地文件系统路径获取
    VirtualFile virtualFileFromLocalFileSystem = LocalFileSystem.getInstance().findFileByIoFile(new File("path"));
    // 方式三: 从 PSI 文件 (如果 PSI 文件仅存在内存中, 则可能返回 null)
    PsiFile psiFile = e.getData(CommonDataKeys.PSI_FILE);
    if (psiFile != null) {
        psiFile.getVirtualFile();
    }
    // 方式四: 从 document 中
    Document document = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
    VirtualFile virtualFileFromDocument = FileDocumentManager.getInstance().getFile(document);

    // 获取 document
    getDocument(e);
}
 
Example 3
Source Project: needsmoredojo   Source File: SourcesLocator.java    License: Apache License 2.0 6 votes vote down vote up
public static @NotNull VirtualFile[] getProjectSourceDirectories(Project project, boolean pullFromSettings)
{
    DojoSettings settingsService = ServiceManager.getService(project, DojoSettings.class);
    String projectLibrary = settingsService.getProjectSourcesDirectory();

    // it's an array in case I decide to add multiple non-dojo source library capability
    if(projectLibrary != null && !projectLibrary.equals("") && pullFromSettings)
    {
        VirtualFile file = LocalFileSystem.getInstance().findFileByPath(projectLibrary);
        return new VirtualFile[] {  file };
    }
    else
    {
        // return the dojo library sources
        VirtualFile dojoSourcesDirectory = getDojoSourcesDirectory(project, pullFromSettings);
        if(dojoSourcesDirectory != null)
        {
            return new VirtualFile[] { dojoSourcesDirectory };
        }
        else
        {
            return new VirtualFile[0];
        }
    }
}
 
Example 4
@NotNull
protected VirtualFile createProjectJarSubFile(String relativePath, Pair<ByteArraySequence, String>... contentEntries) throws IOException {
  assertTrue("Use 'jar' extension for JAR files: '" + relativePath + "'", FileUtilRt.extensionEquals(relativePath, "jar"));
  File f = new File(getProjectPath(), relativePath);
  FileUtil.ensureExists(f.getParentFile());
  FileUtil.ensureCanCreateFile(f);
  final boolean created = f.createNewFile();
  if (!created) {
    throw new AssertionError("Unable to create the project sub file: " + f.getAbsolutePath());
  }

  Manifest manifest = new Manifest();
  manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
  JarOutputStream target = new JarOutputStream(new FileOutputStream(f), manifest);
  for (Pair<ByteArraySequence, String> contentEntry : contentEntries) {
    addJarEntry(contentEntry.first.getBytes(), contentEntry.second, target);
  }
  target.close();

  final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f);
  assertNotNull(virtualFile);
  final VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile);
  assertNotNull(jarFile);
  return jarFile;
}
 
Example 5
Source Project: intellij-haxe   Source File: HaxeClasspathEntry.java    License: Apache License 2.0 6 votes vote down vote up
public HaxeClasspathEntry(@Nullable String name, @NotNull String url) {
  myName = name;
  myUrl = url;

  // Try to fix the URL if it wasn't correct.
  if (!url.contains(URLUtil.SCHEME_SEPARATOR)) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Fixing malformed URL passed by " + HaxeDebugUtil.printCallers(5));
    }
    VirtualFileSystem vfs = VirtualFileManager.getInstance().getFileSystem(LocalFileSystem.PROTOCOL);
    VirtualFile file = vfs.findFileByPath(url);
    if (null != file) {
      myUrl = file.getUrl();
    }
  }

  if (null != myName) {
    if (HaxelibNameUtil.isManagedLibrary(myName)) {
      myName = HaxelibNameUtil.parseHaxelib(myName);
      myIsManagedEntry = true;
    }
  }
}
 
Example 6
/**
 * Returns the Android SDK that matches the ANDROID_HOME environment variable, provided it exists.
 */
@Nullable
public static IntelliJAndroidSdk fromEnvironment() {
  final String path = EnvironmentUtil.getValue("ANDROID_HOME");
  if (path == null) {
    return null;
  }

  // TODO(skybrian) refresh?
  final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
  if (file == null) {
    return null;
  }

  return fromHome(file);
}
 
Example 7
Source Project: leetcode-editor   Source File: ClearAllAction.java    License: Apache License 2.0 6 votes vote down vote up
public void delFile(File file, Project project) {
    if (!file.exists()) {
        return;
    }

    if (file.isDirectory()) {
        File[] files = file.listFiles();
        for (File f : files) {
            delFile(f, project);
        }
    }
    try {
        VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
        if (FileEditorManager.getInstance(project).isFileOpen(vf)) {
            FileEditorManager.getInstance(project).closeFile(vf);
        }
        file.delete();
    } catch (Exception e) {
        LogUtils.LOG.error("Error deleting file", e);
    }

}
 
Example 8
Source Project: ijaas   Source File: JavaGetImportCandidatesHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private Project findProject(String file) {
  LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
  ProjectLocator projectLocator = ProjectLocator.getInstance();
  AtomicReference<Project> ret = new AtomicReference<>();
  FileUtil.processFilesRecursively(
      new File(file),
      (f) -> {
        VirtualFile vf = localFileSystem.findFileByIoFile(f);
        if (vf != null) {
          ret.set(projectLocator.guessProjectForFile(vf));
          return false;
        }
        return true;
      });
  return ret.get();
}
 
Example 9
Source Project: Intellij-Plugin   Source File: GaugeConsoleProperties.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public SMTestLocator getTestLocator() {
    return (protocol, path, project, globalSearchScope) -> {
        try {
            String[] fileInfo = path.split(Constants.SPEC_SCENARIO_DELIMITER);
            VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fileInfo[0]);
            if (file == null) return new ArrayList<>();
            PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
            if (psiFile == null) return new ArrayList<>();
            Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
            if (document == null) return new ArrayList<>();
            int line = Integer.parseInt(fileInfo[1]);
            PsiElement element = psiFile.findElementAt(document.getLineStartOffset(line));
            if (element == null) return new ArrayList<>();
            return Collections.singletonList(new PsiLocation<>(element));
        } catch (Exception e) {
            return new ArrayList<>();
        }
    };
}
 
Example 10
public void testErrorMessageWithStrangerFilePath() {

    try (TempFile filePathWithSpace = TempFile.create("pants_exp  ort_run", ".out")) {

      Optional<PantsMakeBeforeRun.ParseResult> result = PantsMakeBeforeRun.ParseResult.parseErrorLocation(
        "                       [error] " + filePathWithSpace.getFile().getAbsolutePath() + ":23:1: cannot find symbol",
        ERROR_TAG
      );
      assertTrue(result.isPresent());
      assertEquals(
        LocalFileSystem.getInstance()
          .findFileByIoFile(filePathWithSpace.getFile()),
        result.get().getFile()
      );
      assertEquals(23, result.get().getLineNumber());
      assertEquals(1, result.get().getColumnNumber());
    }
    catch (IOException e) {
      // Fall-through to handle outside the block.
    }
  }
 
Example 11
Source Project: consulo   Source File: VfsEventGenerationHelper.java    License: Apache License 2.0 6 votes vote down vote up
void scheduleCreation(@Nonnull VirtualFile parent,
                      @Nonnull String childName,
                      @Nonnull FileAttributes attributes,
                      @Nullable String symlinkTarget,
                      @Nonnull ThrowableRunnable<RefreshWorker.RefreshCancelledException> checkCanceled) throws RefreshWorker.RefreshCancelledException {
  if (LOG.isTraceEnabled()) LOG.trace("create parent=" + parent + " name=" + childName + " attr=" + attributes);
  ChildInfo[] children = null;
  if (attributes.isDirectory() && parent.getFileSystem() instanceof LocalFileSystem && !attributes.isSymLink()) {
    try {
      Path child = Paths.get(parent.getPath(), childName);
      if (shouldScanDirectory(parent, child, childName)) {
        Path[] relevantExcluded = ContainerUtil.mapNotNull(ProjectManagerEx.getInstanceEx().getAllExcludedUrls(), url -> {
          Path path = Paths.get(VirtualFileManager.extractPath(url));
          return path.startsWith(child) ? path : null;
        }, new Path[0]);
        children = scanChildren(child, relevantExcluded, checkCanceled);
      }
    }
    catch (InvalidPathException ignored) {
      // Paths.get() throws sometimes
    }
  }
  VFileCreateEvent event = new VFileCreateEvent(null, parent, childName, attributes.isDirectory(), attributes, symlinkTarget, true, children);
  myEvents.add(event);
}
 
Example 12
Source Project: intellij   Source File: TransitiveClosureClassFileFinder.java    License: Apache License 2.0 6 votes vote down vote up
private static void maybeRefreshJars(Collection<File> missingJars, AtomicBoolean pendingRefresh) {
  // We probably need to refresh the virtual file system to find these files, but we can't refresh
  // here because we're in a read action. We also can't use the async refreshIoFiles since it
  // still tries to refresh the IO files synchronously. A global async refresh can't find new
  // files in the ObjFS since we're not watching it.
  // We need to do our own asynchronous refresh, and guard it with a flag to prevent the event
  // queue from overflowing.
  if (!missingJars.isEmpty() && !pendingRefresh.getAndSet(true)) {
    ApplicationManager.getApplication()
        .invokeLater(
            () -> {
              LocalFileSystem.getInstance().refreshIoFiles(missingJars);
              pendingRefresh.set(false);
            },
            ModalityState.NON_MODAL);
  }
}
 
Example 13
Source Project: azure-devops-intellij   Source File: TFSRollbackEnvironmentTest.java    License: MIT License 6 votes vote down vote up
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    PowerMockito.mockStatic(CommandUtils.class, LocalFileSystem.class, ServiceManager.class, TfsFileUtil.class);

    when(mockTFSVcs.getServerContext(anyBoolean())).thenReturn(mockServerContext);
    when(ServiceManager.getService(eq(mockProject), any())).thenReturn(new ClassicTfvcClient(mockProject));
    when(LocalFileSystem.getInstance()).thenReturn(mockLocalFileSystem);
    when(TfsFileUtil.createLocalPath(any(String.class))).thenCallRealMethod();
    when(TfsFileUtil.createLocalPath(any(FilePath.class))).thenCallRealMethod();
    when(TfsFileUtil.getPathItem(any(TfsPath.class))).thenCallRealMethod();
    when(filePath1.getPath()).thenReturn("/path/to/file1");
    when(filePath2.getPath()).thenReturn("/path/to/file2");
    when(filePath3.getPath()).thenReturn("/path/to/file3");
    exceptions = new ArrayList<>();

    rollbackEnvironment = new TFSRollbackEnvironment(mockTFSVcs, mockProject);
}
 
Example 14
@Override
protected void setUp() throws Exception {
    super.setUp();
    File[] mavenArtifacts = getMavenArtifacts(CAMEL_JSONPATH_MAVEN_ARTIFACT);
    for (File file : mavenArtifacts) {
        final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
        final LibraryTable projectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(getModule().getProject());
        ApplicationManager.getApplication().runWriteAction(() -> {
            String name = file.getName();
            // special for camel JARs
            if (name.contains("camel-core")) {
                name = "org.apache.camel:camel-core:2.22.0";
            } else if (name.contains("camel-jsonpath")) {
                name = "org.apache.camel:camel-jsonpath:2.22.0";
            } else {
                // need to fix the name
                if (name.endsWith(".jar")) {
                    name = name.substring(0, name.length() - 4);
                }
                int lastDash = name.lastIndexOf('-');
                name = name.substring(0, lastDash) + ":" + name.substring(lastDash + 1);
                // add bogus groupid
                name = "com.foo:" + name;
            }

            Library library = projectLibraryTable.createLibrary("maven: " + name);
            final Library.ModifiableModel libraryModifiableModel = library.getModifiableModel();
            libraryModifiableModel.addRoot(virtualFile, OrderRootType.CLASSES);
            libraryModifiableModel.commit();
            ModuleRootModificationUtil.addDependency(getModule(), library);
        });
    }

    disposeOnTearDown(ServiceManager.getService(getModule().getProject(), CamelCatalogService.class));
    disposeOnTearDown(ServiceManager.getService(getModule().getProject(), CamelService.class));
    ServiceManager.getService(getModule().getProject(), CamelService.class).setCamelPresent(true);
}
 
Example 15
Source Project: consulo   Source File: DiffPanelImpl.java    License: Apache License 2.0 5 votes vote down vote up
private static DiffHighlighterFactory createHighlighter(FileType contentType, VirtualFile file, VirtualFile otherFile, String path, Project project) {
  VirtualFile baseFile = file;
  if (baseFile == null) baseFile = otherFile;
  if (baseFile == null && path != null) baseFile = LocalFileSystem.getInstance().findFileByPath(path);

  return new DiffHighlighterFactoryImpl(contentType, baseFile, project);
}
 
Example 16
Source Project: consulo   Source File: CoverageEngine.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Qualified name same as in coverage raw project data
 * E.g. java class qualified name by *.class file of some Java class in corresponding source file
 *
 * @param outputFile
 * @param sourceFile
 * @return
 */
@javax.annotation.Nullable
public String getQualifiedName(@Nonnull final File outputFile,
                               @Nonnull final PsiFile sourceFile) {
  final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByIoFile(outputFile);
  if (virtualFile != null) {
    return getQualifiedName(virtualFile, sourceFile);
  }
  return null;
}
 
Example 17
Source Project: consulo   Source File: FileRefresher.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts watching the specified file, which was added before.
 *
 * @param file      a file to watch
 * @param recursive {@code true} if a file should be considered as root
 * @return an object that allows to stop watching the specified file
 */
protected Object watch(VirtualFile file, boolean recursive) {
  VirtualFileSystem fs = file.getFileSystem();
  if (fs instanceof LocalFileSystem) {
    return LocalFileSystem.getInstance().addRootToWatch(file.getPath(), recursive);
  }
  return null;
}
 
Example 18
Source Project: lsp4intellij   Source File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static VirtualFile virtualFileFromURI(String uri) {
    try {
        return LocalFileSystem.getInstance().findFileByIoFile(new File(new URI(sanitizeURI(uri))));
    } catch (URISyntaxException e) {
        LOG.warn(e);
        return null;
    }
}
 
Example 19
@NotNull
protected Document getTestData(String testDataPath) {
  File dataFile = PantsTestUtils.findTestPath(testDataPath);
  VirtualFile dataVirtualFile = LocalFileSystem.getInstance().findFileByPath(dataFile.getPath());
  assertNotNull(dataVirtualFile);
  Document dataDocument = FileDocumentManager.getInstance().getDocument(dataVirtualFile);
  assertNotNull(dataDocument);
  return dataDocument;
}
 
Example 20
Source Project: intellij-pants-plugin   Source File: FastpassUpdater.java    License: 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 21
Source Project: lsp4intellij   Source File: FileUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@PrepareForTest(LocalFileSystem.class)
@Test
public void testVirtualFileFromURINull() {
  PowerMockito.mockStatic(LocalFileSystem.class);
  PowerMockito.when(LocalFileSystem.getInstance()).thenThrow(URISyntaxException.class);

  Assert.assertNull(FileUtils.virtualFileFromURI("foobar"));
}
 
Example 22
Source Project: neovim-intellij-complete   Source File: EmbeditorUtil.java    License: MIT License 5 votes vote down vote up
@Nullable
public static VirtualFile findVirtualFile(@NotNull final File file) {
    return ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() {
        @Nullable
        @Override
        public VirtualFile compute() {
            return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
        }
    });
}
 
Example 23
Source Project: intellij-pants-plugin   Source File: PantsMakeBeforeRun.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This function parses Pants output against known file and tag,
 * and returns (file, line number, column number)
 * encapsulated in `ParseResult` object if the output contains valid information.
 *
 * @param line original Pants output
 * @param tag  known tag. e.g. [error]
 * @return `ParseResult` instance
 */
public static Optional<ParseResult> parseErrorLocation(String line, String tag) {
  if (!line.contains(tag)) {
    return Optional.empty();
  }

  String[] splitByColon = line.split(":");
  if (splitByColon.length < 3) {
    return Optional.empty();
  }

  try {
    // filePath path is between tag and first colon
    String filePath = splitByColon[0].substring(splitByColon[0].indexOf(tag) + tag.length()).trim();
    VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(filePath);
    if (virtualFile == null) {
      return Optional.empty();
    }
    // line number is between first and second colon
    int lineNumber = Integer.parseInt(splitByColon[1]);
    // column number is between second and third colon
    int columnNumber = Integer.parseInt(splitByColon[2]);
    return Optional.of(new ParseResult(virtualFile, lineNumber, columnNumber));
  }
  catch (NumberFormatException e) {
    return Optional.empty();
  }
}
 
Example 24
@Override
public void setUp() throws Exception {
  assumeThat(gradleVersion, versionMatcherRule.getMatcher());
  myJdkHome = IdeaTestUtil.requireRealJdkHome();
  super.setUp();
  WriteAction.runAndWait(() -> {
    Sdk oldJdk = ProjectJdkTable.getInstance().findJdk(GRADLE_JDK_NAME);
    if (oldJdk != null) {
      ProjectJdkTable.getInstance().removeJdk(oldJdk);
    }
    VirtualFile jdkHomeDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(myJdkHome));
    JavaSdk javaSdk = JavaSdk.getInstance();
    SdkType javaSdkType = javaSdk == null ? SimpleJavaSdkType.getInstance() : javaSdk;
    Sdk jdk = SdkConfigurationUtil.setupSdk(new Sdk[0], jdkHomeDir, javaSdkType, true, null, GRADLE_JDK_NAME);
    assertNotNull("Cannot create JDK for " + myJdkHome, jdk);
    ProjectJdkTable.getInstance().addJdk(jdk);
  });
  myProjectSettings = new GradleProjectSettings().withQualifiedModuleNames();
  System.setProperty(ExternalSystemExecutionSettings.REMOTE_PROCESS_IDLE_TTL_IN_MS_KEY, String.valueOf(GRADLE_DAEMON_TTL_MS));
  PathAssembler.LocalDistribution distribution = configureWrapper();

  List<String> allowedRoots = new ArrayList<>();
  collectAllowedRoots(allowedRoots, distribution);
  if (!allowedRoots.isEmpty()) {
    VfsRootAccess.allowRootAccess(myTestFixture.getTestRootDisposable(), ArrayUtil.toStringArray(allowedRoots));
  }
}
 
Example 25
Source Project: consulo   Source File: ScratchFileServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public VirtualFile findFile(@Nonnull RootType rootType, @Nonnull String pathName, @Nonnull Option option) throws IOException {
  ApplicationManager.getApplication().assertReadAccessAllowed();

  String fullPath = getRootPath(rootType) + "/" + pathName;
  if (option != Option.create_new_always) {
    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(fullPath);
    if (file != null && !file.isDirectory()) return file;
    if (option == Option.existing_only) return null;
  }
  String ext = PathUtil.getFileExtension(pathName);
  String fileNameExt = PathUtil.getFileName(pathName);
  String fileName = StringUtil.trimEnd(fileNameExt, ext == null ? "" : "." + ext);
  AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass());
  try {
    VirtualFile dir = VfsUtil.createDirectories(PathUtil.getParentPath(fullPath));
    if (option == Option.create_new_always) {
      return VfsUtil.createChildSequent(LocalFileSystem.getInstance(), dir, fileName, StringUtil.notNullize(ext));
    }
    else {
      return dir.createChildData(LocalFileSystem.getInstance(), fileNameExt);
    }
  }
  finally {
    token.finish();
  }
}
 
Example 26
Source Project: consulo   Source File: TestsLocationProviderUtil.java    License: Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private static VirtualFile getByFullPath(String filePath) {
  final VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(filePath);
  if (fileByPath != null) {
    return fileByPath;
  }
  // if we are in UnitTest mode probably TempFileSystem is used instead of LocalFileSystem
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    return TempFileSystem.getInstance().findFileByPath(filePath);
  }
  return null;
}
 
Example 27
Source Project: consulo   Source File: PersistentFSTest.java    License: Apache License 2.0 5 votes vote down vote up
public void testAccessingFileByID() throws Exception {
  File dir = createTempDirectory();
  File file = new File(dir, "test.txt");
  assertTrue(file.createNewFile());

  VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
  assertNotNull(vFile);

  int id = ((VirtualFileWithId)vFile).getId();

  assertSame(vFile, PersistentFS.getInstance().findFileById(id));
  vFile.delete(this);

  assertNull(PersistentFS.getInstance().findFileById(id));
}
 
Example 28
@Test
public void testRestClientAnnotationMissingForInterface() throws Exception {
	ApplicationManager.getApplication().invokeAndWait(() -> {
		Module module = getModule("rest-client-quickstart.main");
		MicroProfileJavaDiagnosticsParams params = new MicroProfileJavaDiagnosticsParams();
		VirtualFile javaFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(ModuleUtilCore.getModuleDirPath(module) + "/src/main/java/org/acme/restclient/MyService.java");
		String uri = VfsUtilCore.virtualToIoFile(javaFile).toURI().toString();

		params.setUris(Arrays.asList(uri));
		params.setDocumentFormat(DocumentFormat.Markdown);

		Diagnostic d = d(2, 17, 26,
				"The interface `MyService` does not have the @RegisterRestClient annotation. The 1 fields references will not be injected as CDI beans.",
				DiagnosticSeverity.Warning, MicroProfileRestClientConstants.DIAGNOSTIC_SOURCE,
				MicroProfileRestClientErrorCode.RegisterRestClientAnnotationMissing);

		assertJavaDiagnostics(params, utils, //
				d);

	/*String uri = javaFile.getLocation().toFile().toURI().toString();
	MicroProfileJavaCodeActionParams codeActionParams = createCodeActionParams(uri, d);
	assertJavaCodeAction(codeActionParams, utils, //
			ca(uri, "Insert @RegisterRestClient", d, //
					te(0, 28, 2, 0,
							"\r\n\r\nimport org.eclipse.microprofile.rest.client.inject.RegisterRestClient;\r\n\r\[email protected]\r\n")));*/
	});
}
 
Example 29
Source Project: floobits-intellij   Source File: FloobitsApplication.java    License: Apache License 2.0 5 votes vote down vote up
private Project getProject(String path) {
    ProjectManager pm = ProjectManager.getInstance();
    Project[] openProjects = pm.getOpenProjects();
    for (Project project : openProjects) {
        if (path.equals(project.getBasePath())) {
            return project;
        }
    }
    VirtualFile file = LocalFileSystem.getInstance().findFileByIoFile(new File(path));
    Project openedProject;
    if (ProjectAttachProcessor.canAttachToProject() && file != null) {
        openedProject = PlatformProjectOpenProcessor.doOpenProject(file, null, false, -1, null, false);
    } else {
        openedProject = ProjectUtil.openOrImport(path, null, false);
    }
    if (openedProject == null) {
        try {
            String projectFilePath = ".idea/misc.xml";
            if (path.endsWith(projectFilePath)) {
                Flog.error("Attempted to open the project misc.xml file instead of the directory.");
                path = path.replace(projectFilePath, "");
            }
            openedProject = ProjectManager.getInstance().loadAndOpenProject(path);
        } catch (Throwable e) {
            Flog.error(e);
            API.uploadCrash(null, null, e);
            return null;
        }
    }
    // This is something Intellij does when a user opens a project from the menu:
    FileChooserUtil.setLastOpenedFile(openedProject, file);
    return openedProject;
}
 
Example 30
Source Project: intellij   Source File: TestFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public VirtualFile findFile(String filePath) {
  VirtualFile vf = TempFileSystem.getInstance().findFileByPath(filePath);
  if (vf != null) {
    return vf;
  }
  File file = new File(filePath);
  if (file.isAbsolute()) {
    // try looking for a physical file
    return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
  }
  filePath = makePathRelativeToTestFixture(filePath);
  return tempDirTestFixture.getFile(filePath);
}