com.intellij.openapi.vfs.LocalFileSystem Java Examples

The following examples show how to use com.intellij.openapi.vfs.LocalFileSystem. 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: PantsMakeMessageTest.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: IntelliJAndroidSdk.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #3
Source File: HaxeClasspathEntry.java    From intellij-haxe with 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 #4
Source File: ExternalSystemTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@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 File: TransitiveClosureClassFileFinder.java    From intellij with 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 #6
Source File: SourcesLocator.java    From needsmoredojo with 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 #7
Source File: ClearAllAction.java    From leetcode-editor with 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 File: AbstractUploadCloudActionTest.java    From markdown-image-kit with 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 #9
Source File: IdeaLightweightExtension.java    From p4ic4idea with 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 #10
Source File: JavaGetImportCandidatesHandler.java    From ijaas with 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 #11
Source File: TFSRollbackEnvironmentTest.java    From azure-devops-intellij with 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 #12
Source File: GaugeConsoleProperties.java    From Intellij-Plugin with 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 #13
Source File: VfsEventGenerationHelper.java    From consulo with 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 #14
Source File: MavenImportingTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a new module into the test project from existing in memory POM.
 *
 * @param name the new module name
 * @param xml the project POM
 * @return the created module
 */
protected Module createMavenModule(String name, String xml) throws Exception {
  Module module = myTestFixture.getModule();
  File moduleDir = new File(module.getModuleFilePath()).getParentFile();
  VirtualFile pomFile = createPomFile(LocalFileSystem.getInstance().findFileByIoFile(moduleDir), xml);
  importProject(pomFile);
  Module[] modules = ModuleManager.getInstance(myTestFixture.getProject()).getModules();
  if (modules.length > 0) {
    module = modules[modules.length - 1];
    setupJdkForModule(module.getName());
  }
  return module;
}
 
Example #15
Source File: HaxeFileUtil.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
/**
 * Quick 'n' dirty url fixup, if necessary.
 *
 * @param url
 * @return
 */
@Nullable
public static String fixUrl(@Nullable String url) {
  if (null == url || url.isEmpty())
    return url;
  return url.startsWith(LocalFileSystem.PROTOCOL)
         ? url
         : VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, url);
}
 
Example #16
Source File: FileUtils.java    From leetcode-editor with Apache License 2.0 5 votes vote down vote up
public static void openFileEditorAndSaveState(File file, Project project, Question question){
    ApplicationManager.getApplication().invokeAndWait(()->{
        VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
        OpenFileDescriptor descriptor = new OpenFileDescriptor(project, vf);
        FileEditorManager.getInstance(project).openTextEditor(descriptor, false);
        LeetcodeEditor leetcodeEditor = ProjectConfig.getInstance(project).getDefEditor(vf.getPath());
        leetcodeEditor.setQuestionId(question.getQuestionId());
    });
}
 
Example #17
Source File: DartTestLocationProviderZ.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
@Override
public List<Location> getLocation(@NotNull String protocol,
                                  @NotNull String path,
                                  @NotNull Project project,
                                  @NotNull GlobalSearchScope scope) {
  // see DartTestEventsConverterZ.addLocationHint()
  // path is like /Users/x/projects/foo/test/foo_test.dart,35,12,["main tests","calculate_fail"]

  final int commaIdx1 = path.indexOf(',');
  final int commaIdx2 = path.indexOf(',', commaIdx1 + 1);
  final int commaIdx3 = path.indexOf(',', commaIdx2 + 1);
  if (commaIdx3 < 0) return NONE;

  final String filePath = path.substring(0, commaIdx1);
  final int line = Integer.parseInt(path.substring(commaIdx1 + 1, commaIdx2));
  final int column = Integer.parseInt(path.substring(commaIdx2 + 1, commaIdx3));
  final String names = path.substring(commaIdx3 + 1);

  final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(filePath);
  final PsiFile psiFile = file == null ? null : PsiManager.getInstance(project).findFile(file);
  if (!(psiFile instanceof DartFile)) return NONE;

  if (line >= 0 && column >= 0) {
    final Location<PsiElement> location = getLocationByLineAndColumn(psiFile, line, column);
    if (location != null) {
      return Collections.singletonList(location);
    }
  }

  final List<String> nodes = pathToNodes(names);
  if (nodes.isEmpty()) {
    return Collections.singletonList(new PsiLocation<PsiElement>(psiFile));
  }

  return getLocationByGroupAndTestNames(psiFile, nodes);
}
 
Example #18
Source File: SdkConfigurationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static VirtualFile getSuggestedSdkPath(SdkType sdkType) {
  Collection<String> paths = sdkType.suggestHomePaths();
  if(paths.isEmpty()) {
    return null;
  }

  for (String path : paths) {
    VirtualFile maybeSdkHomePath = LocalFileSystem.getInstance().findFileByPath(path);
    if(maybeSdkHomePath != null) {
      return maybeSdkHomePath;
    }
  }
  return null;
}
 
