com.intellij.openapi.util.io.FileUtilRt Java Examples

The following examples show how to use com.intellij.openapi.util.io.FileUtilRt. 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: ChromeSettings.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<String> getAdditionalParameters() {
  if (myCommandLineOptions == null) {
    if (myUseCustomProfile && myUserDataDirectoryPath != null) {
      return Collections.singletonList(USER_DATA_DIR_ARG + FileUtilRt.toSystemDependentName(myUserDataDirectoryPath));
    }
    else {
      return Collections.emptyList();
    }
  }

  List<String> cliOptions = ParametersListUtil.parse(myCommandLineOptions);
  if (myUseCustomProfile && myUserDataDirectoryPath != null) {
    cliOptions.add(USER_DATA_DIR_ARG + FileUtilRt.toSystemDependentName(myUserDataDirectoryPath));
  }
  return cliOptions;
}
 
Example #2
Source File: FileTemplateManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Inject
public FileTemplateManagerImpl(@Nonnull FileTypeManager typeManager,
                               FileTemplateSettings projectSettings,
                               ExportableFileTemplateSettings defaultSettings,
                               ProjectManager pm,
                               final Project project) {
  myTypeManager = (FileTypeManagerEx)typeManager;
  myProjectSettings = projectSettings;
  myDefaultSettings = defaultSettings;
  myProject = project;

  myProjectScheme = project.isDefault() ? null : new FileTemplatesScheme("Project") {
    @Nonnull
    @Override
    public String getTemplatesDir() {
      return FileUtilRt.toSystemDependentName(StorageUtil.getStoreDir(project) + "/" + TEMPLATES_DIR);
    }

    @Nonnull
    @Override
    public Project getProject() {
      return project;
    }
  };
}
 
Example #3
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updateExtensionsCombo() {
  final Object source = getSource();
  if (source instanceof LanguageFileType) {
    final List<String> extensions = getAllExtensions((LanguageFileType)source);
    if (extensions.size() > 1) {
      final ExtensionComparator comp = new ExtensionComparator(extensions.get(0));
      Collections.sort(extensions, comp);
      final SortedComboBoxModel<String> model = new SortedComboBoxModel<String>(comp);
      model.setAll(extensions);
      myExtensionComboBox.setModel(model);
      myExtensionComboBox.setVisible(true);
      myExtensionLabel.setVisible(true);
      String fileExt = myCurrentFile != null ? FileUtilRt.getExtension(myCurrentFile.getName()) : "";
      if (fileExt.length() > 0 && extensions.contains(fileExt)) {
        myExtensionComboBox.setSelectedItem(fileExt);
        return;
      }
      myExtensionComboBox.setSelectedIndex(0);
      return;
    }
  }
  myExtensionComboBox.setVisible(false);
  myExtensionLabel.setVisible(false);
}
 
Example #4
Source File: ProjectWrangler.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public File copyProjectBeforeOpening(@NotNull String projectDirName) throws IOException {
  File masterProjectPath = getMasterProjectDirPath(projectDirName);

  File projectPath = getTestProjectDirPath(projectDirName);
  if (projectPath.isDirectory()) {
    FileUtilRt.delete(projectPath);
  }
  // If masterProjectPath contains a src.zip file, unzip the file to projectPath.
  // Otherwise, copy the whole directory to projectPath.
  File srcZip = new File(masterProjectPath, SRC_ZIP_NAME);
  if (srcZip.exists() && srcZip.isFile()) {
    ZipUtil.unzip(null, projectPath, srcZip, null, null, true);
  }
  else {
    FileUtil.copyDir(masterProjectPath, projectPath);
  }
  return projectPath;
}
 
