Java 类com.intellij.util.io.ZipUtil 实例源码

项目:educational-plugin    文件:StudyUtils.java   
public static File getBundledCourseRoot(final String courseName, Class clazz) {
  @NonNls String jarPath = PathUtil.getJarPathForClass(clazz);
  if (jarPath.endsWith(".jar")) {
    final File jarFile = new File(jarPath);
    File pluginBaseDir = jarFile.getParentFile();
    File coursesDir = new File(pluginBaseDir, "courses");

    if (!coursesDir.exists()) {
      if (!coursesDir.mkdir()) {
        LOG.info("Failed to create courses dir");
        return coursesDir;
      }
    }
    try {
      ZipUtil.extract(jarFile, pluginBaseDir, (dir, name) -> name.equals(courseName));
    } catch (IOException e) {
      LOG.info("Failed to extract default course", e);
    }
    return coursesDir;
  }
  return new File(jarPath, "courses");
}
项目:educational-plugin    文件:CCCreateCourseArchive.java   
private static void packCourse(@NotNull final VirtualFile baseDir, String locationDir, String zipName, boolean showMessage) {
  try {
    final File zipFile = new File(locationDir, zipName + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    VirtualFile[] courseFiles = baseDir.getChildren();
    for (VirtualFile file : courseFiles) {
      ZipUtil.addFileOrDirRecursively(zos, null, new File(file.getPath()), file.getName(), null, null);
    }
    zos.close();
    if (showMessage) {
      ApplicationManager.getApplication().invokeLater(
        () -> Messages.showInfoMessage("Course archive was saved to " + zipFile.getPath(),
                                       "Course Archive Was Created Successfully"));

    }
  }
  catch (IOException e1) {
    LOG.error(e1);
  }
}
项目:intellij-ce-playground    文件:PluginDownloader.java   
@Nullable
public static IdeaPluginDescriptorImpl loadDescriptionFromJar(final File file) throws IOException {
  IdeaPluginDescriptorImpl descriptor = PluginManagerCore.loadDescriptorFromJar(file);
  if (descriptor == null) {
    if (file.getName().endsWith(".zip")) {
      final File outputDir = FileUtil.createTempDirectory("plugin", "");
      try {
        ZipUtil.extract(file, outputDir, null);
        final File[] files = outputDir.listFiles();
        if (files != null && files.length == 1) {
          descriptor = PluginManagerCore.loadDescriptor(files[0], PluginManagerCore.PLUGIN_XML);
        }
      }
      finally {
        FileUtil.delete(outputDir);
      }
    }
  }
  return descriptor;
}
项目:intellij-ce-playground    文件:StartupActionScriptManager.java   
public void execute() throws IOException {
  if (!mySource.exists()) {
    // Note, that we can not use LOG at this moment because it throws AssertionError 
    //noinspection HardCodedStringLiteral,UseOfSystemOutOrSystemErr
    System.err.println("Source file " + mySource.getAbsolutePath() + " does not exist for action " + this);
  }
  else if (!canCreateFile(myDestination)) {
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  MessageFormat.format("<html>Cannot unzip {0}<br>to<br>{1}<br>Please, check your access rights on folder <br>{2}",
                                                       mySource.getAbsolutePath(), myDestination.getAbsolutePath(), myDestination),
                                  "Installing Plugin", JOptionPane.ERROR_MESSAGE);
  }
  else {
    try {
      ZipUtil.extract(mySource, myDestination, myFilenameFilter);
    }
    catch(Exception ex) {
      //noinspection CallToPrintStackTrace
      ex.printStackTrace();
      JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                    MessageFormat.format("<html>Failed to extract ZIP file {0}<br>to<br>{1}<br>You may need to re-download the plugin you tried to install.",
                                                         mySource.getAbsolutePath(), myDestination.getAbsolutePath()),
                                    "Installing Plugin", JOptionPane.ERROR_MESSAGE);
    }
  }
}
项目:intellij-ce-playground    文件:AppEngineFacetImporter.java   
@Override
public void resolve(Project project,
                    MavenProject mavenProject,
                    NativeMavenProjectHolder nativeMavenProject,
                    MavenEmbedderWrapper embedder,
                    ResolveContext context) throws MavenProcessCanceledException {
  String version = getVersion(mavenProject);
  if (version != null) {
    List<MavenRemoteRepository> repos = mavenProject.getRemoteRepositories();
    MavenArtifactInfo artifactInfo = new MavenArtifactInfo("com.google.appengine", "appengine-java-sdk", version, "zip", null);
    MavenArtifact artifact = embedder.resolve(artifactInfo, repos);
    File file = artifact.getFile();
    File unpackedSdkPath = new File(file.getParentFile(), "appengine-java-sdk");
    if (file.exists() && !AppEngineSdkUtil.checkPath(FileUtil.toSystemIndependentName(unpackedSdkPath.getAbsolutePath())).isOk()) {
      try {
        ZipUtil.extract(file, unpackedSdkPath, null, false);
      }
      catch (IOException e) {
        MavenLog.LOG.warn("cannot unpack AppEngine SDK", e);
      }
    }
  }
}
项目:intellij-ce-playground    文件:PrepareToDeployAction.java   
private static void makeAndAddLibraryJar(final VirtualFile virtualFile,
                                         final File zipFile,
                                         final String pluginName,
                                         final ZipOutputStream zos,
                                         final Set<String> usedJarNames,
                                         final ProgressIndicator progressIndicator,
                                         final String preferredName) throws IOException {
  File libraryJar = FileUtil.createTempFile(TEMP_PREFIX, JAR_EXTENSION);
  libraryJar.deleteOnExit();
  ZipOutputStream jar = null;
  try {
    jar = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(libraryJar)));
    ZipUtil.addFileOrDirRecursively(jar, libraryJar, VfsUtilCore.virtualToIoFile(virtualFile), "",
                                    createFilter(progressIndicator, FileTypeManager.getInstance()), null);
  }
  finally {
    if (jar != null) jar.close();
  }
  final String jarName =
    getLibraryJarName(virtualFile.getName() + JAR_EXTENSION, usedJarNames, preferredName == null ? null : preferredName + JAR_EXTENSION);
  ZipUtil.addFileOrDirRecursively(zos, zipFile, libraryJar, getZipPath(pluginName, jarName), createFilter(progressIndicator, null), null);
}
项目:intellij-ce-playground    文件:PrepareToDeployAction.java   
private static File jarModulesOutput(@NotNull Set<Module> modules, @Nullable Manifest manifest, final @Nullable String pluginXmlPath) throws IOException {
  File jarFile = FileUtil.createTempFile(TEMP_PREFIX, JAR_EXTENSION);
  jarFile.deleteOnExit();
  ZipOutputStream jarPlugin = null;
  try {
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(jarFile));
    jarPlugin = manifest != null ? new JarOutputStream(out, manifest) : new JarOutputStream(out);
    final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
    final Set<String> writtenItemRelativePaths = new HashSet<String>();
    for (Module module : modules) {
      final VirtualFile compilerOutputPath = CompilerModuleExtension.getInstance(module).getCompilerOutputPath();
      if (compilerOutputPath == null) continue; //pre-condition: output dirs for all modules are up-to-date
      ZipUtil.addDirToZipRecursively(jarPlugin, jarFile, new File(compilerOutputPath.getPath()), "",
                                     createFilter(progressIndicator, FileTypeManager.getInstance()), writtenItemRelativePaths);
    }
    if (pluginXmlPath != null) {
      ZipUtil.addFileToZip(jarPlugin, new File(pluginXmlPath), "/META-INF/plugin.xml", writtenItemRelativePaths,
                           createFilter(progressIndicator, null));
    }
  }
  finally {
    if (jarPlugin != null) jarPlugin.close();
  }
  return jarFile;
}
项目:tools-idea    文件:PluginDownloader.java   
@Nullable
public static IdeaPluginDescriptorImpl loadDescriptionFromJar(final File file) throws IOException {
  IdeaPluginDescriptorImpl descriptor = PluginManagerCore.loadDescriptorFromJar(file);
  if (descriptor == null) {
    if (file.getName().endsWith(".zip")) {
      final File outputDir = FileUtil.createTempDirectory("plugin", "");
      try {
        ZipUtil.extract(file, outputDir, new FilenameFilter() {
          public boolean accept(final File dir, final String name) {
            return true;
          }
        });
        final File[] files = outputDir.listFiles();
        if (files != null && files.length == 1) {
          descriptor = PluginManagerCore.loadDescriptor(files[0], PluginManagerCore.PLUGIN_XML);
        }
      }
      finally {
        FileUtil.delete(outputDir);
      }
    }
  }
  return descriptor;
}
项目:tools-idea    文件:StartupActionScriptManager.java   
public void execute() throws IOException {
  if (!mySource.exists()) {
    //noinspection HardCodedStringLiteral
    System.err.println("Source file " + mySource.getAbsolutePath() + " does not exist for action " + this);
  }
  else if (!canCreateFile(myDestination)) {
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  MessageFormat.format("<html>Cannot unzip {0}<br>to<br>{1}<br>Please, check your access rights on folder <br>{2}",
                                                       mySource.getAbsolutePath(), myDestination.getAbsolutePath(), myDestination),
                                  "Installing Plugin", JOptionPane.ERROR_MESSAGE);
  }
  else {
    try {
      ZipUtil.extract(mySource, myDestination, myFilenameFilter);
    }
    catch(Exception ex) {
      ex.printStackTrace();
      JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                    MessageFormat.format("<html>Failed to extract ZIP file {0}<br>to<br>{1}<br>You may need to re-download the plugin you tried to install.",
                                                         mySource.getAbsolutePath(), myDestination.getAbsolutePath()),
                                    "Installing Plugin", JOptionPane.ERROR_MESSAGE);
    }
  }
}
项目:tools-idea    文件:PrepareToDeployAction.java   
private void makeAndAddLibraryJar(final VirtualFile virtualFile,
                                  final File zipFile,
                                  final String pluginName,
                                  final ZipOutputStream zos,
                                  final Set<String> usedJarNames,
                                  final ProgressIndicator progressIndicator,
                                  final String preferredName) throws IOException {
  File libraryJar = FileUtil.createTempFile(TEMP_PREFIX, JAR_EXTENSION);
  libraryJar.deleteOnExit();
  ZipOutputStream jar = null;
  try {
    jar = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(libraryJar)));
    ZipUtil.addFileOrDirRecursively(jar, libraryJar, VfsUtil.virtualToIoFile(virtualFile), "",
                                    createFilter(progressIndicator, myFileTypeManager), null);
  }
  finally {
    if (jar != null) jar.close();
  }
  final String jarName =
    getLibraryJarName(virtualFile.getName() + JAR_EXTENSION, usedJarNames, preferredName == null ? null : preferredName + JAR_EXTENSION);
  ZipUtil.addFileOrDirRecursively(zos, zipFile, libraryJar, getZipPath(pluginName, jarName), createFilter(progressIndicator, null), null);
}
项目:tools-idea    文件:PrepareToDeployAction.java   
private File preparePluginsJar(Module module, final HashSet<Module> modules) throws IOException {
  final PluginBuildConfiguration pluginModuleBuildProperties = PluginBuildConfiguration.getInstance(module);
  File jarFile = FileUtil.createTempFile(TEMP_PREFIX, JAR_EXTENSION);
  jarFile.deleteOnExit();
  final Manifest manifest = createOrFindManifest(pluginModuleBuildProperties);
  ZipOutputStream jarPlugin = null;
  try {
    jarPlugin = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile)), manifest);
    final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
    final HashSet<String> writtenItemRelativePaths = new HashSet<String>();
    for (Module module1 : modules) {
      final VirtualFile compilerOutputPath = CompilerModuleExtension.getInstance(module1).getCompilerOutputPath();
      if (compilerOutputPath == null) continue; //pre-condition: output dirs for all modules are up-to-date
      ZipUtil.addDirToZipRecursively(jarPlugin, jarFile, new File(compilerOutputPath.getPath()), "",
                                     createFilter(progressIndicator, myFileTypeManager), writtenItemRelativePaths);
    }
    final String pluginXmlPath = pluginModuleBuildProperties.getPluginXmlPath();
    @NonNls final String metaInf = "/META-INF/plugin.xml";
    ZipUtil.addFileToZip(jarPlugin, new File(pluginXmlPath), metaInf, writtenItemRelativePaths, createFilter(progressIndicator, null));
  }
  finally {
    if (jarPlugin != null) jarPlugin.close();
  }
  return jarFile;
}
项目:consulo    文件:PluginDownloader.java   
public static void install(final File fromFile, final String pluginName, boolean deleteFromFile) throws IOException {
  // add command to unzip file to the plugins path
  String unzipPath;
  if (ZipUtil.isZipContainsFolder(fromFile)) {
    unzipPath = PathManager.getInstallPluginsPath();
  }
  else {
    unzipPath = PathManager.getInstallPluginsPath() + File.separator + pluginName;
  }

  StartupActionScriptManager.ActionCommand unzip = new StartupActionScriptManager.UnzipCommand(fromFile, new File(unzipPath));

  StartupActionScriptManager.addActionCommand(unzip);

  // add command to remove temp plugin file
  if (deleteFromFile) {
    StartupActionScriptManager.ActionCommand deleteTemp = new StartupActionScriptManager.DeleteCommand(fromFile);
    StartupActionScriptManager.addActionCommand(deleteTemp);
  }
}
项目:consulo    文件:InstalledPluginsManagerMain.java   
@Nullable
public static IdeaPluginDescriptorImpl loadDescriptionFromJar(final File file) throws IOException {
  IdeaPluginDescriptorImpl descriptor = PluginManagerCore.loadDescriptorFromJar(file);
  if (descriptor == null) {
    if (file.getName().endsWith(".zip")) {
      final File outputDir = FileUtil.createTempDirectory("plugin", "");
      try {
        ZipUtil.extract(file, outputDir, null);
        final File[] files = outputDir.listFiles();
        if (files != null && files.length == 1) {
          descriptor = PluginManagerCore.loadDescriptor(files[0], PluginManagerCore.PLUGIN_XML);
        }
      }
      finally {
        FileUtil.delete(outputDir);
      }
    }
  }
  return descriptor;
}
项目:consulo    文件:UnzipNewModuleBuilderProcessor.java   
protected void unzip(@Nonnull ModifiableRootModel model) {
  InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(myPath);
  if(resourceAsStream == null) {
    LOGGER.error("Resource by path '" + myPath + "' not found");
    return;
  }
  try {
    File tempFile = FileUtil.createTempFile("template", "zip");
    FileUtil.writeToFile(tempFile, FileUtil.loadBytes(resourceAsStream));
    final VirtualFile moduleDir = model.getModule().getModuleDir();

    File outputDir = VfsUtil.virtualToIoFile(moduleDir);

    ZipUtil.extract(tempFile, outputDir, null);
  }
  catch (IOException e) {
    LOGGER.error(e);
  }
}
项目:consulo    文件:StartupActionScriptManager.java   
@Override
public void execute(final Logger logger) throws IOException {
  if (!mySource.exists()) {
    logger.error("Source file " + mySource.getAbsolutePath() + " does not exist for action " + this);
  }
  else if (!canCreateFile(myDestination)) {
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), MessageFormat
                                          .format("<html>Cannot unzip {0}<br>to<br>{1}<br>Please, check your access rights on folder <br>{2}", mySource.getAbsolutePath(), myDestination.getAbsolutePath(), myDestination),
                                  "Installing Plugin", JOptionPane.ERROR_MESSAGE);
  }
  else {
    try {
      ZipUtil.extract(mySource, myDestination, myFilenameFilter);
    }
    catch (Exception ex) {
      logger.error(ex);

      JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), MessageFormat
              .format("<html>Failed to extract ZIP file {0}<br>to<br>{1}<br>You may need to re-download the plugin you tried to install.", mySource.getAbsolutePath(),
                      myDestination.getAbsolutePath()), "Installing Plugin", JOptionPane.ERROR_MESSAGE);
    }
  }
}
项目:mule-intellij-plugins    文件:MuleSdkSelectionDialog.java   
private void downloadVersionWithProgress(String version, String destinationDir) {

        Messages.showInfoMessage(contentPane, "Download Is Going to Take Some Time. Good time for a coffee.", "Mule Distribution Download");
        final Optional<MuleUrl> first = MuleUrl.getVERSIONS().stream().filter((url) -> url.getName().equals(version)).findFirst();
        final MuleUrl muleUrl = first.get();
        try {
            final ProgressManager instance = ProgressManager.getInstance();
            final File distro = instance.runProcessWithProgressSynchronously(() -> {
                final URL artifactUrl = new URL(muleUrl.getUrl());
                final File sourceFile = FileUtil.createTempFile("mule" + version, ".zip");
                if (download(instance.getProgressIndicator(), artifactUrl, sourceFile, version)) {
                    final File destDir = new File(destinationDir);
                    destDir.mkdirs();
                    ZipUtil.extract(sourceFile, destDir, null);
                    try (ZipFile zipFile = new ZipFile(sourceFile)) {
                        String rootName = zipFile.entries().nextElement().getName();
                        return new File(destDir, rootName);
                    }
                } else {
                    return null;
                }
            }, "Downloading Mule Distribution " + muleUrl.getName(), true, null);
            if (distro != null) {
                final MuleSdk muleSdk = new MuleSdk(distro.getAbsolutePath());
                MuleSdkManagerImpl.getInstance().addSdk(muleSdk);
                myTableModel.addRow(muleSdk);
                final int rowIndex = myTableModel.getRowCount() - 1;
                myInputsTable.getSelectionModel().setSelectionInterval(rowIndex, rowIndex);
                onOK();
            }
        } catch (Exception e) {
            Messages.showErrorDialog("An error occurred while trying to download " + version + ".\n" + e.getMessage(),
                    "Mule SDK Download Error");
        }

    }
