public void testNonCanonicallyNamedFileRoot() throws Exception {
    if (SystemInfo.isFileSystemCaseSensitive) {
      System.err.println("Ignored: case-insensitive FS required");
      return;
    }

    File file = createTestFile("test.txt");
    refresh(file);

    String watchRoot = file.getAbsolutePath().toUpperCase(Locale.US);
    LocalFileSystem.WatchRequest request = watch(new File(watchRoot));
    try {
      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileContentChangeEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.delete(file);
      assertEvent(VFileDeleteEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "re-creation");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());
    } finally {
      unwatch(request);
      delete(file);
    }
  }
  public void testDirectoryMixed() throws Exception {
    File topDir = createTestDir("top");
    File watchedFile1 = createTestFile(topDir, "test.txt");
    File sub1Dir = createTestDir(topDir, "sub1");
    File unwatchedFile = createTestFile(sub1Dir, "test.txt");
    File sub2Dir = createTestDir(topDir, "sub2");
    File sub2subDir = createTestDir(sub2Dir, "sub");
    File watchedFile2 = createTestFile(sub2subDir, "test.txt");
    refresh(topDir);

    LocalFileSystem.WatchRequest topRequest = watch(topDir, false);
    LocalFileSystem.WatchRequest subRequest = watch(sub2Dir);
    try {
      myAccept = true;
      FileUtil.writeToFile(watchedFile1, "new content");
      FileUtil.writeToFile(watchedFile2, "new content");
      FileUtil.writeToFile(unwatchedFile, "new content");
      assertEvent(
          VFileContentChangeEvent.class,
          watchedFile1.getAbsolutePath(),
          watchedFile2.getAbsolutePath());
    } finally {
      unwatch(subRequest, topRequest);
      delete(topDir);
    }
  }
  public void testDirectoryRecursive() throws Exception {
    File topDir = createTestDir("top");
    refresh(topDir);

    LocalFileSystem.WatchRequest request = watch(topDir);
    try {
      myAccept = true;
      File subDir = createTestDir(topDir, "sub");
      assertEvent(VFileCreateEvent.class, subDir.getAbsolutePath());
      refresh(subDir);

      myAccept = true;
      File file = createTestFile(subDir, "test.txt");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileContentChangeEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.delete(file);
      assertEvent(VFileDeleteEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "re-creation");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());
    } finally {
      unwatch(request);
      delete(topDir);
    }
  }
  public void testDirectoryOverlapping() throws Exception {
    File topDir = createTestDir("top");
    File fileInTopDir = createTestFile(topDir, "file1.txt");
    File subDir = createTestDir(topDir, "sub");
    File fileInSubDir = createTestFile(subDir, "file2.txt");
    File sideDir = createTestDir("side");
    File fileInSideDir = createTestFile(sideDir, "file3.txt");
    refresh(topDir);
    refresh(sideDir);

    LocalFileSystem.WatchRequest requestForSubDir = watch(subDir);
    LocalFileSystem.WatchRequest requestForSideDir = watch(sideDir);
    try {
      myAccept = true;
      FileUtil.writeToFile(fileInTopDir, "new content");
      FileUtil.writeToFile(fileInSubDir, "new content");
      FileUtil.writeToFile(fileInSideDir, "new content");
      assertEvent(
          VFileContentChangeEvent.class,
          fileInSubDir.getAbsolutePath(),
          fileInSideDir.getAbsolutePath());

      LocalFileSystem.WatchRequest requestForTopDir = watch(topDir);
      try {
        myAccept = true;
        FileUtil.writeToFile(fileInTopDir, "newer content");
        FileUtil.writeToFile(fileInSubDir, "newer content");
        FileUtil.writeToFile(fileInSideDir, "newer content");
        assertEvent(
            VFileContentChangeEvent.class,
            fileInTopDir.getAbsolutePath(),
            fileInSubDir.getAbsolutePath(),
            fileInSideDir.getAbsolutePath());
      } finally {
        unwatch(requestForTopDir);
      }

      myAccept = true;
      FileUtil.writeToFile(fileInTopDir, "newest content");
      FileUtil.writeToFile(fileInSubDir, "newest content");
      FileUtil.writeToFile(fileInSideDir, "newest content");
      assertEvent(
          VFileContentChangeEvent.class,
          fileInSubDir.getAbsolutePath(),
          fileInSideDir.getAbsolutePath());

      myAccept = true;
      FileUtil.delete(fileInTopDir);
      FileUtil.delete(fileInSubDir);
      FileUtil.delete(fileInSideDir);
      assertEvent(
          VFileDeleteEvent.class,
          fileInTopDir.getAbsolutePath(),
          fileInSubDir.getAbsolutePath(),
          fileInSideDir.getAbsolutePath());
    } finally {
      unwatch(requestForSubDir, requestForSideDir);
      delete(topDir);
    }
  }
  public void testSubst() throws Exception {
    if (!SystemInfo.isWindows) {
      System.err.println("Ignored: Windows required");
      return;
    }

    File targetDir = createTestDir("top");
    File subDir = createTestDir(targetDir, "sub");
    File file = createTestFile(subDir, "test.txt");
    File rootFile = createSubst(targetDir.getAbsolutePath());
    VirtualDirectoryImpl.allowRootAccess(rootFile.getPath());
    VirtualFile vfsRoot = myFileSystem.findFileByIoFile(rootFile);

    try {
      assertNotNull(rootFile.getPath(), vfsRoot);
      File substDir = new File(rootFile, subDir.getName());
      File substFile = new File(substDir, file.getName());
      refresh(targetDir);
      refresh(substDir);

      LocalFileSystem.WatchRequest request = watch(substDir);
      try {
        myAccept = true;
        FileUtil.writeToFile(file, "new content");
        assertEvent(VFileContentChangeEvent.class, substFile.getAbsolutePath());

        LocalFileSystem.WatchRequest request2 = watch(targetDir);
        try {
          myAccept = true;
          FileUtil.delete(file);
          assertEvent(VFileDeleteEvent.class, file.getAbsolutePath(), substFile.getAbsolutePath());
        } finally {
          unwatch(request2);
        }

        myAccept = true;
        FileUtil.writeToFile(file, "re-creation");
        assertEvent(VFileCreateEvent.class, substFile.getAbsolutePath());
      } finally {
        unwatch(request);
      }
    } finally {
      delete(targetDir);
      IoTestUtil.deleteSubst(rootFile.getPath());
      if (vfsRoot != null) {
        ((NewVirtualFile) vfsRoot).markDirty();
        myFileSystem.refresh(false);
      }
      VirtualDirectoryImpl.disallowRootAccess(rootFile.getPath());
    }
  }
  public void testFileLength() throws Exception {
    File file = FileUtil.createTempFile("test", "txt");
    FileUtil.writeToFile(file, "hello");
    VirtualFile virtualFile = LocalFileSystem.getInstance().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());
  }
  public void testRefreshSeesLatestDirectoryContents() throws Exception {
    File testDir = FileUtil.createTempDirectory("RefreshChildrenTest." + getName(), null);
    String content = "";
    FileUtil.writeToFile(new File(testDir, "Foo.java"), content);

    LocalFileSystem local = LocalFileSystem.getInstance();
    VirtualFile virtualDir = local.findFileByIoFile(testDir);
    assert virtualDir != null : testDir;
    virtualDir.getChildren();
    virtualDir.refresh(false, true);
    checkChildCount(virtualDir, 1);

    FileUtil.writeToFile(new File(testDir, "Bar.java"), content);
    virtualDir.refresh(false, true);
    checkChildCount(virtualDir, 2);
  }
 public static void generateStubs(Framework framework, File location) {
   final StringBuilder builder = new StringBuilder();
   builder
       .append("# This is a machine generated stub for: ")
       .append(framework.getName())
       .append("\n");
   builder
       .append("# Created on: ")
       .append(DateFormatUtil.formatDateTime(new Date()))
       .append("\n\n");
   for (Class aClass : framework.getClasses()) {
     generateClassStub(builder, framework, aClass);
   }
   for (Function function : framework.getFunctions()) {
     generateFunctionStub(builder, function, "");
   }
   for (Constant constant : framework.getConstants()) {
     generateConstantStub(builder, constant);
   }
   for (Map.Entry<String, String> entry : framework.getFunctionAliases().entrySet()) {
     generateAlias(builder, entry);
   }
   try {
     FileUtil.writeToFile(location, builder.toString());
   } catch (Throwable ignored) {
   }
 }
