public void testToUri() {
    if (!SystemInfo.isWindows) {
      assertEquals("file:///asd", VfsUtil.toUri(new File("/asd")).toASCIIString());
      assertEquals("file:///asd%20/sd", VfsUtil.toUri(new File("/asd /sd")).toASCIIString());
    }

    URI uri = VfsUtil.toUri("file:///asd");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd", uri.getPath());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#test");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd/ ads/ad", uri.getPath());
    assertEquals("test", uri.getFragment());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#");
    assertNotNull(uri);
    assertEquals("file:///asd/%20ads/ad#", uri.toString());

    uri = VfsUtil.toUri("mailto:[email protected]");
    assertNotNull(uri);
    assertEquals("*****@*****.**", uri.getSchemeSpecificPart());

    if (SystemInfo.isWindows) {
      uri = VfsUtil.toUri("file://C:/p");
      assertNotNull(uri);
      assertEquals("file", uri.getScheme());
      assertEquals("/C:/p", uri.getPath());
    }

    uri = VfsUtil.toUri("file:///Users/S pace");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/Users/S pace", uri.getPath());
    assertEquals("/Users/S%20pace", uri.getRawPath());
    assertEquals("file:///Users/S%20pace", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals("http://developer.android.com/guide/developing/tools/avd.html", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals(
        "http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd", uri.toString());
    assertEquals("f=23r2ewd", uri.getQuery());
  }
  @NotNull
  private static List<VirtualFile> findClasses(File file, boolean isJre) {
    List<VirtualFile> result = ContainerUtil.newArrayList();
    VirtualFileManager fileManager = VirtualFileManager.getInstance();

    String path = file.getPath();
    if (JrtFileSystem.isModularJdk(path)) {
      String url =
          VirtualFileManager.constructUrl(
              JrtFileSystem.PROTOCOL,
              FileUtil.toSystemIndependentName(path) + JrtFileSystem.SEPARATOR);
      for (String module : JrtFileSystem.listModules(path)) {
        ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url + module));
      }
    }

    for (File root : JavaSdkUtil.getJdkClassesRoots(file, isJre)) {
      String url = VfsUtil.getUrlForLibraryRoot(root);
      ContainerUtil.addIfNotNull(result, fileManager.findFileByUrl(url));
    }

    Collections.sort(result, (o1, o2) -> o1.getPath().compareTo(o2.getPath()));

    return result;
  }
 synchronized void clearPointerCaches(String url, VirtualFilePointerListener listener) {
   TreeMap<String, VirtualFilePointerImpl> urlToPointer = myUrlToPointerMaps.get(listener);
   if (urlToPointer == null && ApplicationManager.getApplication().isUnitTestMode()) return;
   assert urlToPointer != null;
   urlToPointer.remove(VfsUtil.urlToPath(url));
   if (urlToPointer.isEmpty()) {
     myUrlToPointerMaps.remove(listener);
   }
 }
Beispiel #4
0
  private PathsList removeFrameworkStuff(Module module, List<VirtualFile> rootFiles) {
    final List<File> toExclude = getImplicitClasspathRoots(module);
    if (LOG.isDebugEnabled()) {
      LOG.debug("Before removing framework stuff: " + rootFiles);
      LOG.debug("Implicit roots:" + toExclude);
    }

    PathsList scriptClassPath = new PathsList();
    eachRoot:
    for (VirtualFile file : rootFiles) {
      for (final File excluded : toExclude) {
        if (VfsUtil.isAncestor(excluded, VfsUtil.virtualToIoFile(file), false)) {
          continue eachRoot;
        }
      }
      scriptClassPath.add(file);
    }
    return scriptClassPath;
  }
  public void testFindFileByUrl() throws Exception {
    File file1 = new File(PathManagerEx.getTestDataPath());
    file1 = new File(file1, "vfs");
    file1 = new File(file1, "findFileByUrl");
    VirtualFile file0 = VfsUtil.findFileByURL(file1.toURI().toURL());
    assertNotNull(file0);
    assertTrue(file0.isDirectory());
    final VirtualFile[] children = file0.getChildren();
    List<VirtualFile> list = new ArrayList<VirtualFile>();
    final VirtualFileFilter fileFilter =
        new VirtualFileFilter() {
          @Override
          public boolean accept(VirtualFile file) {
            return !file.getName().endsWith(".new");
          }
        };
    for (VirtualFile child : children) {
      if (fileFilter.accept(child)) {
        list.add(child);
      }
    }
    assertEquals(2, list.size()); // "CVS" dir ignored

    File file2 = new File(file1, "test.zip");
    URL url2 = file2.toURI().toURL();
    url2 = new URL("jar", "", url2.toExternalForm() + "!/");
    url2 = new URL(url2, "com/intellij/installer");
    url2 = new URL(url2.toExternalForm());
    file0 = VfsUtil.findFileByURL(url2);
    assertNotNull(file0);
    assertTrue(file0.isDirectory());

    File file3 = new File(file1, "1.txt");
    file0 = VfsUtil.findFileByURL(file3.toURI().toURL());
    String content = VfsUtilCore.loadText(file0);
    assertNotNull(file0);
    assertFalse(file0.isDirectory());
    assertEquals(content, "test text");
  }
 private static boolean clearReadOnly(final Project project, final File dstFile) {
   //noinspection EmptyCatchBlock
   final URL url;
   try {
     url = dstFile.toURL();
   } catch (MalformedURLException e) {
     return true;
   }
   final VirtualFile vfile = VfsUtil.findFileByURL(url);
   return vfile == null
       || !ReadonlyStatusHandler.getInstance(project)
           .ensureFilesWritable(vfile)
           .hasReadonlyFiles();
 }