Example #5
Source File: ArtifactEditorImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void updateOutputPath(@Nonnull String oldArtifactName, @Nonnull final String newArtifactName) {
  final String oldDefaultPath = ArtifactUtil.getDefaultArtifactOutputPath(oldArtifactName, myProject);
  if (Comparing.equal(oldDefaultPath, getConfiguredOutputPath())) {
    setOutputPath(ArtifactUtil.getDefaultArtifactOutputPath(newArtifactName, myProject));
    final CompositePackagingElement<?> root = getRootElement();
    if (root instanceof ArchivePackagingElement) {
      String oldFileName = ArtifactUtil.suggestArtifactFileName(oldArtifactName);
      final String name = ((ArchivePackagingElement)root).getArchiveFileName();
      final String fileName = FileUtil.getNameWithoutExtension(name);
      final String extension = FileUtilRt.getExtension(name);
      if (fileName.equals(oldFileName) && extension.length() > 0) {
        myLayoutTreeComponent.editLayout(new Runnable() {
          @Override
          public void run() {
            ((ArchivePackagingElement)getRootElement()).setArchiveFileName(ArtifactUtil.suggestArtifactFileName(newArtifactName) + "." + extension);
          }
        });
        myLayoutTreeComponent.updateRootNode();
      }
    }
  }
}
 
Example #6
Source File: BlazeLibrary.java    From intellij with Apache License 2.0 6 votes vote down vote up
protected static String pathToUrl(File path) {
  String name = path.getName();
  boolean isJarFile =
      FileUtilRt.extensionEquals(name, "jar")
          || FileUtilRt.extensionEquals(name, "srcjar")
          || FileUtilRt.extensionEquals(name, "zip");
  // .jar files require an URL with "jar" protocol.
  String protocol =
      isJarFile
          ? StandardFileSystems.JAR_PROTOCOL
          : VirtualFileSystemProvider.getInstance().getSystem().getProtocol();
  String filePath = FileUtil.toSystemIndependentName(path.getPath());
  String url = VirtualFileManager.constructUrl(protocol, filePath);
  if (isJarFile) {
    url += URLUtil.JAR_SEPARATOR;
  }
  return url;
}
 
Example #7
Source File: ChangeDiffRequestPresentable.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean checkAssociate(final Project project, String fileName, DiffChainContext context) {
  final String pattern = FileUtilRt.getExtension(fileName).toLowerCase();
  if (context.contains(pattern)) return false;
  int rc = Messages.showOkCancelDialog(project,
                                       VcsBundle.message("diff.unknown.file.type.prompt", fileName),
                                       VcsBundle.message("diff.unknown.file.type.title"),
                                       VcsBundle.message("diff.unknown.file.type.associate"),
                                       CommonBundle.getCancelButtonText(),
                                       Messages.getQuestionIcon());
  if (rc == Messages.OK) {
    FileType fileType = FileTypeChooser.associateFileType(fileName);
    return fileType != null && !fileType.isBinary();
  } else {
    context.add(pattern);
  }
  return false;
}
 
Example #8
Source File: ZipUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static File compressFile(@Nonnull File srcFile, @Nonnull File zipFile) throws IOException {
  InputStream is = new FileInputStream(srcFile);
  try {
    ZipOutputStream os = new ZipOutputStream(new FileOutputStream(zipFile));
    try {
      os.putNextEntry(new ZipEntry(srcFile.getName()));
      FileUtilRt.copy(is, os);
      os.closeEntry();
      return zipFile;
    }
    finally {
      os.close();
    }
  }
  finally {
    is.close();
  }
}
 
Example #9
Source File: StartupActionScriptManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(Logger logger) throws IOException {
  if (mySource == null) {
    return;
  }

  if (!mySource.exists()) {
    logger.error("Source file " + mySource.getAbsolutePath() + " does not exist for action " + this);
  }
  else if (!FileUtilRt.delete(mySource)) {
    logger.error("Action " + this + " failed.");

    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  MessageFormat.format("<html>Cannot delete {0}<br>Please, check your access rights on folder <br>{1}", mySource.getAbsolutePath(), mySource.getAbsolutePath()),
                                  "Installing Plugin", JOptionPane.ERROR_MESSAGE);
  }
}
 
