com.intellij.openapi.vfs.JarFileSystem Java Examples

The following examples show how to use com.intellij.openapi.vfs.JarFileSystem. 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: 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 #2
Source File: RoboVmSdkType.java    From robovm-idea with GNU General Public License v2.0 6 votes vote down vote up
public void setupSdkRoots(Sdk sdk, Sdk jdk) {
    SdkModificator sdkModificator = sdk.getSdkModificator();
    sdkModificator.removeAllRoots();

    // add all class and source jars from the SDK lib/ folder
    for(File file: RoboVmPlugin.getSdkLibraries()) {
        VirtualFile virtualFile = JarFileSystem.getInstance().findLocalVirtualFileByPath(file.getAbsolutePath());
        sdkModificator.addRoot(virtualFile, file.getName().endsWith("-sources.jar")?  OrderRootType.SOURCES: OrderRootType.CLASSES);
    }

    // set the JDK version as the version string, otherwise
    // IDEA gets angry
    sdkModificator.setVersionString(jdk.getVersionString());

    // set the home path, we check this in createSdkIfNotExists
    sdkModificator.setHomePath(RoboVmPlugin.getSdkHome().getAbsolutePath());

    // commit changes and let IDEA handle the rest
    sdkModificator.commitChanges();
}
 
Example #3
Source File: SourceJarGenerator.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
public static void attachSourceJar(@NotNull File sourceJar, @NotNull Collection<? extends Library> libraries) {
  VirtualFile srcFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(sourceJar);
  if (srcFile == null) return;

  VirtualFile jarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(srcFile);
  if (jarRoot == null) return;

  WriteAction.run(() -> {
    for (Library library : libraries) {
      Library.ModifiableModel model = library.getModifiableModel();
      List<VirtualFile> alreadyExistingFiles = Arrays.asList(model.getFiles(OrderRootType.SOURCES));

      if (!alreadyExistingFiles.contains(jarRoot)) {
        model.addRoot(jarRoot, OrderRootType.SOURCES);
      }
      model.commit();
    }
  });
}
 
Example #4
Source File: MetadataContainerInfo.java    From intellij-spring-assistant with MIT License 5 votes vote down vote up
private static VirtualFile getContainerFile(VirtualFile fileContainer) {
  if (fileContainer.getFileType() == ARCHIVE) {
    return requireNonNull(JarFileSystem.getInstance().getLocalVirtualFileFor(fileContainer));
  } else {
    return fileContainer;
  }
}
 