Ejemplo n.º 9
0
  public static void assertEqualsToFile(
      @NotNull File expectedFile,
      @NotNull String actual,
      @NotNull Function1<String, String> sanitizer) {
    try {
      String actualText =
          JetTestUtilsKt.trimTrailingWhitespacesAndAddNewlineAtEOF(
              StringUtil.convertLineSeparators(actual.trim()));

      if (!expectedFile.exists()) {
        FileUtil.writeToFile(expectedFile, actualText);
        Assert.fail("Expected data file did not exist. Generating: " + expectedFile);
      }
      String expected = FileUtil.loadFile(expectedFile, CharsetToolkit.UTF8, true);

      String expectedText =
          JetTestUtilsKt.trimTrailingWhitespacesAndAddNewlineAtEOF(
              StringUtil.convertLineSeparators(expected.trim()));

      if (!Comparing.equal(sanitizer.invoke(expectedText), sanitizer.invoke(actualText))) {
        throw new FileComparisonFailure(
            "Actual data differs from file content: " + expectedFile.getName(),
            expected,
            actual,
            expectedFile.getAbsolutePath());
      }
    } catch (IOException e) {
      throw ExceptionUtilsKt.rethrow(e);
    }
  }
  protected void doTest(String xmlPath) throws IOException {
    File txtFile = new File(FileUtil.getNameWithoutExtension(xmlPath) + ".txt");

    ModuleScriptData result =
        ModuleXmlParser.parseModuleScript(
            xmlPath,
            new MessageCollector() {
              @Override
              public void report(
                  @NotNull CompilerMessageSeverity severity,
                  @NotNull String message,
                  @NotNull CompilerMessageLocation location) {
                throw new AssertionError(
                    MessageRenderer.PLAIN_FULL_PATHS.render(severity, message, location));
              }
            });

    StringBuilder sb = new StringBuilder();
    for (Module module : result.getModules()) {
      sb.append(moduleToString(module)).append("\n");
    }

    String actual = sb.toString();

    if (!txtFile.exists()) {
      FileUtil.writeToFile(txtFile, actual);
      fail("Expected data file does not exist. A new file created: " + txtFile);
    }

    JetTestUtils.assertEqualsToFile(txtFile, actual);
  }
 protected static void change(String filePath, final @Nullable String newContent) {
   try {
     File file = new File(FileUtil.toSystemDependentName(filePath));
     assertTrue("File " + file.getAbsolutePath() + " doesn't exist", file.exists());
     if (newContent != null) {
       FileUtil.writeToFile(file, newContent);
     }
     long oldTimestamp = FileSystemUtil.lastModified(file);
     long time = System.currentTimeMillis();
     setLastModified(file, time);
     if (FileSystemUtil.lastModified(file) <= oldTimestamp) {
       setLastModified(file, time + 1);
       long newTimeStamp = FileSystemUtil.lastModified(file);
       if (newTimeStamp <= oldTimestamp) {
         // Mac OS and some versions of Linux truncates timestamp to nearest second
         setLastModified(file, time + 1000);
         newTimeStamp = FileSystemUtil.lastModified(file);
         assertTrue(
             "Failed to change timestamp for " + file.getAbsolutePath(),
             newTimeStamp > oldTimestamp);
       }
       sleepUntil(newTimeStamp);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 12
0
 public void testContextFileRepair() throws Exception {
   WorkingContextManager manager = getContextManager();
   manager.saveContext("foo", "bar");
   File file = manager.getContextFile();
   assertTrue(file.length() > 0);
   FileUtil.writeToFile(file, "123"); // corrupt it
   manager.saveContext("foo", "bar");
 }
 public String createFile(String relativePath, final String text) {
   try {
     File file = new File(getOrCreateProjectDir(), relativePath);
     FileUtil.writeToFile(file, text);
     return FileUtil.toSystemIndependentName(file.getAbsolutePath());
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 14
0
 public static void writeToOutputDirectory(ClassFileFactory factory, @NotNull File outputDir) {
   List<String> files = factory.files();
   for (String file : files) {
     File target = new File(outputDir, file);
     try {
       FileUtil.writeToFile(target, factory.asBytes(file));
     } catch (IOException e) {
       throw new CompileEnvironmentException(e);
     }
   }
 }
 protected File createTempFile(String name, @Nullable String text) throws IOException {
   File directory = createTempDirectory();
   File file = new File(directory, name);
   if (!file.createNewFile()) {
     throw new IOException("Can't create " + file);
   }
   if (text != null) {
     FileUtil.writeToFile(file, text);
   }
   return file;
 }
  public void testExternalFileModificationWhileProjectClosed() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {});
    FileBasedIndex.getInstance()
        .getContainingFiles(
            TodoIndex.NAME,
            new TodoIndexEntry("todo", true),
            GlobalSearchScope.allScope(getProject()));

    final String projectLocation = myProject.getPresentableUrl();
    assert projectLocation != null : myProject;
    PlatformTestUtil.saveProject(myProject);
    final VirtualFile content = ModuleRootManager.getInstance(getModule()).getContentRoots()[0];
    Project project = myProject;
    ProjectUtil.closeAndDispose(project);
    InjectedLanguageManagerImpl.checkInjectorsAreDisposed(project);

    assertTrue("Project was not disposed", myProject.isDisposed());
    myModule = null;

    final File file = new File(root.getPath(), "1.java");
    assertTrue(file.exists());

    FileUtil.writeToFile(file, "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    root.refresh(false, true);

    LocalFileSystem.getInstance().refresh(false);

    myProject = ProjectManager.getInstance().loadAndOpenProject(projectLocation);
    InjectedLanguageManagerImpl.pushInjectors(getProject());

    setUpModule();
    setUpJdk();
    ProjectManagerEx.getInstanceEx().openTestProject(myProject);
    UIUtil.dispatchAllInvocationEvents(); // startup activities

    runStartupActivities();
    PsiTestUtil.addSourceContentToRoots(getModule(), content);

    assertNotNull(myProject);
    myPsiManager = (PsiManagerImpl) PsiManager.getInstance(myProject);
    myJavaFacade = JavaPsiFacadeEx.getInstanceEx(myProject);

    objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"1.java"});
  }
  @Nullable
  private String fetchOneFile(
      final ProgressIndicator indicator,
      final String resourceUrl,
      final Project project,
      String extResourcesPath,
      @Nullable String refname)
      throws IOException {
    SwingUtilities.invokeLater(
        () -> indicator.setText(XmlBundle.message("fetching.progress.indicator", resourceUrl)));

    FetchResult result = fetchData(project, resourceUrl, indicator);
    if (result == null) return null;

    if (!resultIsValid(project, indicator, resourceUrl, result)) {
      return null;
    }

    int slashIndex = resourceUrl.lastIndexOf('/');
    String resPath = extResourcesPath + File.separatorChar;

    if (refname != null) { // resource is known under ref.name so need to save it
      resPath += refname;
      int refNameSlashIndex = resPath.lastIndexOf('/');
      if (refNameSlashIndex != -1) {
        final File parent = new File(resPath.substring(0, refNameSlashIndex));
        if (!parent.mkdirs() || !parent.exists()) {
          LOG.warn("Unable to create: " + parent);
        }
      }
    } else {
      resPath +=
          Integer.toHexString(resourceUrl.hashCode()) + "_" + resourceUrl.substring(slashIndex + 1);
    }

    final int lastDoPosInResourceUrl = resourceUrl.lastIndexOf('.', slashIndex);
    if (lastDoPosInResourceUrl == -1
        || FileTypeManager.getInstance()
                .getFileTypeByExtension(resourceUrl.substring(lastDoPosInResourceUrl + 1))
            == FileTypes.UNKNOWN) {
      // remote url does not contain file with extension
      final String extension =
          result.contentType != null && result.contentType.contains(HTML_MIME)
              ? StdFileTypes.HTML.getDefaultExtension()
              : StdFileTypes.XML.getDefaultExtension();
      resPath += "." + extension;
    }

    File res = new File(resPath);

    FileUtil.writeToFile(res, result.bytes);
    return resPath;
  }
  public void testFileRoot() throws Exception {
    File file = createTestFile("test.txt");
    refresh(file);

    LocalFileSystem.WatchRequest request = watch(file);
    try {
      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileContentChangeEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.delete(file);
      assertEvent(VFileDeleteEvent.class, file.getAbsolutePath());

      myAccept = true;
      FileUtil.writeToFile(file, "re-creation");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());
    } finally {
      unwatch(request);
      delete(file);
    }
  }
  public void testSwitchingToFsRoot() throws Exception {
    File topDir = createTestDir("top");
    File rootDir = createTestDir(topDir, "root");
    File file1 = createTestFile(topDir, "1.txt");
    File file2 = createTestFile(rootDir, "2.txt");
    refresh(topDir);

    File fsRoot =
        new File(
            SystemInfo.isUnix
                ? "/"
                : topDir.getPath().substring(0, topDir.getPath().indexOf(File.separatorChar))
                    + "\\");
    assertTrue("can't guess root of " + topDir, fsRoot.exists());

    LocalFileSystem.WatchRequest request = watch(rootDir);
    try {
      myAccept = true;
      FileUtil.writeToFile(file1, "abc");
      FileUtil.writeToFile(file2, "abc");
      assertEvent(VFileContentChangeEvent.class, file2.getPath());

      LocalFileSystem.WatchRequest rootRequest = watch(fsRoot);
      try {
        myTimeout = 10 * INTER_RESPONSE_DELAY;
        myAccept = true;
        FileUtil.writeToFile(file1, "12345");
        FileUtil.writeToFile(file2, "12345");
        assertEvent(VFileContentChangeEvent.class, file1.getPath(), file2.getPath());
        myTimeout = NATIVE_PROCESS_DELAY;
      } finally {
        unwatch(rootRequest);
      }

      myAccept = true;
      FileUtil.writeToFile(file1, "");
      FileUtil.writeToFile(file2, "");
      assertEvent(VFileContentChangeEvent.class, file2.getPath());
    } finally {
      unwatch(request);
    }

    myTimeout = 10 * INTER_RESPONSE_DELAY;
    myAccept = true;
    FileUtil.writeToFile(file1, "xyz");
    FileUtil.writeToFile(file2, "xyz");
    assertEvent(VFileEvent.class);
    myTimeout = NATIVE_PROCESS_DELAY;
  }
  public void testDirectoryFlat() throws Exception {
    File topDir = createTestDir("top");
    File watchedFile = createTestFile(topDir, "test.txt");
    File subDir = createTestDir(topDir, "sub");
    File unwatchedFile = createTestFile(subDir, "test.txt");
    refresh(topDir);

    LocalFileSystem.WatchRequest request = watch(topDir, false);
    try {
      myAccept = true;
      FileUtil.writeToFile(watchedFile, "new content");
      assertEvent(VFileContentChangeEvent.class, watchedFile.getAbsolutePath());

      myTimeout = 10 * INTER_RESPONSE_DELAY;
      myAccept = true;
      FileUtil.writeToFile(unwatchedFile, "new content");
      assertEvent(VFileEvent.class);
      myTimeout = NATIVE_PROCESS_DELAY;
    } finally {
      unwatch(request);
      delete(topDir);
    }
  }
Ejemplo n.º 21
0
  protected void initialize() throws ExecutionException {
    JavaParametersUtil.configureConfiguration(myJavaParameters, myConfiguration);
    myJavaParameters.setMainClass(JUnitConfiguration.JUNIT_START_CLASS);
    final Module module = myConfiguration.getConfigurationModule().getModule();
    if (myJavaParameters.getJdk() == null) {
      myJavaParameters.setJdk(
          module != null
              ? ModuleRootManager.getInstance(module).getSdk()
              : ProjectRootManager.getInstance(myProject).getProjectSdk());
    }

    myJavaParameters.getClassPath().add(JavaSdkUtil.getIdeaRtJarPath());
    myJavaParameters.getClassPath().add(PathUtil.getJarPathForClass(JUnitStarter.class));
    myJavaParameters
        .getProgramParametersList()
        .add(JUnitStarter.IDE_VERSION + JUnitStarter.VERSION);
    for (RunConfigurationExtension ext :
        Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
      ext.updateJavaParameters(myConfiguration, myJavaParameters, getRunnerSettings());
    }

    final Object[] listeners = Extensions.getExtensions(IDEAJUnitListener.EP_NAME);
    final StringBuilder buf = new StringBuilder();
    for (final Object listener : listeners) {
      boolean enabled = true;
      for (RunConfigurationExtension ext :
          Extensions.getExtensions(RunConfigurationExtension.EP_NAME)) {
        if (ext.isListenerDisabled(myConfiguration, listener, getRunnerSettings())) {
          enabled = false;
          break;
        }
      }
      if (enabled) {
        final Class classListener = listener.getClass();
        buf.append(classListener.getName()).append("\n");
        myJavaParameters.getClassPath().add(PathUtil.getJarPathForClass(classListener));
      }
    }
    if (buf.length() > 0) {
      try {
        myListenersFile = FileUtil.createTempFile("junit_listeners_", "");
        myListenersFile.deleteOnExit();
        myJavaParameters.getProgramParametersList().add("@@" + myListenersFile.getPath());
        FileUtil.writeToFile(myListenersFile, buf.toString().getBytes());
      } catch (IOException e) {
        LOG.error(e);
      }
    }
  }
  public void testExternalFileCreation() throws Exception {
    VirtualFile root = ProjectRootManager.getInstance(myProject).getContentRoots()[0];

    String newFilePath = root.getPresentableUrl() + File.separatorChar + "New.java";
    FileUtil.writeToFile(
        new File(newFilePath), "class A{ Object o;}".getBytes(CharsetToolkit.UTF8_CHARSET));
    VirtualFile file =
        LocalFileSystem.getInstance()
            .refreshAndFindFileByPath(newFilePath.replace(File.separatorChar, '/'));
    assertNotNull(file);
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiClass objectClass =
        myJavaFacade.findClass(
            CommonClassNames.JAVA_LANG_OBJECT, GlobalSearchScope.allScope(getProject()));
    assertNotNull(objectClass);
    checkUsages(objectClass, new String[] {"New.java"});
  }
  public void testLineBreaksInName() throws Exception {
    if (!SystemInfo.isUnix) {
      System.err.println("Ignored: Unix required");
      return;
    }

    File topDir = createTestDir("topDir");
    File testDir = createTestDir(topDir, "weird\ndir\nname");
    File testFile = createTestFile(testDir, "weird\nfile\nname");
    refresh(topDir);

    LocalFileSystem.WatchRequest request = watch(topDir);
    try {
      myAccept = true;
      FileUtil.writeToFile(testFile, "abc");
      assertEvent(VFileContentChangeEvent.class, testFile.getPath());
    } finally {
      unwatch(request);
    }
  }
  public void testDirectoryNonExisting() throws Exception {
    File topDir = createTestDir("top");
    File subDir = new File(topDir, "subDir");
    File file = new File(subDir, "file.txt");
    refresh(topDir);

    LocalFileSystem.WatchRequest request = watch(subDir);
    try {
      myAccept = true;
      assertTrue(subDir.toString(), subDir.mkdir());
      assertEvent(VFileCreateEvent.class, subDir.getAbsolutePath());
      refresh(subDir);

      myAccept = true;
      FileUtil.writeToFile(file, "new content");
      assertEvent(VFileCreateEvent.class, file.getAbsolutePath());
    } finally {
      unwatch(request);
      delete(topDir);
    }
  }
  private static File getOrCreateConfigFile(final String fileName, final String text)
      throws IOException {
    final File tempFolder = new File(FlexCommonUtils.getTempFlexConfigsDirPath());
    final File configFile = new File(tempFolder, fileName);

    /*
    try {
      if (configFile.isFile() && Arrays.equals(textBytes, FileUtil.loadFileBytes(configFile))) {
        return configFile;
      }
    }
    catch (IOException ignore) {
    }
    */

    // configFile.isDirectory() check is required because folder could be created by a parallel
    // process
    if (!FileUtil.createDirectory(tempFolder) && !tempFolder.isDirectory()) {
      throw new IOException("Failed to create folder " + configFile.getParent());
    }
    FileUtil.writeToFile(configFile, text);

    return configFile;
  }
Ejemplo n.º 26
0
 public static void writeToFile(@NotNull File file, @NotNull byte[] text, boolean append)
     throws IOException {
   writeToFile(file, text, 0, text.length, append);
 }
Ejemplo n.º 27
0
 public static void writeToFile(@NotNull File file, @NotNull byte[] text, int off, int len)
     throws IOException {
   writeToFile(file, text, off, len, false);
 }
Ejemplo n.º 28
0
 public static void writeToFile(@NotNull File file, @NotNull String text) throws IOException {
   writeToFile(file, text.getBytes("UTF-8"), false);
 }
Ejemplo n.º 29
0
 public static void writeToFile(@NotNull File file, @NotNull byte[] text) throws IOException {
   writeToFile(file, text, false);
 }
Ejemplo n.º 30
0
  private void doAsyncRefreshTest() throws Exception {
    final int N = 1000;
    final byte[] data = "xxx".getBytes();

    File temp =
        new WriteAction<File>() {
          @Override
          protected void run(Result<File> result) throws Throwable {
            File res = createTempDirectory();
            result.setResult(res);
          }
        }.execute().getResultObject();
    LocalFileSystem fs = LocalFileSystem.getInstance();
    VirtualFile vTemp = fs.findFileByIoFile(temp);
    assertNotNull(vTemp);
    VirtualFile[] children = new VirtualFile[N];

    long[] timestamp = new long[N];
    for (int i = 0; i < N; i++) {
      File file = new File(temp, i + ".txt");
      FileUtil.writeToFile(file, data);
      VirtualFile child = fs.refreshAndFindFileByIoFile(file);
      assertNotNull(child);
      children[i] = child;
      timestamp[i] = file.lastModified();
    }

    vTemp.refresh(false, true);

    for (int i = 0; i < N; i++) {
      File file = new File(temp, i + ".txt");
      assertEquals(timestamp[i], file.lastModified());
      VirtualFile child = fs.findFileByIoFile(file);
      assertNotNull(child);
      IoTestUtil.assertTimestampsEqual(timestamp[i], child.getTimeStamp());
    }

    for (int i = 0; i < N; i++) {
      File file = new File(temp, i + ".txt");
      FileUtil.writeToFile(file, "xxx".getBytes());
      assertTrue(file.setLastModified(timestamp[i] - 2000));
      long modified = file.lastModified();
      assertTrue("File:" + file.getPath() + "; time:" + modified, timestamp[i] != modified);
      timestamp[i] = modified;
      IoTestUtil.assertTimestampsNotEqual(children[i].getTimeStamp(), modified);
    }

    final CountDownLatch latch = new CountDownLatch(N);
    for (final VirtualFile child : children) {
      child.refresh(
          true,
          true,
          new Runnable() {
            @Override
            public void run() {
              latch.countDown();
            }
          });
    }
    while (true) {
      latch.await(100, TimeUnit.MILLISECONDS);
      UIUtil.pump();
      if (latch.getCount() == 0) break;
    }

    for (int i = 0; i < N; i++) {
      VirtualFile child = children[i];
      IoTestUtil.assertTimestampsEqual(timestamp[i], child.getTimeStamp());
    }
  }