Java Code Examples for com.intellij.openapi.util.io.FileUtil#createTempFile()

The following examples show how to use com.intellij.openapi.util.io.FileUtil#createTempFile() . 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: VfsUtilTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testDirAttributeRefreshes() throws IOException {
  File tempDir = WriteAction.compute(() -> {
    File res = createTempDirectory();
    return res;
  });
  VirtualFile vDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDir);
  assertNotNull(vDir);
  assertTrue(vDir.isDirectory());

  File file = FileUtil.createTempFile(tempDir, "xxx", "yyy", true);
  assertNotNull(file);
  VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
  assertNotNull(vFile);
  assertFalse(vFile.isDirectory());

  boolean deleted = file.delete();
  assertTrue(deleted);
  boolean created = file.mkdir();
  assertTrue(created);
  assertTrue(file.exists());

  VirtualFile vFile2 = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
  assertNotNull(vFile2);
  assertTrue(vFile2.isDirectory());
}
 
Example 2
Source File: PantsCompileOptionsExecutor.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
private String loadProjectStructureFromTargets(
  @NotNull Consumer<String> statusConsumer,
  @Nullable ProcessAdapter processAdapter
) throws IOException, ExecutionException {
  final File outputFile = FileUtil.createTempFile("pants_depmap_run", ".out");
  final GeneralCommandLine command = getPantsExportCommand(outputFile, statusConsumer);
  statusConsumer.consume("Resolving dependencies...");
  PantsMetrics.markExportStart();
  final ProcessOutput processOutput = getProcessOutput(command);
  PantsMetrics.markExportEnd();
  if (processOutput.getStdout().contains("no such option")) {
    throw new ExternalSystemException("Pants doesn't have necessary APIs. Please upgrade your pants!");
  }
  if (processOutput.checkSuccess(LOG)) {
    return FileUtil.loadFile(outputFile);
  }
  else {
    throw new PantsExecutionException("Failed to update the project!", command.getCommandLineString("pants"), processOutput);
  }
}
 
Example 3
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testSingleFileRootRefresh() throws Exception {
  File file = FileUtil.createTempFile("test.", ".txt");
  VirtualFile virtualFile = myFS.refreshAndFindFileByIoFile(file);
  assertNotNull(virtualFile);
  assertTrue(virtualFile.exists());
  assertTrue(virtualFile.isValid());

  virtualFile.refresh(false, false);
  assertFalse(((VirtualFileSystemEntry)virtualFile).isDirty());

  FileUtil.delete(file);
  assertFalse(file.exists());
  virtualFile.refresh(false, false);
  assertFalse(virtualFile.exists());
  assertFalse(virtualFile.isValid());
}
 
Example 4
Source File: UnzipNewModuleBuilderProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
protected void unzip(@Nonnull ModifiableRootModel model) {
  InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(myPath);
  if (resourceAsStream == null) {
    LOG.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) {
    LOG.error(e);
  }
}
 
Example 5
Source File: DiffContentFactoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static VirtualFile createTemporalFile(@javax.annotation.Nullable Project project,
                                              @Nonnull String prefix,
                                              @Nonnull String suffix,
                                              @Nonnull byte[] content) throws IOException {
  File tempFile = FileUtil.createTempFile(PathUtil.suggestFileName(prefix + "_", true, false),
                                          PathUtil.suggestFileName("_" + suffix, true, false), true);
  if (content.length != 0) {
    FileUtil.writeToFile(tempFile, content);
  }
  if (!tempFile.setWritable(false, false)) LOG.warn("Can't set writable attribute of temporal file");

  VirtualFile file = VfsUtil.findFileByIoFile(tempFile, true);
  if (file == null) {
    throw new IOException("Can't create temp file for revision content");
  }
  VfsUtil.markDirtyAndRefresh(true, true, true, file);
  return file;
}
 
Example 6
Source File: FileContent.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static FileContent createFromTempFile(Project project, String name, String ext, @Nonnull byte[] content) throws IOException {
  File tempFile = FileUtil.createTempFile(name, "." + ext);
  if (content.length != 0) {
    FileUtil.writeToFile(tempFile, content);
  }
  tempFile.deleteOnExit();
  final LocalFileSystem lfs = LocalFileSystem.getInstance();
  VirtualFile file = lfs.findFileByIoFile(tempFile);
  if (file == null) {
    file = lfs.refreshAndFindFileByIoFile(tempFile);
  }
  if (file != null) {
    return new FileContent(project, file);
  }
  throw new IOException("Can not create temp file for revision content");
}
 