Example #10
Source File: BlazeLanguageKindCalculatorHelper.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public OCLanguageKind getLanguageByExtension(Project project, String name) {
  if (Blaze.isBlazeProject(project)) {
    String extension = FileUtilRt.getExtension(name);
    if (CFileExtensions.C_FILE_EXTENSIONS.contains(extension)) {
      return CLanguageKind.C;
    }
    if (CFileExtensions.CXX_FILE_EXTENSIONS.contains(extension)) {
      return CLanguageKind.CPP;
    }
    if (CFileExtensions.CXX_ONLY_HEADER_EXTENSIONS.contains(extension)) {
      return CLanguageKind.CPP;
    }
  }
  return null;
}
 
Example #11
Source File: FileMoveTest.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
private void doMove(String[] checkedFiles, String movedFileSource, String moveTargetDir) {
    myFixture.setTestDataPath(getTestDataPath() + getTestName(true));

    Set<String> filenames = Sets.newHashSet(checkedFiles);
    filenames.add(movedFileSource);

    myFixture.configureByFiles(filenames.toArray(new String[filenames.size()]));

    VirtualFile sourceVirtualFile = myFixture.findFileInTempDir(movedFileSource);
    Assert.assertNotNull(sourceVirtualFile);
    PsiFile sourceFile = myFixture.getPsiManager().findFile(sourceVirtualFile);
    moveFile(moveTargetDir, sourceFile);

    for (String filename : checkedFiles) {
        myFixture.checkResultByFile(filename, FileUtil.getNameWithoutExtension(filename) + "_after." + FileUtilRt.getExtension(filename), false);
    }

    myFixture.checkResultByFile(moveTargetDir + "/" + movedFileSource, moveTargetDir + "/" + FileUtil.getNameWithoutExtension(movedFileSource) + "_after." + FileUtilRt.getExtension(movedFileSource), false);
}
 
Example #12
Source File: VirtualFilePointerManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static String cleanupPath(@Nonnull String path) {
  path = FileUtilRt.toSystemIndependentName(path);
  path = trimTrailingSeparators(path);
  for (int i = 0; i < path.length(); ) {
    int slash = path.indexOf('/', i);
    if (slash == -1 || slash == path.length() - 1) {
      break;
    }
    char next = path.charAt(slash + 1);

    if (next == '/' && !(i == 0 && SystemInfo.isWindows) || // additional condition for Windows UNC
        next == '.' && (slash == path.length() - 2 || path.charAt(slash + 2) == '/')) {
      return cleanupTail(path, slash);
    }
    i = slash + 1;
  }
  return path;
}
 
Example #13
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 #14
Source File: HaxeNamedElementImpl.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
@Override
public PsiElement setName(@NonNls @NotNull String newElementName) throws IncorrectOperationException {
  final HaxeIdentifier identifier = getIdentifier();
  final HaxeIdentifier identifierNew = HaxeElementGenerator.createIdentifierFromText(getProject(), newElementName);

  final String oldName = getName();
  if (identifierNew != null) {
    getNode().replaceChild(identifier.getNode(), identifierNew.getNode());
  }

  if (oldName != null &&
      getParent() instanceof HaxeClass &&
      getParent().getParent() instanceof HaxeFile)
  {
    final HaxeFile haxeFile = (HaxeFile)getParent().getParent();
    if (oldName.equals(FileUtil.getNameWithoutExtension(haxeFile.getName()))) {
      haxeFile.setName(newElementName + "." + FileUtilRt.getExtension(haxeFile.getName()));
    }
  }
  return this;
}
 
Example #15
Source File: BackgroundTaskByVfsChangeTaskImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ReplacePathToMacroMap createReplaceMacroToPathMap() {
  final ReplacePathToMacroMap replacePathToMacroMap = new ReplacePathToMacroMap();
  replacePathToMacroMap.put(myVirtualFilePointer.getFileName(), "$FileName$");
  replacePathToMacroMap.addMacroReplacement(myVirtualFilePointer.getPresentableUrl(), "FilePath");

  File parentFile = FileUtilRt.getParentFile(new File(myVirtualFilePointer.getPresentableUrl()));
  replacePathToMacroMap.addMacroReplacement(parentFile.getAbsolutePath(), "FileParentPath");
  return replacePathToMacroMap;
}
 