项目:intellij-ce-playground    文件:JarsBuilder.java   
private void addFileOrDirRecursively(@NotNull ZipOutputStream jarOutputStream,
                                     @NotNull File file,
                                     SourceFileFilter filter,
                                     @NotNull String relativePath,
                                     String targetJarPath,
                                     @NotNull Set<String> writtenItemRelativePaths,
                                     List<String> packedFilePaths,
                                     int rootIndex) throws IOException {
  final String filePath = FileUtil.toSystemIndependentName(file.getAbsolutePath());
  if (!filter.accept(filePath) || !filter.shouldBeCopied(filePath, myContext.getProjectDescriptor())) {
    return;
  }

  if (file.isDirectory()) {
    final String directoryPath = relativePath.length() == 0 ? "" : relativePath + "/";
    if (!directoryPath.isEmpty()) {
      addDirectoryEntry(jarOutputStream, directoryPath, writtenItemRelativePaths);
    }
    final File[] children = file.listFiles();
    if (children != null) {
      for (File child : children) {
        addFileOrDirRecursively(jarOutputStream, child, filter, directoryPath + child.getName(), targetJarPath, writtenItemRelativePaths,
                                packedFilePaths, rootIndex);
      }
    }
    return;
  }

  final boolean added = ZipUtil.addFileToZip(jarOutputStream, file, relativePath, writtenItemRelativePaths, null);
  if (rootIndex != -1) {
    myOutSrcMapping.appendData(targetJarPath, rootIndex, filePath);
    if (added) {
      packedFilePaths.add(filePath);
    }
  }
}
项目:intellij-ce-playground    文件:PlatformTestUtil.java   
public static void assertJarFilesEqual(File file1, File file2) throws IOException {
  final File tempDirectory1;
  final File tempDirectory2;

  final JarFile jarFile1 = new JarFile(file1);
  try {
    final JarFile jarFile2 = new JarFile(file2);
    try {
      tempDirectory1 = PlatformTestCase.createTempDir("tmp1");
      tempDirectory2 = PlatformTestCase.createTempDir("tmp2");
      ZipUtil.extract(jarFile1, tempDirectory1, null);
      ZipUtil.extract(jarFile2, tempDirectory2, null);
    }
    finally {
      jarFile2.close();
    }
  }
  finally {
    jarFile1.close();
  }

  final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1);
  assertNotNull(tempDirectory1.toString(), dirAfter);
  final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2);
  assertNotNull(tempDirectory2.toString(), dirBefore);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      dirAfter.refresh(false, true);
      dirBefore.refresh(false, true);
    }
  });
  assertDirectoriesEqual(dirAfter, dirBefore);
}
项目:intellij-ce-playground    文件:PluginInstaller.java   
public static void install(final File fromFile, final String pluginName, boolean deleteFromFile) throws IOException {
  //noinspection HardCodedStringLiteral
  if (fromFile.getName().endsWith(".jar")) {
    // add command to copy file to the IDEA/plugins path
    StartupActionScriptManager.ActionCommand copyPlugin =
      new StartupActionScriptManager.CopyCommand(fromFile, new File(PathManager.getPluginsPath() + File.separator + fromFile.getName()));
    StartupActionScriptManager.addActionCommand(copyPlugin);
  }
  else {
    // add command to unzip file to the IDEA/plugins path
    String unzipPath;
    if (ZipUtil.isZipContainsFolder(fromFile)) {
      unzipPath = PathManager.getPluginsPath();
    }
    else {
      unzipPath = PathManager.getPluginsPath() + File.separator + pluginName;
    }

    StartupActionScriptManager.ActionCommand unzip = new StartupActionScriptManager.UnzipCommand(fromFile, new File(unzipPath));
    StartupActionScriptManager.addActionCommand(unzip);
  }

  // add command to remove temp plugin file
  if (deleteFromFile) {
    StartupActionScriptManager.ActionCommand deleteTemp = new StartupActionScriptManager.DeleteCommand(fromFile);
    StartupActionScriptManager.addActionCommand(deleteTemp);
  }
}
项目:intellij-ce-playground    文件:PySkeletonRefresher.java   
private void unpackPreGeneratedSkeletons() throws InvalidSdkException {
  indicate("Unpacking pregenerated skeletons...");
  try {
    final VirtualFile jar = JarFileSystem.getInstance().getVirtualFileForJar(myPregeneratedSkeletons);
    if (jar != null) {
      ZipUtil.extract(new File(jar.getPath()),
                      new File(getSkeletonsPath()), null);
    }
  }
  catch (IOException e) {
    LOG.info("Error unpacking pregenerated skeletons", e);
  }
}
项目:intellij-ce-playground    文件:CCCreateCourseArchive.java   
private void packCourse(@NotNull final VirtualFile baseDir, @NotNull final Course course) {
  try {
    final File zipFile = new File(myLocationDir, myZipName + ".zip");
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    final CCLanguageManager manager = CCUtils.getStudyLanguageManager(course);
    VirtualFile[] courseFiles = baseDir.getChildren();
    for (VirtualFile file : courseFiles) {
      ZipUtil.addFileOrDirRecursively(zos, null, new File(file.getPath()), file.getName(), new FileFilter() {
        @Override
        public boolean accept(File pathname) {
          String name = pathname.getName();
          String nameWithoutExtension = FileUtil.getNameWithoutExtension(pathname);
          if (nameWithoutExtension.endsWith(".answer") || name.contains(EduNames.WINDOWS_POSTFIX) || name.contains(".idea")
            || FileUtil.filesEqual(pathname, zipFile)) {
            return false;
          }
          return manager != null && !manager.doNotPackFile(pathname);
        }
      }, null);
    }
    zos.close();
    Messages.showInfoMessage("Course archive was saved to " + zipFile.getPath(), "Course Archive Was Created Successfully");
  }
  catch (IOException e1) {
    LOG.error(e1);
  }
}
项目:intellij-ce-playground    文件:AndroidFacetImporterBase.java   
private static boolean extractArtifact(String zipFilePath, String targetDirPath, Project project, String moduleName) {
  final File targetDir = new File(targetDirPath);
  if (targetDir.exists()) {
    if (!FileUtil.delete(targetDir)) {
      AndroidUtils.reportImportErrorToEventLog("Cannot delete old " + targetDirPath, moduleName, project);
      return false;
    }
  }

  if (!targetDir.mkdirs()) {
    AndroidUtils.reportImportErrorToEventLog("Cannot create directory " + targetDirPath, moduleName, project);
    return false;
  }
  final File artifactFile = new File(zipFilePath);

  if (artifactFile.exists()) {
    try {
      ZipUtil.extract(artifactFile, targetDir, null);
    }
    catch (IOException e) {
      reportIoErrorToEventLog(e, moduleName, project);
      return false;
    }
  }
  else {
    AndroidUtils.reportImportErrorToEventLog("Cannot find file " + artifactFile.getPath(), moduleName, project);
  }
  return true;
}
项目:intellij-ce-playground    文件:GitRepositoryReaderTest.java   
private void prepareTest(File testDir) throws IOException {
  assertTrue("Temp directory was not created", myTempDir.mkdir());
  FileUtil.copyDir(testDir, myTempDir);
  myGitDir = new File(myTempDir, ".git");
  File dotGit = new File(myTempDir, "dot_git");
  if (!dotGit.exists()) {
    File dotGitZip = new File(myTempDir, "dot_git.zip");
    assertTrue("Neither dot_git nor dot_git.zip were found", dotGitZip.exists());
    ZipUtil.extract(dotGitZip, myTempDir, null);
  }
  FileUtil.rename(dotGit, myGitDir);
  TestCase.assertTrue(myGitDir.exists());
  myRepositoryReader = new GitRepositoryReader(myGitDir);
}
项目:intellij-ce-playground    文件:PrepareToDeployAction.java   
private static void processLibrariesAndJpsPlugins(final File jarFile, final File zipFile, final String pluginName,
                                                  final Set<Library> libs,
                                                  Map<Module, String> jpsModules, final ProgressIndicator progressIndicator) throws IOException {
  if (FileUtil.ensureCanCreateFile(zipFile)) {
    ZipOutputStream zos = null;
    try {
      zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
      addStructure(pluginName, zos);
      addStructure(pluginName + "/" + MIDDLE_LIB_DIR, zos);
      final String entryName = pluginName + JAR_EXTENSION;
      ZipUtil.addFileToZip(zos, jarFile, getZipPath(pluginName, entryName), new HashSet<String>(),
                           createFilter(progressIndicator, FileTypeManager.getInstance()));
      for (Map.Entry<Module, String> entry : jpsModules.entrySet()) {
        File jpsPluginJar = jarModulesOutput(Collections.singleton(entry.getKey()), null, null);
        ZipUtil.addFileToZip(zos, jpsPluginJar, getZipPath(pluginName, entry.getValue()), null, null);
      }
      Set<String> usedJarNames = new HashSet<String>();
      usedJarNames.add(entryName);
      Set<VirtualFile> jarredVirtualFiles = new HashSet<VirtualFile>();
      for (Library library : libs) {
        final VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
        for (VirtualFile virtualFile : files) {
          if (jarredVirtualFiles.add(virtualFile)) {
            if (virtualFile.getFileSystem() instanceof JarFileSystem) {
              addLibraryJar(virtualFile, zipFile, pluginName, zos, usedJarNames, progressIndicator);
            }
            else {
              makeAndAddLibraryJar(virtualFile, zipFile, pluginName, zos, usedJarNames, progressIndicator, library.getName());
            }
          }
        }
      }
    }
    finally {
      if (zos != null) zos.close();
    }
  }
}
项目:intellij-ce-playground    文件:PrepareToDeployAction.java   
private static void addLibraryJar(final VirtualFile virtualFile,
                                  final File zipFile,
                                  final String pluginName,
                                  final ZipOutputStream zos,
                                  final Set<String> usedJarNames,
                                  final ProgressIndicator progressIndicator) throws IOException {
  File ioFile = VfsUtil.virtualToIoFile(virtualFile);
  final String jarName = getLibraryJarName(ioFile.getName(), usedJarNames, null);
  ZipUtil.addFileOrDirRecursively(zos, zipFile, ioFile, getZipPath(pluginName, jarName), createFilter(progressIndicator, null), null);
}
项目:idea-php-shopware-plugin    文件:ShopwareInstallerProjectGenerator.java   
@Override
public void generateProject(@NotNull final Project project, final @NotNull VirtualFile baseDir, final @NotNull ShopwareInstallerSettings settings, @NotNull Module module) {

    String downloadPath = settings.getVersion().getUrl();
    String toDir = baseDir.getPath();

    VirtualFile zipFile = PhpConfigurationUtil.downloadFile(project, null, toDir, downloadPath, "shopware.zip");

    if (zipFile == null) {
        showErrorNotification(project, "Cannot download Shopware.zip file");
        return;
    }

    // Convert files
    File zip = VfsUtil.virtualToIoFile(zipFile);
    File base = VfsUtil.virtualToIoFile(baseDir);

    Task.Backgroundable task = new Task.Backgroundable(project, "Extracting", true) {
        @Override
        public void run(@NotNull ProgressIndicator progressIndicator) {

            try {
                // unzip file
                ZipUtil.extract(zip, base, null);

                // Delete TMP File
                FileUtil.delete(zip);

                // Activate Plugin
                IdeHelper.enablePluginAndConfigure(project);
            } catch (IOException e) {
                showErrorNotification(project, "There is a error occurred");
            }
        }
    };

    ProgressManager.getInstance().run(task);
}
项目:tools-idea    文件:JarsBuilder.java   
private void addFileOrDirRecursively(@NotNull ZipOutputStream jarOutputStream,
                                     @NotNull File file,
                                     SourceFileFilter filter,
                                     @NotNull String relativePath,
                                     String targetJarPath,
                                     @NotNull Set<String> writtenItemRelativePaths,
                                     List<String> packedFilePaths,
                                     int rootIndex) throws IOException {
  final String filePath = FileUtil.toSystemIndependentName(file.getAbsolutePath());
  if (!filter.accept(filePath) || !filter.shouldBeCopied(filePath, myContext.getProjectDescriptor())) {
    return;
  }

  if (file.isDirectory()) {
    final String directoryPath = relativePath.length() == 0 ? "" : relativePath + "/";
    if (!directoryPath.isEmpty()) {
      addDirectoryEntry(jarOutputStream, directoryPath, writtenItemRelativePaths);
    }
    final File[] children = file.listFiles();
    if (children != null) {
      for (File child : children) {
        addFileOrDirRecursively(jarOutputStream, child, filter, directoryPath + child.getName(), targetJarPath, writtenItemRelativePaths,
                                packedFilePaths, rootIndex);
      }
    }
    return;
  }

  final boolean added = ZipUtil.addFileToZip(jarOutputStream, file, relativePath, writtenItemRelativePaths, null);
  if (rootIndex != -1) {
    myOutSrcMapping.appendData(targetJarPath, rootIndex, filePath);
    if (added) {
      packedFilePaths.add(filePath);
    }
  }
}
项目:tools-idea    文件:JarsBuilder.java   
private void addFileToJar(final @NotNull JarOutputStream jarOutputStream, final @NotNull File file, @NotNull String relativePath,
                          final @NotNull THashSet<String> writtenPaths) throws IOException {
  if (!file.exists()) {
    return;
  }

  relativePath = addParentDirectories(jarOutputStream, writtenPaths, relativePath);
  myContext.getProgressIndicator().setText2(relativePath);
  ZipUtil.addFileToZip(jarOutputStream, file, relativePath, writtenPaths, myFileFilter);
}
项目:tools-idea    文件:PlatformTestUtil.java   
public static void assertJarFilesEqual(File file1, File file2) throws IOException {
  final File tempDirectory1;
  final File tempDirectory2;

  final JarFile jarFile1 = new JarFile(file1);
  try {
    final JarFile jarFile2 = new JarFile(file2);
    try {
      tempDirectory1 = PlatformTestCase.createTempDir("tmp1");
      tempDirectory2 = PlatformTestCase.createTempDir("tmp2");
      ZipUtil.extract(jarFile1, tempDirectory1, null);
      ZipUtil.extract(jarFile2, tempDirectory2, null);
    }
    finally {
      jarFile2.close();
    }
  }
  finally {
    jarFile1.close();
  }

  final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1);
  assertNotNull(tempDirectory1.toString(), dirAfter);
  final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2);
  assertNotNull(tempDirectory2.toString(), dirBefore);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      dirAfter.refresh(false, true);
      dirBefore.refresh(false, true);
    }
  });
  assertDirectoriesEqual(dirAfter, dirBefore);
}
项目:tools-idea    文件:PluginDownloader.java   
public static void install(final File fromFile, final String pluginName, boolean deleteFromFile) throws IOException {
  //noinspection HardCodedStringLiteral
  if (fromFile.getName().endsWith(".jar")) {
    // add command to copy file to the IDEA/plugins path
    StartupActionScriptManager.ActionCommand copyPlugin =
      new StartupActionScriptManager.CopyCommand(fromFile, new File(PathManager.getPluginsPath() + File.separator + fromFile.getName()));
    StartupActionScriptManager.addActionCommand(copyPlugin);
  }
  else {
    // add command to unzip file to the IDEA/plugins path
    String unzipPath;
    if (ZipUtil.isZipContainsFolder(fromFile)) {
      unzipPath = PathManager.getPluginsPath();
    }
    else {
      unzipPath = PathManager.getPluginsPath() + File.separator + pluginName;
    }

    StartupActionScriptManager.ActionCommand unzip = new StartupActionScriptManager.UnzipCommand(fromFile, new File(unzipPath));
    StartupActionScriptManager.addActionCommand(unzip);
  }

  // add command to remove temp plugin file
  if (deleteFromFile) {
    StartupActionScriptManager.ActionCommand deleteTemp = new StartupActionScriptManager.DeleteCommand(fromFile);
    StartupActionScriptManager.addActionCommand(deleteTemp);
  }
}
项目:tools-idea    文件:ExportSettingsAction.java   
private static void exportInstalledPlugins(File saveFile, JarOutputStream output, HashSet<String> writtenItemRelativePaths) throws IOException {
  final List<String> oldPlugins = new ArrayList<String>();
  for (IdeaPluginDescriptor descriptor : PluginManager.getPlugins()) {
    if (!descriptor.isBundled() && descriptor.isEnabled()) {
      oldPlugins.add(descriptor.getPluginId().getIdString());
    }
  }
  if (!oldPlugins.isEmpty()) {
    final File tempFile = File.createTempFile("installed", "plugins");
    tempFile.deleteOnExit();
    PluginManager.savePluginsList(oldPlugins, false, tempFile);
    ZipUtil.addDirToZipRecursively(output, saveFile, tempFile, "/" + PluginManager.INSTALLED_TXT, null, writtenItemRelativePaths);
  }
}
项目:tools-idea    文件:MavenExternalParameters.java   
private static String getArtifactResolverJar(boolean isMaven3) throws IOException {
  Class marker = isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class;

  File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));

  if (!classDirOrJar.isDirectory()) {
    return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation.
  }

  // it's a classes directory, we are in development mode.
  File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar");
  tempFile.deleteOnExit();

  ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile));
  try {
    ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null);

    if (isMaven3) {
      File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class));

      String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/');
      ZipUtil.addDirToZipRecursively(zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null);
    }
  } finally {
    zipOutput.close();
  }

  return tempFile.getAbsolutePath();
}
项目:tools-idea    文件:PrepareToDeployAction.java   
private void processLibraries(final File jarFile,
                              final File zipFile,
                              final String pluginName,
                              final Set<Library> libs,
                              final ProgressIndicator progressIndicator) throws IOException {
  if (FileUtil.ensureCanCreateFile(zipFile)) {
    ZipOutputStream zos = null;
    try {
      zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
      addStructure(pluginName, zos);
      addStructure(pluginName + "/" + MIDDLE_LIB_DIR, zos);
      final String entryName = pluginName + JAR_EXTENSION;
      ZipUtil.addFileToZip(zos, jarFile, getZipPath(pluginName, entryName), new HashSet<String>(),
                           createFilter(progressIndicator, myFileTypeManager));
      Set<String> usedJarNames = new HashSet<String>();
      usedJarNames.add(entryName);
      Set<VirtualFile> jarredVirtualFiles = new HashSet<VirtualFile>();
      for (Library library : libs) {
        final VirtualFile[] files = library.getFiles(OrderRootType.CLASSES);
        for (VirtualFile virtualFile : files) {
          if (jarredVirtualFiles.add(virtualFile)) {
            if (virtualFile.getFileSystem() instanceof JarFileSystem) {
              addLibraryJar(virtualFile, zipFile, pluginName, zos, usedJarNames, progressIndicator);
            }
            else {
              makeAndAddLibraryJar(virtualFile, zipFile, pluginName, zos, usedJarNames, progressIndicator, library.getName());
            }
          }
        }
      }
    }
    finally {
      if (zos != null) zos.close();
    }
  }
}
项目:tools-idea    文件:PrepareToDeployAction.java   
private static void addLibraryJar(final VirtualFile virtualFile,
                                  final File zipFile,
                                  final String pluginName,
                                  final ZipOutputStream zos,
                                  final Set<String> usedJarNames,
                                  final ProgressIndicator progressIndicator) throws IOException {
  File ioFile = VfsUtil.virtualToIoFile(virtualFile);
  final String jarName = getLibraryJarName(ioFile.getName(), usedJarNames, null);
  ZipUtil.addFileOrDirRecursively(zos, zipFile, ioFile, getZipPath(pluginName, jarName), createFilter(progressIndicator, null), null);
}
项目:consulo    文件:PlatformTestUtil.java   
public static void assertJarFilesEqual(File file1, File file2) throws IOException {
  final File tempDirectory1;
  final File tempDirectory2;

  final JarFile jarFile1 = new JarFile(file1);
  try {
    final JarFile jarFile2 = new JarFile(file2);
    try {
      tempDirectory1 = PlatformTestCase.createTempDir("tmp1");
      tempDirectory2 = PlatformTestCase.createTempDir("tmp2");
      ZipUtil.extract(jarFile1, tempDirectory1, null);
      ZipUtil.extract(jarFile2, tempDirectory2, null);
    }
    finally {
      jarFile2.close();
    }
  }
  finally {
    jarFile1.close();
  }

  final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1);
  assertNotNull(tempDirectory1.toString(), dirAfter);
  final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2);
  assertNotNull(tempDirectory2.toString(), dirBefore);
  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      dirAfter.refresh(false, true);
      dirBefore.refresh(false, true);
    }
  });
  assertDirectoriesEqual(dirAfter, dirBefore);
}
项目:consulo    文件:ExportSettingsAction.java   
private static void exportInstalledPlugins(File saveFile, JarOutputStream output, HashSet<String> writtenItemRelativePaths) throws IOException {
  final List<String> oldPlugins = new ArrayList<>();
  for (IdeaPluginDescriptor descriptor : PluginManagerCore.getPlugins()) {
    if (!descriptor.isBundled() && descriptor.isEnabled()) {
      oldPlugins.add(descriptor.getPluginId().getIdString());
    }
  }
  if (!oldPlugins.isEmpty()) {
    final File tempFile = File.createTempFile("installed", "plugins");
    tempFile.deleteOnExit();
    PluginManagerCore.savePluginsList(oldPlugins, false, tempFile);
    ZipUtil.addDirToZipRecursively(output, saveFile, tempFile, "/" + PluginManager.INSTALLED_TXT, null, writtenItemRelativePaths);
  }
}
项目:consulo    文件:MemoryDumpHelper.java   
public static synchronized void captureMemoryDumpZipped(@Nonnull String zipPath) throws Exception {
  File tempFile = FileUtil.createTempFile("heapDump.", ".hprof");
  FileUtil.delete(tempFile);

  captureMemoryDump(tempFile.getPath());

  ZipUtil.compressFile(tempFile, new File(zipPath));
  FileUtil.delete(tempFile);
}
项目:intellij-ce-playground    文件:AndroidAarDepsBuilder.java   
private static boolean doBuild(final CompileContext context,
                               AndroidAarDepsBuildTarget target,
                               BuildOutputConsumer outputConsumer) {
  final JpsModule module = target.getModule();
  final JpsAndroidModuleExtension extension = AndroidJpsUtil.getExtension(module);
  if (extension == null || extension.isLibrary()) {
    return true;
  }

  File outputDir = AndroidJpsUtil.getDirectoryForIntermediateArtifacts(context, module);
  outputDir = AndroidJpsUtil.createDirIfNotExist(outputDir, context, BUILDER_NAME);
  if (outputDir == null) {
    return false;
  }
  final List<String> srcJarFiles = new ArrayList<String>();

  for (BuildRootDescriptor descriptor : context.getProjectDescriptor().getBuildRootIndex().getTargetRoots(target, context)) {
    final File file = descriptor.getRootFile();

    if (file.exists()) {
      srcJarFiles.add(file.getPath());
    }
  }
  if (srcJarFiles.size() == 0) {
    return true;
  }
  context.processMessage(new ProgressMessage(AndroidJpsBundle.message(
    "android.jps.progress.aar.dependencies.packaging", module.getName())));

  File tempDir = null;

  try {
    tempDir = FileUtil.createTempDirectory("extracted_aar_deps", "tmp");

    for (int i = srcJarFiles.size() - 1; i >= 0; i--) {
      ZipUtil.extract(new File(srcJarFiles.get(i)), tempDir, null, true);
    }
    final File outputJarFile = new File(outputDir, AndroidCommonUtils.AAR_DEPS_JAR_FILE_NAME);

    if (!packDirectoryIntoJar(tempDir, outputJarFile, context)) {
      return false;
    }
    final AndroidBuildTestingManager testingManager = AndroidBuildTestingManager.getTestingManager();

    if (testingManager != null && outputJarFile.isFile()) {
      testingManager.getCommandExecutor().checkJarContent("aar_dependencies_package_jar", outputJarFile.getPath());
    }
    outputConsumer.registerOutputFile(outputJarFile, srcJarFiles);
    return true;
  }
  catch (IOException e) {
    AndroidJpsUtil.reportExceptionError(context, null, e, BUILDER_NAME);
    return false;
  }
  finally {
    if (tempDir != null) {
      FileUtil.delete(tempDir);
    }
  }
}
项目:intellij-ce-playground    文件:MavenExternalParameters.java   
private static String getArtifactResolverJar(@Nullable String mavenVersion) throws IOException {
  boolean isMaven3;
  Class marker;

  if (mavenVersion != null && mavenVersion.compareTo("3.1.0") >= 0) {
    isMaven3 = true;
    marker = MavenArtifactResolvedM31RtMarker.class;
  }
  else if (mavenVersion != null && mavenVersion.compareTo("3.0.0") >= 0) {
    isMaven3 = true;
    marker = MavenArtifactResolvedM3RtMarker.class;
  }
  else {
    isMaven3 = false;
    marker = MavenArtifactResolvedM2RtMarker.class;
  }

  File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));

  if (!classDirOrJar.isDirectory()) {
    return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation.
  }

  // it's a classes directory, we are in development mode.
  File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar");
  tempFile.deleteOnExit();

  ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile));
  try {
    ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null);

    if (isMaven3) {
      File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class));

      String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/');
      ZipUtil.addDirToZipRecursively(zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null);
    }
  } finally {
    zipOutput.close();
  }

  return tempFile.getAbsolutePath();
}
项目:intellij-ce-playground    文件:AbstractJavaFxPackager.java   
public void buildJavaFxArtifact(final String homePath) {
  if (!checkNotEmpty(getAppClass(), "Application class")) return;
  if (!checkNotEmpty(getWidth(), "Width")) return;
  if (!checkNotEmpty(getHeight(), "Height")) return;

  final String zipPath = getArtifactOutputFilePath();

  final File tempUnzippedArtifactOutput;
  try {
    tempUnzippedArtifactOutput = FileUtil.createTempDirectory("artifact", "unzipped");
    final File artifactOutputFile = new File(zipPath);
    ZipUtil.extract(artifactOutputFile, tempUnzippedArtifactOutput, null);
    copyLibraries(FileUtil.getNameWithoutExtension(artifactOutputFile), tempUnzippedArtifactOutput);
  }
  catch (IOException e) {
    registerJavaFxPackagerError(e);
    return;
  }

  final File tempDirectory = new File(tempUnzippedArtifactOutput, "deploy");
  try {

    final StringBuilder buf = new StringBuilder();
    buf.append("<project default=\"build artifact\">\n");
    buf.append("<taskdef resource=\"com/sun/javafx/tools/ant/antlib.xml\" uri=\"javafx:com.sun.javafx.tools.ant\" ")
       .append("classpath=\"").append(homePath).append("/lib/ant-javafx.jar\"/>\n");
    buf.append("<target name=\"build artifact\" xmlns:fx=\"javafx:com.sun.javafx.tools.ant\">");
    final String artifactFileName = getArtifactRootName();
    final List<JavaFxAntGenerator.SimpleTag> tags =
      JavaFxAntGenerator.createJarAndDeployTasks(this, artifactFileName, getArtifactName(), tempUnzippedArtifactOutput.getPath());
    for (JavaFxAntGenerator.SimpleTag tag : tags) {
      tag.generate(buf);
    }
    buf.append("</target>");
    buf.append("</project>");

    final int result = startAntTarget(buf.toString(), homePath);
    if (result == 0) {
      if (isEnabledSigning()) {
        signApp(homePath + File.separator + "bin", tempDirectory);
      }
    }
    else {
      registerJavaFxPackagerError("fx:deploy task has failed.");
    }
  }
  finally {
    copyResultsToArtifactsOutput(tempDirectory);
    FileUtil.delete(tempUnzippedArtifactOutput);
  }
}