Beispiel #7
0
  protected List<File> getImplicitClasspathRoots(@NotNull Module module) {
    final List<File> toExclude = new ArrayList<File>();

    VirtualFile sdkRoot = getSdkRoot(module);
    if (sdkRoot != null) toExclude.add(VfsUtil.virtualToIoFile(sdkRoot));

    ContainerUtil.addIfNotNull(getCommonPluginsDir(module), toExclude);
    final VirtualFile appRoot = findAppRoot(module);
    if (appRoot != null) {
      VirtualFile pluginDir = appRoot.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY);
      if (pluginDir != null) toExclude.add(VfsUtil.virtualToIoFile(pluginDir));

      VirtualFile libDir = appRoot.findChild("lib");
      if (libDir != null) toExclude.add(VfsUtil.virtualToIoFile(libDir));
    }

    final Library library = MvcModuleStructureUtil.findUserLibrary(module, getUserLibraryName());
    if (library != null) {
      for (VirtualFile file : library.getFiles(OrderRootType.CLASSES)) {
        toExclude.add(VfsUtil.virtualToIoFile(PathUtil.getLocalFile(file)));
      }
    }
    return toExclude;
  }
 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);
 }
 private static VirtualFile[] getFilesToCheckReadonlyStatus(
     GeneratingCompiler.GenerationItem[] items) {
   List<VirtualFile> filesToCheck = new ArrayList<VirtualFile>();
   for (GeneratingCompiler.GenerationItem item : items) {
     if (item instanceof AndroidAptCompiler.AptGenerationItem) {
       final Set<File> generatedFiles =
           ((AndroidAptCompiler.AptGenerationItem) item).getGeneratedFiles().keySet();
       for (File generatedFile : generatedFiles) {
         if (generatedFile.exists()) {
           VirtualFile generatedVFile =
               LocalFileSystem.getInstance().findFileByIoFile(generatedFile);
           if (generatedVFile != null) {
             filesToCheck.add(generatedVFile);
           }
         }
       }
     }
   }
   return VfsUtil.toVirtualFileArray(filesToCheck);
 }
  public static VirtualFile createTestProjectStructure(
      String tempName,
      Module module,
      String rootPath,
      Collection<File> filesToDelete,
      boolean addProjectRoots)
      throws IOException {
    File dir = FileUtil.createTempDirectory(tempName, null, false);
    filesToDelete.add(dir);

    VirtualFile vDir =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/'));
    assert vDir != null && vDir.isDirectory() : dir;
    PlatformTestCase.synchronizeTempDirVfs(vDir);

    EdtTestUtil.runInEdtAndWait(
        () -> {
          AccessToken token = WriteAction.start();
          try {
            if (rootPath != null) {
              VirtualFile vDir1 =
                  LocalFileSystem.getInstance()
                      .findFileByPath(rootPath.replace(File.separatorChar, '/'));
              if (vDir1 == null) {
                throw new Exception(rootPath + " not found");
              }
              VfsUtil.copyDirectory(null, vDir1, vDir, null);
            }

            if (addProjectRoots) {
              addSourceContentToRoots(module, vDir);
            }
          } finally {
            token.finish();
          }
        });
    return vDir;
  }
  @NotNull
  private FSRecords.NameId[] persistAllChildren(
      @NotNull final VirtualFile file, final int id, @NotNull FSRecords.NameId[] current) {
    assert file != mySuperRoot;
    final NewVirtualFileSystem fs = replaceWithNativeFS(getDelegate(file));

    String[] delegateNames = VfsUtil.filterNames(fs.list(file));
    if (delegateNames.length == 0 && current.length > 0) {
      return current;
    }

    Set<String> toAdd = ContainerUtil.newHashSet(delegateNames);
    for (FSRecords.NameId nameId : current) {
      toAdd.remove(nameId.name);
    }

    final TIntArrayList childrenIds = new TIntArrayList(current.length + toAdd.size());
    final List<FSRecords.NameId> nameIds =
        ContainerUtil.newArrayListWithExpectedSize(current.length + toAdd.size());
    for (FSRecords.NameId nameId : current) {
      childrenIds.add(nameId.id);
      nameIds.add(nameId);
    }
    for (String newName : toAdd) {
      FakeVirtualFile child = new FakeVirtualFile(file, newName);
      FileAttributes attributes = fs.getAttributes(child);
      if (attributes != null) {
        int childId = createAndFillRecord(fs, child, id, attributes);
        childrenIds.add(childId);
        nameIds.add(new FSRecords.NameId(childId, FileNameCache.storeName(newName), newName));
      }
    }

    FSRecords.updateList(id, childrenIds.toNativeArray());
    setChildrenCached(id);

    return nameIds.toArray(new FSRecords.NameId[nameIds.size()]);
  }
    @Override
    public void after(@NotNull final List<? extends VFileEvent> events) {
      cleanContainerCaches();

      if (myUrlsToUpdate == null) {
        return;
      }
      for (String url : myUrlsToUpdate) {
        synchronized (VirtualFilePointerManagerImpl.this) {
          for (TreeMap<String, VirtualFilePointerImpl> urlToPointer : myUrlToPointerMaps.values()) {
            VirtualFilePointerImpl pointer = urlToPointer.remove(url);
            if (pointer != null) {
              String path = VfsUtil.urlToPath(pointer.getUrl());
              urlToPointer.put(path, pointer);
            }
          }
        }
      }

      for (VirtualFilePointer pointer : myPointersToUpdate) {
        ((VirtualFilePointerImpl) pointer).update();
      }

      for (EventDescriptor event : myEvents) {
        event.fireAfter();
      }

      if (!myPointersToUpdate.isEmpty()) {
        VirtualFilePointer[] arr =
            myPointersToUpdate.toArray(new VirtualFilePointer[myPointersToUpdate.size()]);
        myBus.syncPublisher(VirtualFilePointerListener.TOPIC).validityChanged(arr);
      }

      myUrlsToUpdate = null;
      myEvents = null;
      myPointersToUpdate = null;
    }
  @Nullable
  public static String findResourcesCacheDirectory(
      @NotNull Module module, boolean createIfNotFound, @Nullable CompileContext context) {
    final Project project = module.getProject();

    final CompilerProjectExtension extension = CompilerProjectExtension.getInstance(project);
    if (extension == null) {
      if (context != null) {
        context.addMessage(
            CompilerMessageCategory.ERROR,
            "Cannot get compiler settings for project " + project.getName(),
            null,
            -1,
            -1);
      }
      return null;
    }

    final String projectOutputDirUrl = extension.getCompilerOutputUrl();
    if (projectOutputDirUrl == null) {
      if (context != null) {
        context.addMessage(
            CompilerMessageCategory.ERROR,
            "Cannot find output directory for project " + project.getName(),
            null,
            -1,
            -1);
      }
      return null;
    }

    final String pngCacheDirPath =
        VfsUtil.urlToPath(projectOutputDirUrl)
            + '/'
            + RESOURCES_CACHE_DIR_NAME
            + '/'
            + module.getName();
    final String pngCacheDirOsPath = FileUtil.toSystemDependentName(pngCacheDirPath);

    final File pngCacheDir = new File(pngCacheDirOsPath);
    if (pngCacheDir.exists()) {
      if (pngCacheDir.isDirectory()) {
        return pngCacheDirOsPath;
      } else {
        if (context != null) {
          context.addMessage(
              CompilerMessageCategory.ERROR,
              "Cannot create directory " + pngCacheDirOsPath + " because file already exists",
              null,
              -1,
              -1);
        }
        return null;
      }
    }

    if (!createIfNotFound) {
      return null;
    }

    if (!pngCacheDir.mkdirs()) {
      if (context != null) {
        context.addMessage(
            CompilerMessageCategory.ERROR,
            "Cannot create directory " + pngCacheDirOsPath,
            null,
            -1,
            -1);
      }
      return null;
    }

    return pngCacheDirOsPath;
  }