Example 7
Source File: MemoryDumpHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: UnpackedAars.java    From intellij with Apache License 2.0 5 votes vote down vote up
/** Returns a locally-accessible file mirroring the contents of this {@link BlazeArtifact}. */
private static File getOrCreateLocalFile(BlazeArtifact artifact) throws IOException {
  if (artifact instanceof LocalFileArtifact) {
    return ((LocalFileArtifact) artifact).getFile();
  }
  File tmpFile =
      FileUtil.createTempFile(
          "local-aar-file",
          Integer.toHexString(artifactKey(artifact).hashCode()),
          /* deleteOnExit= */ true);
  try (InputStream stream = artifact.getInputStream()) {
    Files.copy(stream, Paths.get(tmpFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
    return tmpFile;
  }
}
 
Example 9
Source File: PagedFileStorageTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  super.setUp();
  lock.lock();
  try {
    f = FileUtil.createTempFile("storage", ".tmp");
    s = new PagedFileStorage(f, lock);
  }
  finally {
    lock.unlock();
  }
}
 
Example 10
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testFileLength() throws Exception {
  File file = FileUtil.createTempFile("test", "txt");
  FileUtil.writeToFile(file, "hello");
  VirtualFile virtualFile = myFS.refreshAndFindFileByIoFile(file);
  assertNotNull(virtualFile);
  String s = VfsUtilCore.loadText(virtualFile);
  assertEquals("hello", s);
  assertEquals(5, virtualFile.getLength());

  FileUtil.writeToFile(file, "new content");
  ((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents();
  s = VfsUtilCore.loadText(virtualFile);
  assertEquals("new content", s);
  assertEquals(11, virtualFile.getLength());
}
 
Example 11
Source File: ExecUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static File createTempExecutableScript(@Nonnull String prefix, @Nonnull String suffix, @Nonnull String content) throws IOException, ExecutionException {
  File tempDir = new File(ContainerPathManager.get().getTempPath());
  File tempFile = FileUtil.createTempFile(tempDir, prefix, suffix, true, true);
  FileUtil.writeToFile(tempFile, content.getBytes(CharsetToolkit.UTF8));
  if (!tempFile.setExecutable(true, true)) {
    throw new ExecutionException("Failed to make temp file executable: " + tempFile);
  }
  return tempFile;
}
 
Example 12
Source File: GeneralToSMTRunnerEventsConvertorTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testPreserveFullOutputAfterImport() throws Exception {

    mySuite.addChild(mySimpleTest);
    for (int i = 0; i < 550; i++) {
      String message = "line" + i + "\n";
      mySimpleTest.addLast(printer -> printer.print(message, ConsoleViewContentType.NORMAL_OUTPUT));
    }
    mySimpleTest.setFinished();
    mySuite.setFinished();

    SAXTransformerFactory transformerFactory = (SAXTransformerFactory)TransformerFactory.newInstance();
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    File output = FileUtil.createTempFile("output", "");
    try {
      FileUtilRt.createParentDirs(output);
      handler.setResult(new StreamResult(new FileWriter(output)));
      MockRuntimeConfiguration configuration = new MockRuntimeConfiguration(getProject());
      TestResultsXmlFormatter.execute(mySuite, configuration, new SMTRunnerConsoleProperties(configuration, "framework", new DefaultRunExecutor()), handler);

      String savedText = FileUtil.loadFile(output);
      assertTrue(savedText.split("\n").length > 550);

      myEventsProcessor.onStartTesting();
      ImportedToGeneralTestEventsConverter.parseTestResults(() -> new StringReader(savedText), myEventsProcessor);
      myEventsProcessor.onFinishTesting();

      List<? extends SMTestProxy> children = myResultsViewer.getTestsRootNode().getChildren();
      assertSize(1, children);
      SMTestProxy testProxy = children.get(0);
      MockPrinter mockPrinter = new MockPrinter();
      testProxy.printOn(mockPrinter);
      assertSize(550, mockPrinter.getAllOut().split("\n"));
    }
    finally {
      FileUtil.delete(output);
    }
  }
 
Example 13
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 14
Source File: TFSTmpFileStore.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
private static String getTfsTmpDir() throws IOException {
    if (myTfsTmpDir == null) {
        File tmpDir = FileUtil.createTempFile(TMP_FILE_NAME, "");
        tmpDir.delete();
        tmpDir.mkdir();
        tmpDir.deleteOnExit();
        myTfsTmpDir = tmpDir.getAbsolutePath();
    }
    return myTfsTmpDir;
}
 
Example 15
Source File: ActionWithTempFile.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void init() throws IOException {
  myTempFile = FileUtil.createTempFile(TMP_PREFIX, TMP_SUFFIX);
  FileUtil.delete(myTempFile);
  FileUtil.rename(mySourceFile, myTempFile);
}
 
Example 16
Source File: ExternalDiffToolUtil.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
private static File createFile(@Nonnull byte[] bytes, @Nonnull FileNameInfo fileName) throws IOException {
  File tempFile = FileUtil.createTempFile(fileName.prefix + "_", "_" + fileName.name, true);
  FileUtil.writeToFile(tempFile, bytes);
  return tempFile;
}
 
Example 17
Source File: PersistentMapTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void testOpeningWithCompact3() throws IOException {
  if (!DO_SLOW_TEST) return;
  File file = FileUtil.createTempFile("persistent", "map");

  EnumeratorStringDescriptor stringDescriptor = new EnumeratorStringDescriptor();
  EnumeratorIntegerDescriptor integerDescriptor = new EnumeratorIntegerDescriptor();
  PersistentHashMap<String, Integer> map = new PersistentHashMap<String, Integer>(file, stringDescriptor, integerDescriptor);
  try {
    final int stringsCount = 10000002;
    //final int stringsCount =      102;

    for(int t = 0; t < 4; ++t) {
      for (int i = 0; i < stringsCount; ++i) {
        final int finalI = i;
        final int finalT = t;
        PersistentHashMap.ValueDataAppender appender = new PersistentHashMap.ValueDataAppender() {
          @Override
          public void append(DataOutput out) throws IOException {
            out.write((finalI + finalT) & 0xFF);
          }
        };
        map.appendData(String.valueOf(i), appender);
      }
    }
    map.close();
    map = new PersistentHashMap<String, Integer>(file, stringDescriptor, integerDescriptor);
    for (int i = 0; i < stringsCount; ++i) {
      if (i < 2 * stringsCount / 3) {
        map.remove(String.valueOf(i));
      }
    }
    map.close();
    final boolean isSmall = stringsCount < 1000000;
    assertTrue(isSmall || map.makesSenseToCompact());
    long started = System.currentTimeMillis();

    map = new PersistentHashMap<String, Integer>(file, stringDescriptor, integerDescriptor);
    if (isSmall) map.compact();
    assertTrue(!map.makesSenseToCompact());
    System.out.println(System.currentTimeMillis() - started);
    for (int i = 0; i < stringsCount; ++i) {
      if (i >= 2 * stringsCount / 3) {
        Integer s = map.get(String.valueOf(i));
        assertEquals((s & 0xFF), ((i + 3) & 0xFF));
        assertEquals(((s >>> 8) & 0xFF), ((i + 2) & 0xFF));
        assertEquals((s >>> 16) & 0xFF, ((i + 1) & 0xFF));
        assertEquals((s >>> 24) & 0xFF, (i & 0xFF));
      }
    }
  }
  finally {
    clearMap(file, map);
  }
}
 
Example 18
Source File: BTreeEnumeratorTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  myFile = FileUtil.createTempFile("persistent", "trie");
  myEnumerator = new TestStringEnumerator(myFile);
}
 
Example 19
Source File: StringEnumeratorTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
  super.setUp();
  myFile = FileUtil.createTempFile("persistent", "trie");
  myEnumerator = new PersistentStringEnumerator(myFile);
}
 
Example 20
Source File: CompilerWrapperProviderImpl.java    From intellij with Apache License 2.0 4 votes vote down vote up
@Override
public File createCompilerExecutableWrapper(
    File executionRoot, File blazeCompilerExecutableFile) {
  try {
    File blazeCompilerWrapper =
        FileUtil.createTempFile("blaze_compiler", ".sh", true /* deleteOnExit */);
    if (!blazeCompilerWrapper.setExecutable(true)) {
      logger.warn("Unable to make compiler wrapper script executable: " + blazeCompilerWrapper);
      return null;
    }
    ImmutableList<String> compilerWrapperScriptLines =
        ImmutableList.of(
            "#!/bin/bash",
            "",
            "# The c toolchain compiler wrapper script doesn't handle arguments files, so we",
            "# need to move the compiler arguments from the file to the command line. We",
            "# preserve any existing commandline arguments, and remove the escaping from",
            "# arguments inside the args file.",
            "",
            "parsedargs=()",
            "for arg in \"${@}\"; do ",
            "  case \"$arg\" in",
            "    @*)",
            "      # Make sure the file ends with a newline - the read loop will not return",
            "      # the final line if it does not.",
            "      echo >> ${arg#@}",
            "      # Args file, the read will remove a layer of escaping",
            "      while read; do",
            "        parsedargs+=($REPLY)",
            "      done < ${arg#@}",
            "      ;;",
            "    *)",
            "      # Regular arg",
            "      parsedargs+=(\"$arg\")",
            "      ;;",
            "  esac",
            "done",
            "",
            "# The actual compiler wrapper script we get from blaze",
            String.format("EXE=%s", blazeCompilerExecutableFile.getPath()),
            "# Read in the arguments file so we can pass the arguments on the command line.",
            String.format("(cd %s && $EXE \"${parsedargs[@]}\")", executionRoot));

    try (PrintWriter pw = new PrintWriter(blazeCompilerWrapper, UTF_8.name())) {
      compilerWrapperScriptLines.forEach(pw::println);
    }
    return blazeCompilerWrapper;
  } catch (IOException e) {
    logger.warn(
        "Unable to write compiler wrapper script executable: " + blazeCompilerExecutableFile, e);
    return null;
  }
}