@@ -0,0 +1,2612 @@
+package ucar.nc2;%0A%0Aimport java.io.IOException;%0Aimport java.nio.file.Files;%0Aimport java.nio.file.Path;%0Aimport java.nio.file.Paths;%0Aimport java.nio.file.StandardCopyOption;%0Aimport org.junit.After;%0Aimport org.junit.Assert;%0Aimport org.junit.Before;%0Aimport org.junit.Test;%0Aimport ucar.unidata.util.test.TestDir;%0A%0A/**%0A * NetcdfFile.openInMemory(URI) and NetcdfFiles.openInMemory(URI) were leaking an open input stream.%0A * This tests for a leak by trying to delete a file that's been opened in memory using the URI signature.%0A *%0A * See https://github.com/Unidata/netcdf-java/issues/166%0A * Contributed by https://github.com/tayloj%0A */%0Apublic class TestOpenInMemoryResourceLeak %7B%0A%0A  // holds the tempFile Path object created before each test runs%0A  Path tempFile;%0A%0A  /*%0A   * Before each test, create a copy of an existing netcdf file from the built-in test datasets.%0A   * We will try to delete this temp file after opening it in memory.%0A   */%0A  @Before%0A  public void makeFileToBeDeleted() throws IOException %7B%0A    tempFile = Files.createTempFile(%22cdmTest_%22, %22.nc%22);%0A    Path ncfileToCopy = Paths.get(TestDir.cdmLocalTestDataDir + %22jan.nc%22);%0A    Files.copy(ncfileToCopy, tempFile, StandardCopyOption.REPLACE_EXISTING);%0A  %7D%0A%0A  /**%0A   * Test for leak using NetcdfFile.openInMemory(URI)%0A   */%0A  @Test%0A  public void inputStreamNetcdfFileLeak() throws IOException %7B%0A%0A    /*%0A     * Read the file into a NetcdfFile. try-with-resources ensures that the NetcdfFile's close()%0A     * method is called, so all resources with it are released.%0A     */%0A    try (NetcdfFile ncfile = NetcdfFile.openInMemory(tempFile.toUri())) %7B%0A      // prove it's opened%0A      Assert.assertTrue(ncfile.getFileTypeId().equalsIgnoreCase(%22netcdf%22));%0A    %7D%0A%0A    /*%0A     * Try to delete the temp file with Files.delete(). When this fails, it will due so with an exception like:%0A     *%0A     * java.nio.file.FileSystemException:%0A     * C:%5CUsers%5C%5Cusername%5CAppData%5CLocal%5CTemp%5Cfile8726442302596323190.nc: The process cannot access%0A     * the file because it is being used by another process.%0A     */%0A    Files.delete(tempFile);%0A  %7D%0A%0A  /**%0A   * Test for leak using NetcdfFiles.openInMemory(URI)%0A   */%0A  @Test%0A  public void inputStreamNetcdfFilesLeak() throws IOException %7B%0A%0A    try (NetcdfFile ncfile = NetcdfFiles.openInMemory(tempFile.toUri())) %7B%0A      // prove it's opened%0A      Assert.assertTrue(ncfile.getFileTypeId().equalsIgnoreCase(%22netcdf%22));%0A    %7D%0A%0A    Files.delete(tempFile);%0A  %7D%0A%0A  /**%0A   * Check that the temp file has been deleted after each test%0A   */%0A  @After%0A  public void reallyDeleted() %7B%0A    Assert.assertTrue(Files.notExists(tempFile));%0A  %7D%0A%0A%7D%0A

Create failing test for openInMemory resource leak