Example #19
Source File: FileExperimentLoader.java    From intellij with Apache License 2.0 5 votes vote down vote up
private void doInitialize() {
  LocalFileSystem fileSystem = LocalFileSystem.getInstance();
  fileSystem.addRootToWatch(file.getPath(), /* watchRecursively= */ false);
  // We need to look up the file in the VFS or else we don't receive events about it. This works
  // even if the returned VirtualFile is null (because the experiments file doesn't exist yet).
  fileSystem.findFileByIoFile(file);
  ApplicationManager.getApplication()
      .getMessageBus()
      .connect()
      .subscribe(VirtualFileManager.VFS_CHANGES, new RefreshExperimentsListener());
}
 
Example #20
Source File: ScratchFileServiceImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public Set<VirtualFile> getAdditionalRootsToIndex() {
  ScratchFileService instance = ScratchFileService.getInstance();
  LocalFileSystem fileSystem = LocalFileSystem.getInstance();
  HashSet<VirtualFile> result = new HashSet<>();
  for (RootType rootType : RootType.getAllRootTypes()) {
    if (rootType.isHidden()) continue;
    ContainerUtil.addIfNotNull(result, fileSystem.findFileByPath(instance.getRootPath(rootType)));
  }
  return result;
}
 
Example #21
Source File: WebCoreResourcePathRootsProvider.java    From protobuf-jetbrains-plugin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public VirtualFile[] getSourceRoots(Module module, ProtoPsiFileRoot psiFileRoot) {
    try {
        if (GET_INSTANCE != null && GET_RESOURCE_ROOTS != null) {
            Object configurationInstance = GET_INSTANCE.invoke(null, module.getProject());
            if (configurationInstance != null) {
                List<VirtualFile> result = new ArrayList<>();
                MultiMap<String, String> resourceRoots = (MultiMap<String, String>) GET_RESOURCE_ROOTS.invoke(configurationInstance);
                for (Map.Entry<String, Collection<String>> entry : resourceRoots.entrySet()) {
                    for (String uri : entry.getValue()) {
                        if (!Strings.isNullOrEmpty(uri) && uri.startsWith("file://")) {
                            String path = uri.substring(7);
                            VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
                            if (file != null && file.isDirectory()) {
                                result.add(file);
                            }
                        }
                    }
                }
                return result.toArray(new VirtualFile[0]);
            }
        }
    } catch (Exception e) {
        LOGGER.warn("Could not get source roots for WebCore IDE", e);
    }
    return new VirtualFile[0];
}
 
Example #22
Source File: AbstractVcsHelperImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static DiffContent getContentForVersion(final VcsFileRevision version, final File file) throws IOException, VcsException {
  VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(file);
  if (vFile != null && (version instanceof CurrentRevision) && !vFile.getFileType().isBinary()) {
    return new DocumentContent(FileDocumentManager.getInstance().getDocument(vFile), vFile.getFileType());
  }
  else {
    return new SimpleContent(VcsHistoryUtil.loadRevisionContentGuessEncoding(version, vFile, null),
                             FileTypeManager.getInstance().getFileTypeByFileName(file.getName()));
  }
}
 
Example #23
Source File: MavenJavaDiagnosticsMicroProfileHealthTest.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testHealthAnnotationMissing() throws Exception {

	Module module = createMavenModule("microprofile-health-quickstart", new File("projects/maven/microprofile-health-quickstart"));
	MicroProfileJavaDiagnosticsParams diagnosticsParams = new MicroProfileJavaDiagnosticsParams();
	VirtualFile javaFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(ModuleUtilCore.getModuleDirPath(module) + "/src/main/java/org/acme/health/ImplementHealthCheck.java");
	String uri = VfsUtilCore.virtualToIoFile(javaFile).toURI().toString();
	diagnosticsParams.setUris(Arrays.asList(uri));
	diagnosticsParams.setDocumentFormat(DocumentFormat.Markdown);

	Diagnostic d = d(5, 13, 33,
			"The class `org.acme.health.ImplementHealthCheck` implementing the HealthCheck interface should use the @Liveness, @Readiness, or @Health annotation.",
			DiagnosticSeverity.Warning, MicroProfileHealthConstants.DIAGNOSTIC_SOURCE,
			MicroProfileHealthErrorCode.HealthAnnotationMissing);
	assertJavaDiagnostics(diagnosticsParams, utils, //
			d);

	/*MicroProfileJavaCodeActionParams codeActionParams = createCodeActionParams(uri, d);
	assertJavaCodeAction(codeActionParams, utils, //
			ca(uri, "Insert @Health", d, //
					te(2, 0, 5, 0, "import org.eclipse.microprofile.health.Health;\r\n" + //
							"import org.eclipse.microprofile.health.HealthCheck;\r\n" + //
							"import org.eclipse.microprofile.health.HealthCheckResponse;\r\n\r\n" + //
							"@Health\r\n")),
			ca(uri, "Insert @Liveness", d, //
					te(3, 59, 5, 0, "\r\n" + //
							"import org.eclipse.microprofile.health.Liveness;\r\n\r\n" + //
							"@Liveness\r\n")), //
			ca(uri, "Insert @Readiness", d, //
					te(3, 59, 5, 0, "\r\n" + //
							"import org.eclipse.microprofile.health.Readiness;\r\n\r\n" + //
							"@Readiness\r\n")) //
	);*/
}
 