Example #16
Source File: BackgroundTaskByVfsChangeTaskImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private ExpandMacroToPathMap createExpandOutMacroToPathMap() {
  final ExpandMacroToPathMap expandMacroToPathMap = new ExpandMacroToPathMap();
  expandMacroToPathMap.addMacroExpand("FileName", myVirtualFilePointer.getFileName());
  expandMacroToPathMap.addMacroExpand("FilePath", myVirtualFilePointer.getPresentableUrl());
  expandMacroToPathMap.addMacroExpand("OutPath", myParameters.getOutPath());

  File parentFile = FileUtilRt.getParentFile(new File(myVirtualFilePointer.getPresentableUrl()));
  expandMacroToPathMap.addMacroExpand("FileParentPath", parentFile.getAbsolutePath());
  return expandMacroToPathMap;
}
 
Example #17
Source File: VcsConfiguration.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void acceptLastCreatedPatchName(final String string) {
  if (StringUtil.isEmptyOrSpaces(string)) return;
  if (FileUtilRt.extensionEquals(string, DIFF)) {
    DEFAULT_PATCH_EXTENSION = DIFF;
  }
  else if (FileUtilRt.extensionEquals(string, PATCH)) {
    DEFAULT_PATCH_EXTENSION = PATCH;
  }
}
 
Example #18
Source File: UniqueNameEditorTabTitleProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String getEditorTabText(String result, String separator, boolean hideKnownExtensionInTabs) {
  if (hideKnownExtensionInTabs) {
    String withoutExtension = FileUtilRt.getNameWithoutExtension(result);
    if (StringUtil.isNotEmpty(withoutExtension) && !withoutExtension.endsWith(separator)) {
      return withoutExtension;
    }
  }
  return result;
}
 
Example #19
Source File: HierarchicalFilePathComparator.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public int compare(@Nonnull FilePath filePath1, @Nonnull FilePath filePath2) {
  final String path1 = FileUtilRt.toSystemIndependentName(filePath1.getPath());
  final String path2 = FileUtilRt.toSystemIndependentName(filePath2.getPath());

  int index1 = 0;
  int index2 = 0;

  int start = 0;

  while (index1 < path1.length() && index2 < path2.length()) {
    char c1 = path1.charAt(index1);
    char c2 = path2.charAt(index2);

    if (StringUtil.compare(c1, c2, myIgnoreCase) != 0) break;

    if (c1 == '/') start = index1;

    index1++;
    index2++;
  }

  if (index1 == path1.length() && index2 == path2.length()) return 0;
  if (index1 == path1.length()) return -1;
  if (index2 == path2.length()) return 1;

  int end1 = path1.indexOf('/', start + 1);
  int end2 = path2.indexOf('/', start + 1);

  String name1 = end1 == -1 ? path1.substring(start) : path1.substring(start, end1);
  String name2 = end2 == -1 ? path2.substring(start) : path2.substring(start, end2);

  boolean isDirectory1 = end1 != -1 || filePath1.isDirectory();
  boolean isDirectory2 = end2 != -1 || filePath2.isDirectory();

  if (isDirectory1 && !isDirectory2) return -1;
  if (!isDirectory1 && isDirectory2) return 1;

  return StringUtil.compare(name1, name2, myIgnoreCase);
}
 
Example #20
Source File: BackgroundTaskByVfsChangeTaskImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public ExpandMacroToPathMap createExpandMacroToPathMap() {
  final ExpandMacroToPathMap expandMacroToPathMap = new ExpandMacroToPathMap();
  expandMacroToPathMap.addMacroExpand("FileName", myVirtualFilePointer.getFileName());
  expandMacroToPathMap.addMacroExpand("FilePath", myVirtualFilePointer.getPresentableUrl());

  File parentFile = FileUtilRt.getParentFile(new File(myVirtualFilePointer.getPresentableUrl()));
  expandMacroToPathMap.addMacroExpand("FileParentPath", parentFile.getAbsolutePath());
  return expandMacroToPathMap;
}
 