Example #5
Source File: ArchiveUtil.java    From weex-language-support with MIT License 5 votes vote down vote up
public static VirtualFile getFileFromArchive(String name) {
    String[] subPath = name.split("/");
    try {
        URL def = ArchiveUtil.class.getClassLoader().getResource("/");
        if (def != null) {
            String path = URLDecoder.decode(def.getPath(), "utf-8").replace("file:", "");
            String[] temp = path.split("!");
            if (temp.length > 1 && path.toLowerCase().contains(".jar")) {
                path = temp[0];
            }
            VirtualFile root = JarFileSystem.getInstance().findLocalVirtualFileByPath(path);
            if (root == null) {
                root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
            }

            VirtualFile target = root;
            for (String s : subPath) {
                if (target != null) {
                    target = target.findChild(s);
                }
            }
            return target;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #6
Source File: BundledProtobufRootsProvider.java    From protobuf-jetbrains-plugin with Apache License 2.0 5 votes vote down vote up
private Optional<VirtualFile> tryClasspath() {
    String classpath = System.getProperty("java.class.path");
    String separator = System.getProperty("path.separator");
    Iterable<String> classpathEntries = Splitter.on(separator).split(classpath);
    return StreamSupport.stream(classpathEntries.spliterator(), false)
            .filter(entry -> entry.contains(PREFIX))
            .filter(entry -> entry.contains(SUFFIX))
            .findAny()
            .map(protobufSourcesJar -> {
                JarFileSystem instance = JarFileSystem.getInstance();
                return instance.findLocalVirtualFileByPath(protobufSourcesJar);
            });
}
 
Example #7
Source File: BundledProtobufRootsProvider.java    From protobuf-jetbrains-plugin with Apache License 2.0 5 votes vote down vote up
private Optional<VirtualFile> tryPluginLibFolder() {
    IdeaPluginDescriptor plugin = Objects.requireNonNull(PluginManager.getPlugin(PluginId.getId(PLUGIN_ID)));
    return ((IdeaPluginDescriptorImpl) plugin).getClassPath().stream()
            .filter(entry -> entry.getName().contains(PREFIX))
            .filter(entry -> entry.getName().contains(SUFFIX))
            .findAny()
            .map(protobufSourcesJarUrl -> {
                JarFileSystem instance = JarFileSystem.getInstance();
                return instance.findLocalVirtualFileByPath(protobufSourcesJarUrl.getPath());
            });
}
 
Example #8
Source File: BlazeSourceJarNavigationPolicy.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static VirtualFile getSourceJarRoot(
    Project project, ArtifactLocationDecoder decoder, ArtifactLocation sourceJar) {
  File sourceJarFile = JarCache.getInstance(project).getCachedSourceJar(decoder, sourceJar);
  if (sourceJar == null) {
    return null;
  }
  VirtualFile vfsFile = VfsUtils.resolveVirtualFile(sourceJarFile, /* refreshIfNeeded= */ true);
  if (vfsFile == null) {
    return null;
  }
  return JarFileSystem.getInstance().getJarRootForLocalFile(vfsFile);
}
 
Example #9
Source File: DecompileAndAttachAction.java    From decompile-and-attach with MIT License 5 votes vote down vote up
private void process(Project project, String baseDirPath, VirtualFile sourceVF, ProgressIndicator indicator, double fractionStep) {
    indicator.setText("Decompiling '" + sourceVF.getName() + "'");
    JarFileSystem jarFileInstance = JarFileSystem.getInstance();
    VirtualFile jarRoot = jarFileInstance.getJarRootForLocalFile(sourceVF);
    if (jarRoot == null) {
        jarRoot = jarFileInstance.getJarRootForLocalFile(jarFileInstance.getLocalVirtualFileFor(sourceVF));
    }
    try {
        File tmpJarFile = FileUtil.createTempFile("decompiled", "tmp");
        Pair<String, Set<String>> result;
        try (JarOutputStream jarOutputStream = createJarOutputStream(tmpJarFile)) {
            result = processor(jarOutputStream, indicator).apply(jarRoot);
        }
        indicator.setFraction(indicator.getFraction() + (fractionStep * 70 / 100));
        indicator.setText("Attaching decompiled sources for '" + sourceVF.getName() + "'");
        result.second.forEach((failedFile) -> new Notification("DecompileAndAttach", "Decompilation problem",
                "fernflower could not decompile class " + failedFile, WARNING).notify(project));
        File resultJar = copy(project, baseDirPath, sourceVF, tmpJarFile, result.first);
        attach(project, sourceVF, resultJar);
        indicator.setFraction(indicator.getFraction() + (fractionStep * 30 / 100));
        FileUtil.delete(tmpJarFile);
    } catch (Exception e) {
        if (!(e instanceof ProcessCanceledException)) {
            new Notification("DecompileAndAttach", "Jar lib couldn't be decompiled", e.getMessage(), ERROR).notify(project);
        }
        Throwables.propagate(e);
    }
}
 
Example #10
Source File: DecompileAndAttachAction.java    From decompile-and-attach with MIT License 5 votes vote down vote up
private void attach(final Project project, final VirtualFile sourceVF, File resultJar) {
    ApplicationManager.getApplication().invokeAndWait(() -> {
        VirtualFile resultJarVF = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(resultJar);
        checkNotNull(resultJarVF, "could not find Virtual File of %s", resultJar.getAbsolutePath());
        VirtualFile resultJarRoot = JarFileSystem.getInstance().getJarRootForLocalFile(resultJarVF);
        VirtualFile[] roots = PathUIUtils.scanAndSelectDetectedJavaSourceRoots(null,
                new VirtualFile[] {resultJarRoot});
        new WriteCommandAction<Void>(project) {

            @Override
            protected void run(@NotNull Result<Void> result) throws Throwable {
                final Module currentModule = ProjectRootManager.getInstance(project).getFileIndex()
                        .getModuleForFile(sourceVF, false);

                checkNotNull(currentModule, "could not find current module");
                Optional<Library> moduleLib = findModuleDependency(currentModule, sourceVF);
                checkState(moduleLib.isPresent(), "could not find library in module dependencies");
                Library.ModifiableModel model = moduleLib.get().getModifiableModel();
                for (VirtualFile root : roots) {
                    model.addRoot(root, OrderRootType.SOURCES);
                }
                model.commit();

                new Notification("DecompileAndAttach", "Jar Sources Added", "decompiled sources " + resultJar.getName()
                        + " where added successfully to dependency of a module '" + currentModule.getName() + "'",
                        INFORMATION).notify(project);
            }
        }.execute();
    } , ModalityState.NON_MODAL);
}
 
Example #11
Source File: ToolDelegate.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
default VirtualFile getJarFile(File file) {
    VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
    return virtualFile != null? JarFileSystem.getInstance().getJarRootForLocalFile(virtualFile):null;
}
 
Example #12
Source File: PsiBasedClassFileFinder.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static VirtualFile getJarRootForLocalFile(VirtualFile file) {
  return ApplicationManager.getApplication().isUnitTestMode()
      ? TempFileSystem.getInstance().findFileByPath(file.getPath() + JarFileSystem.JAR_SEPARATOR)
      : JarFileSystem.getInstance().getJarRootForLocalFile(file);
}
 
Example #13
Source File: TransitiveClosureClassFileFinder.java    From intellij with Apache License 2.0 4 votes vote down vote up
private static VirtualFile getJarRootForLocalFile(VirtualFile file) {
  return ApplicationManager.getApplication().isUnitTestMode()
      ? TempFileSystem.getInstance().findFileByPath(file.getPath() + JarFileSystem.JAR_SEPARATOR)
      : JarFileSystem.getInstance().getJarRootForLocalFile(file);
}
 
Example #14
Source File: BlazeAndroidModel.java    From intellij with Apache License 2.0 4 votes vote down vote up
public static boolean testIsClassFileOutOfDate(
    @NotNull Project project, @NotNull String fqcn, @NotNull VirtualFile classFile) {
  VirtualFile sourceFile =
      ApplicationManager.getApplication()
          .runReadAction(
              (Computable<VirtualFile>)
                  () -> {
                    PsiClass psiClass =
                        JavaPsiFacade.getInstance(project)
                            .findClass(fqcn, GlobalSearchScope.projectScope(project));
                    if (psiClass == null) {
                      return null;
                    }
                    PsiFile psiFile = psiClass.getContainingFile();
                    if (psiFile == null) {
                      return null;
                    }
                    return psiFile.getVirtualFile();
                  });
  if (sourceFile == null) {
    return false;
  }

  // Edited but not yet saved?
  if (FileDocumentManager.getInstance().isFileModified(sourceFile)) {
    return true;
  }

  long sourceTimeStamp = sourceFile.getTimeStamp();
  long buildTimeStamp = classFile.getTimeStamp();

  if (classFile.getFileSystem() instanceof JarFileSystem) {
    JarFileSystem jarFileSystem = (JarFileSystem) classFile.getFileSystem();
    VirtualFile jarFile = jarFileSystem.getVirtualFileForJar(classFile);
    if (jarFile != null) {
      if (jarFile.getFileSystem() instanceof LocalFileSystem) {
        // The virtual file timestamp could be stale since we don't watch this file.
        buildTimeStamp = VfsUtilCore.virtualToIoFile(jarFile).lastModified();
      } else {
        buildTimeStamp = jarFile.getTimeStamp();
      }
    }
  }

  if (sourceTimeStamp > buildTimeStamp) {
    // It's possible that the source file's timestamp has been updated, but the content remains
    // same. In this case, blaze will not try to rebuild the jar, we have to also check whether
    // the user recently clicked the build button. So they can at least manually get rid of the
    // error.
    Long projectBuildTimeStamp = BlazeBuildService.getLastBuildTimeStamp(project);
    return projectBuildTimeStamp == null || sourceTimeStamp > projectBuildTimeStamp;
  }

  return false;
}