Example #24
Source File: FileTreeStructure.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Object getParentElement(Object element) {
  if (element instanceof FileElement) {

    final FileElement fileElement = (FileElement)element;

    final VirtualFile elementFile = getValidFile(fileElement);
    if (elementFile != null && myRootElement.getFile() != null && myRootElement.getFile().equals(elementFile)) {
      return null;
    }

    final VirtualFile parentElementFile = getValidFile(fileElement.getParent());

    if (elementFile != null && parentElementFile != null) {
      final VirtualFile parentFile = elementFile.getParent();
      if (parentElementFile.equals(parentFile)) return fileElement.getParent();
    }

    VirtualFile file = fileElement.getFile();
    if (file == null) return null;
    VirtualFile parent = file.getParent();
    if (parent != null && parent.getFileSystem() instanceof ArchiveFileSystem && parent.getParent() == null) {
      // parent of jar contents should be local jar file
      String localPath = parent.getPath().substring(0,
                                                    parent.getPath().length() - ArchiveFileSystem.ARCHIVE_SEPARATOR.length());
      parent = LocalFileSystem.getInstance().findFileByPath(localPath);
    }

    if (parent != null && parent.isValid() && parent.equals(myRootElement.getFile())) {
      return myRootElement;
    }

    if (parent == null) {
      return myRootElement;
    }
    return new FileElement(parent, parent.getName());
  }
  return null;
}
 
Example #25
Source File: CamelJSonPathAnnotatorTestIT.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: BazelTestFields.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns the file or directory containing the tests to run, or null if it doesn't exist.
 */
@Nullable
public VirtualFile getFile() {
  final String path = getEntryFile();
  if (path == null) return null;
  return LocalFileSystem.getInstance().findFileByPath(path);
}
 
Example #27
Source File: Location.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public XSourcePosition getXSourcePosition() {
  final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);

  if (file == null) {
    return null;
  }
  return XSourcePositionImpl.create(file, line - 1, column - 1);
}
 
Example #28
Source File: BazelTestRunner.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Attempt to find a local Dart file corresponding to a script in Observatory.
 */
@Nullable
@Override
protected VirtualFile findLocalFile(@NotNull final String uri) {
  // Get the workspace directory name provided by the test harness.
  final String workspaceDirName = connector.getWorkspaceDirName();

  // Verify the returned workspace directory name, we weren't passed a workspace name or if the valid workspace name does not start the
  // uri then return the super invocation of this method. This prevents the unknown URI type from being passed to the analysis server.
  if (StringUtils.isEmpty(workspaceDirName) || !uri.startsWith(workspaceDirName + ":/")) return super.findLocalFile(uri);

  final String pathFromWorkspace = uri.substring(workspaceDirName.length() + 1);

  // For each root in each module, look for a bazel workspace path, if found attempt to compute the VirtualFile, return when found.
  return ApplicationManager.getApplication().runReadAction((Computable<VirtualFile>)() -> {
    for (Module module : DartSdkLibUtil.getModulesWithDartSdkEnabled(getProject())) {
      for (ContentEntry contentEntry : ModuleRootManager.getInstance(module).getContentEntries()) {
        final VirtualFile includedRoot = contentEntry.getFile();
        if (includedRoot == null) continue;

        final String includedRootPath = includedRoot.getPath();
        final int workspaceOffset = includedRootPath.indexOf(workspaceDirName);
        if (workspaceOffset == -1) continue;

        final String pathToWorkspace = includedRootPath.substring(0, workspaceOffset + workspaceDirName.length());
        final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(pathToWorkspace + pathFromWorkspace);
        if (virtualFile != null) {
          return virtualFile;
        }
      }
    }
    return super.findLocalFile(uri);
  });
}
 
Example #29
Source File: GotoFileItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private PsiFileSystemItem getFileByAbsolutePath(@Nonnull String pattern) {
  if (pattern.contains("/") || pattern.contains("\\")) {
    String path = FileUtil.toSystemIndependentName(ChooseByNamePopup.getTransformedPattern(pattern, myModel));
    VirtualFile vFile = LocalFileSystem.getInstance().findFileByPathIfCached(path);
    if (vFile != null) {
      ProjectFileIndex index = ProjectFileIndex.getInstance(myProject);
      if (index.isInContent(vFile) || index.isInLibrary(vFile)) {
        return PsiUtilCore.findFileSystemItem(myProject, vFile);
      }
    }
  }
  return null;
}
 
Example #30
Source File: MavenTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
protected VirtualFile updateSettingsXmlFully(@NonNls @Language("XML") String content) throws IOException {
  File ioFile = new File(myDir, "settings.xml");
  ioFile.createNewFile();
  VirtualFile f = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile);
  setFileContent(f, content, true);
  getMavenGeneralSettings().setUserSettingsFile(f.getPath());
  return f;
}