Example #21
Source File: DesktopImportantFolderLocker.java    From consulo with Apache License 2.0 5 votes vote down vote up
private <V> V underLocks(@Nonnull Callable<V> action) throws Exception {
  FileUtilRt.createDirectory(new File(myConfigPath));
  try (@SuppressWarnings("unused") FileOutputStream lock1 = new FileOutputStream(new File(myConfigPath, PORT_LOCK_FILE), true)) {
    FileUtilRt.createDirectory(new File(mySystemPath));
    try (@SuppressWarnings("unused") FileOutputStream lock2 = new FileOutputStream(new File(mySystemPath, PORT_LOCK_FILE), true)) {
      return action.call();
    }
  }
}
 
Example #22
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean areTooManyDocumentsInTheQueue(@Nonnull Collection<? extends Document> documents) {
  if (documents.size() > 100) return true;
  int totalSize = 0;
  for (Document document : documents) {
    totalSize += document.getTextLength();
    if (totalSize > FileUtilRt.LARGE_FOR_CONTENT_LOADING) return true;
  }
  return false;
}
 
Example #23
Source File: FileDocumentManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Document getDocument(@Nonnull final VirtualFile file) {
  ApplicationManager.getApplication().assertReadAccessAllowed();
  DocumentEx document = (DocumentEx)getCachedDocument(file);
  if (document == null) {
    if (!file.isValid() || file.isDirectory() || isBinaryWithoutDecompiler(file)) return null;

    boolean tooLarge = FileUtilRt.isTooLarge(file.getLength());
    if (file.getFileType().isBinary() && tooLarge) return null;

    final CharSequence text = tooLarge ? LoadTextUtil.loadText(file, getPreviewCharCount(file)) : LoadTextUtil.loadText(file);
    synchronized (lock) {
      document = (DocumentEx)getCachedDocument(file);
      if (document != null) return document; // Double checking

      document = (DocumentEx)createDocument(text, file);
      document.setModificationStamp(file.getModificationStamp());
      document.putUserData(BIG_FILE_PREVIEW, tooLarge ? Boolean.TRUE : null);
      final FileType fileType = file.getFileType();
      document.setReadOnly(tooLarge || !file.isWritable() || fileType.isBinary());

      if (!(file instanceof LightVirtualFile || file.getFileSystem() instanceof NonPhysicalFileSystem)) {
        document.addDocumentListener(myPhysicalDocumentChangeTracker);
      }

      if (file instanceof LightVirtualFile) {
        registerDocument(document, file);
      }
      else {
        document.putUserData(FILE_KEY, file);
        cacheDocument(file, document);
      }
    }

    myMultiCaster.fileContentLoaded(file, document);
  }

  return document;
}
 
Example #24
Source File: FileTypeManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private FileType detectFromContent(@Nonnull VirtualFile file, @Nullable byte[] content, @Nonnull Iterable<? extends FileTypeDetector> detectors) throws IOException {
  FileType fileType;
  if (content != null) {
    fileType = detect(file, content, content.length, detectors);
  }
  else {
    try (InputStream inputStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
      if (toLog()) {
        log("F: detectFromContentAndCache(" + file.getName() + "):" + " inputStream=" + streamInfo(inputStream));
      }

      int fileLength = (int)file.getLength();

      int bufferLength = StreamSupport.stream(detectors.spliterator(), false).map(FileTypeDetector::getDesiredContentPrefixLength).max(Comparator.naturalOrder()).orElse(FileUtilRt.getUserContentLoadLimit());
      byte[] buffer = fileLength <= FileUtilRt.THREAD_LOCAL_BUFFER_LENGTH ? FileUtilRt.getThreadLocalBuffer() : new byte[Math.min(fileLength, bufferLength)];

      int n = readSafely(inputStream, buffer, 0, buffer.length);
      fileType = detect(file, buffer, n, detectors);

      if (toLog()) {
        try (InputStream newStream = ((FileSystemInterface)file.getFileSystem()).getInputStream(file)) {
          byte[] buffer2 = new byte[50];
          int n2 = newStream.read(buffer2, 0, buffer2.length);
          log("F: detectFromContentAndCache(" + file.getName() + "): result: " + fileType.getName() +
              "; stream: " + streamInfo(inputStream) +
              "; newStream: " + streamInfo(newStream) +
              "; read: " + n2 +
              "; buffer: " + Arrays.toString(buffer2));
        }
      }
    }
  }

  if (LOG.isDebugEnabled()) {
    LOG.debug(file + "; type=" + fileType.getDescription() + "; " + counterAutoDetect);
  }
  return fileType;
}
 
Example #25
Source File: DesktopImportantFolderLocker.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void addExistingPort(@Nonnull File portMarker, @Nonnull String path, @Nonnull MultiMap<Integer, String> portToPath) {
  if (portMarker.exists()) {
    try {
      portToPath.putValue(Integer.parseInt(FileUtilRt.loadFile(portMarker)), path);
    }
    catch (Exception e) {
      log(e);
      // don't delete - we overwrite it on write in any case
    }
  }
}
 
Example #26
Source File: FirefoxSettingsConfigurable.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void reset() {
  File defaultFile = FirefoxUtil.getDefaultProfileIniPath();
  myDefaultProfilesIniPath = defaultFile != null ? defaultFile.getAbsolutePath() : "";

  String path = mySettings.getProfilesIniPath();
  myProfilesIniPathField.setText(path != null ? FileUtilRt.toSystemDependentName(path) : myDefaultProfilesIniPath);
  updateProfilesList();
  myProfileCombobox.setSelectedItem(ObjectUtil.notNull(mySettings.getProfile(), myDefaultProfile));
}
 
Example #27
Source File: HttpRequests.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public File saveToFile(@Nonnull File file, @Nullable ProgressIndicator indicator) throws IOException {
  FileUtilRt.createParentDirs(file);

  boolean deleteFile = true;
  try {
    OutputStream out = new FileOutputStream(file);
    try {
      NetUtils.copyStreamContent(indicator, getInputStream(), out, getConnection().getContentLength());
      deleteFile = false;
    }
    catch (IOException e) {
      throw new IOException(createErrorMessage(e, this, false), e);
    }
    finally {
      out.close();
    }
  }
  finally {
    if (deleteFile) {
      FileUtilRt.delete(file);
    }
  }

  return file;
}
 
Example #28
Source File: PlatformTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static File createTempDir(@NonNls final String prefix, final boolean refresh) throws IOException {
  final File tempDirectory = FileUtilRt.createTempDirectory(TEST_DIR_PREFIX + prefix, null, false);
  myFilesToDelete.add(tempDirectory);
  if (refresh) {
    getVirtualFile(tempDirectory);
  }
  return tempDirectory;
}
 
Example #29
Source File: CodeInsightTestUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void doActionTest(AnAction action, String file, CodeInsightTestFixture fixture) {
  String extension = FileUtilRt.getExtension(file);
  String name = FileUtil.getNameWithoutExtension(file);
  fixture.configureByFile(file);
  fixture.testAction(action);
  fixture.checkResultByFile(name + "_after." + extension);
}
 
Example #30
Source File: GotoFileItemProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private JBIterable<FoundItemDescriptor<PsiFileSystemItem>> getFilesMatchingPath(@Nonnull FindSymbolParameters parameters,
                                                                                @Nonnull List<MatchResult> fileNames,
                                                                                @Nonnull DirectoryPathMatcher dirMatcher,
                                                                                @Nonnull ProgressIndicator indicator) {
  GlobalSearchScope scope = dirMatcher.narrowDown(parameters.getSearchScope());
  FindSymbolParameters adjusted = parameters.withScope(scope);

  List<List<MatchResult>> sortedNames = sortAndGroup(fileNames, Comparator.comparing(mr -> StringUtil.toLowerCase(FileUtilRt.getNameWithoutExtension(mr.elementName))));
  return JBIterable.from(sortedNames).flatMap(nameGroup -> getItemsForNames(indicator, adjusted, nameGroup));
}