Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/demo/zipfs/ZipFSTester.java
38833 views
/*1* Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.*;24import java.nio.*;25import java.nio.channels.*;26import java.nio.file.*;27import java.nio.file.spi.*;28import java.nio.file.attribute.*;29import java.net.*;30import java.util.*;31import java.util.concurrent.TimeUnit;32import java.util.zip.*;3334import static java.nio.file.StandardOpenOption.*;35import static java.nio.file.StandardCopyOption.*;3637/*38* Tests various zipfs operations.39*/4041public class ZipFSTester {4243public static void main(String[] args) throws Throwable {4445try (FileSystem fs = newZipFileSystem(Paths.get(args[0]),46new HashMap<String, Object>()))47{48test0(fs);49test1(fs);50test2(fs); // more tests51testTime(Paths.get(args[0]));52test8069211();53}54}5556static void test0(FileSystem fs)57throws Exception58{59List<String> list = new LinkedList<>();60try (ZipFile zf = new ZipFile(fs.toString())) {61Enumeration<? extends ZipEntry> zes = zf.entries();62while (zes.hasMoreElements()) {63list.add(zes.nextElement().getName());64}65for (String pname : list) {66Path path = fs.getPath(pname);67if (!Files.exists(path))68throw new RuntimeException("path existence check failed!");69while ((path = path.getParent()) != null) {70if (!Files.exists(path))71throw new RuntimeException("parent existence check failed!");72}73}74}75}7677static void test1(FileSystem fs0)78throws Exception79{80Random rdm = new Random();81// clone a fs and test on it82Path tmpfsPath = getTempPath();83Map<String, Object> env = new HashMap<String, Object>();84env.put("create", "true");85try (FileSystem copy = newZipFileSystem(tmpfsPath, env)) {86z2zcopy(fs0, copy, "/", 0);87}8889try (FileSystem fs = newZipFileSystem(tmpfsPath, new HashMap<String, Object>())) {9091FileSystemProvider provider = fs.provider();92// newFileSystem(path...) should not throw exception93try (FileSystem fsPath = provider.newFileSystem(tmpfsPath, new HashMap<String, Object>())){}94try (FileSystem fsUri = provider.newFileSystem(95new URI("jar", tmpfsPath.toUri().toString(), null),96new HashMap<String, Object>()))97{98throw new RuntimeException("newFileSystem(uri...) does not throw exception");99} catch (FileSystemAlreadyExistsException fsaee) {}100101// prepare a src102Path src = getTempPath();103String tmpName = src.toString();104OutputStream os = Files.newOutputStream(src);105byte[] bits = new byte[12345];106rdm.nextBytes(bits);107os.write(bits);108os.close();109110try {111provider.newFileSystem(new File(System.getProperty("test.src", ".")).toPath(),112new HashMap<String, Object>());113throw new RuntimeException("newFileSystem() opens a directory as zipfs");114} catch (UnsupportedOperationException uoe) {}115116try {117provider.newFileSystem(src, new HashMap<String, Object>());118throw new RuntimeException("newFileSystem() opens a non-zip file as zipfs");119} catch (UnsupportedOperationException uoe) {}120121122// copyin123Path dst = getPathWithParents(fs, tmpName);124Files.copy(src, dst);125checkEqual(src, dst);126127// copy128Path dst2 = getPathWithParents(fs, "/xyz" + rdm.nextInt(100) +129"/efg" + rdm.nextInt(100) + "/foo.class");130Files.copy(dst, dst2);131//dst.moveTo(dst2);132checkEqual(src, dst2);133134// delete135Files.delete(dst);136if (Files.exists(dst))137throw new RuntimeException("Failed!");138139// moveout140Path dst3 = Paths.get(tmpName + "_Tmp");141Files.move(dst2, dst3);142checkEqual(src, dst3);143if (Files.exists(dst2))144throw new RuntimeException("Failed!");145146// copyback + move147Files.copy(dst3, dst);148Path dst4 = getPathWithParents(fs, tmpName + "_Tmp0");149Files.move(dst, dst4);150checkEqual(src, dst4);151152// delete153Files.delete(dst4);154if (Files.exists(dst4))155throw new RuntimeException("Failed!");156Files.delete(dst3);157if (Files.exists(dst3))158throw new RuntimeException("Failed!");159160// move (existing entry)161Path dst5 = fs.getPath("META-INF/MANIFEST.MF");162if (Files.exists(dst5)) {163Path dst6 = fs.getPath("META-INF/MANIFEST.MF_TMP");164Files.move(dst5, dst6);165walk(fs.getPath("/"));166}167168// newInputStream on dir169Path parent = dst2.getParent();170try {171Files.newInputStream(parent);172throw new RuntimeException("Failed");173} catch (FileSystemException e) {174e.printStackTrace(); // expected fse175}176177// rmdirs178try {179rmdirs(parent);180} catch (IOException x) {181x.printStackTrace();182}183184// newFileChannel() copy in, out and verify via fch185fchCopy(src, dst); // in186checkEqual(src, dst);187Path tmp = Paths.get(tmpName + "_Tmp");188fchCopy(dst, tmp); // out189checkEqual(src, tmp);190Files.delete(tmp);191192// test channels193channel(fs, dst);194Files.delete(dst);195Files.delete(src);196} finally {197if (Files.exists(tmpfsPath))198Files.delete(tmpfsPath);199}200}201202static void test2(FileSystem fs) throws Exception {203204Path fs1Path = getTempPath();205Path fs2Path = getTempPath();206Path fs3Path = getTempPath();207208// create a new filesystem, copy everything from fs209Map<String, Object> env = new HashMap<String, Object>();210env.put("create", "true");211FileSystem fs0 = newZipFileSystem(fs1Path, env);212213final FileSystem fs2 = newZipFileSystem(fs2Path, env);214final FileSystem fs3 = newZipFileSystem(fs3Path, env);215216System.out.println("copy src: fs -> fs0...");217z2zcopy(fs, fs0, "/", 0); // copy fs -> fs1218fs0.close(); // dump to file219220System.out.println("open fs0 as fs1");221env = new HashMap<String, Object>();222final FileSystem fs1 = newZipFileSystem(fs1Path, env);223224System.out.println("listing...");225final ArrayList<String> files = new ArrayList<>();226final ArrayList<String> dirs = new ArrayList<>();227list(fs1.getPath("/"), files, dirs);228229Thread t0 = new Thread(new Runnable() {230public void run() {231List<String> list = new ArrayList<>(dirs);232Collections.shuffle(list);233for (String path : list) {234try {235z2zcopy(fs1, fs2, path, 0);236} catch (Exception x) {237x.printStackTrace();238}239}240}241242});243244Thread t1 = new Thread(new Runnable() {245public void run() {246List<String> list = new ArrayList<>(dirs);247Collections.shuffle(list);248for (String path : list) {249try {250z2zcopy(fs1, fs2, path, 1);251} catch (Exception x) {252x.printStackTrace();253}254}255}256257});258259Thread t2 = new Thread(new Runnable() {260public void run() {261List<String> list = new ArrayList<>(dirs);262Collections.shuffle(list);263for (String path : list) {264try {265z2zcopy(fs1, fs2, path, 2);266} catch (Exception x) {267x.printStackTrace();268}269}270}271272});273274Thread t3 = new Thread(new Runnable() {275public void run() {276List<String> list = new ArrayList<>(files);277Collections.shuffle(list);278while (!list.isEmpty()) {279Iterator<String> itr = list.iterator();280while (itr.hasNext()) {281String path = itr.next();282try {283if (Files.exists(fs2.getPath(path))) {284z2zmove(fs2, fs3, path);285itr.remove();286}287} catch (FileAlreadyExistsException x){288itr.remove();289} catch (Exception x) {290x.printStackTrace();291}292}293}294}295296});297298System.out.println("copying/removing...");299t0.start(); t1.start(); t2.start(); t3.start();300t0.join(); t1.join(); t2.join(); t3.join();301302System.out.println("closing: fs1, fs2");303fs1.close();304fs2.close();305306int failed = 0;307System.out.println("checkEqual: fs vs fs3");308for (String path : files) {309try {310checkEqual(fs.getPath(path), fs3.getPath(path));311} catch (IOException x) {312//x.printStackTrace();313failed++;314}315}316System.out.println("closing: fs3");317fs3.close();318319System.out.println("opening: fs3 as fs4");320FileSystem fs4 = newZipFileSystem(fs3Path, env);321322323ArrayList<String> files2 = new ArrayList<>();324ArrayList<String> dirs2 = new ArrayList<>();325list(fs4.getPath("/"), files2, dirs2);326327System.out.println("checkEqual: fs vs fs4");328for (String path : files2) {329checkEqual(fs.getPath(path), fs4.getPath(path));330}331System.out.println("walking: fs4");332walk(fs4.getPath("/"));333System.out.println("closing: fs4");334fs4.close();335System.out.printf("failed=%d%n", failed);336337Files.delete(fs1Path);338Files.delete(fs2Path);339Files.delete(fs3Path);340}341342// test file stamp343static void testTime(Path src) throws Exception {344BasicFileAttributes attrs = Files345.getFileAttributeView(src, BasicFileAttributeView.class)346.readAttributes();347// create a new filesystem, copy this file into it348Map<String, Object> env = new HashMap<String, Object>();349env.put("create", "true");350Path fsPath = getTempPath();351FileSystem fs = newZipFileSystem(fsPath, env);352353System.out.println("test copy with timestamps...");354// copyin355Path dst = getPathWithParents(fs, "me");356Files.copy(src, dst, COPY_ATTRIBUTES);357checkEqual(src, dst);358System.out.println("mtime: " + attrs.lastModifiedTime());359System.out.println("ctime: " + attrs.creationTime());360System.out.println("atime: " + attrs.lastAccessTime());361System.out.println(" ==============>");362BasicFileAttributes dstAttrs = Files363.getFileAttributeView(dst, BasicFileAttributeView.class)364.readAttributes();365System.out.println("mtime: " + dstAttrs.lastModifiedTime());366System.out.println("ctime: " + dstAttrs.creationTime());367System.out.println("atime: " + dstAttrs.lastAccessTime());368369// 1-second granularity370if (attrs.lastModifiedTime().to(TimeUnit.SECONDS) !=371dstAttrs.lastModifiedTime().to(TimeUnit.SECONDS) ||372attrs.lastAccessTime().to(TimeUnit.SECONDS) !=373dstAttrs.lastAccessTime().to(TimeUnit.SECONDS) ||374attrs.creationTime().to(TimeUnit.SECONDS) !=375dstAttrs.creationTime().to(TimeUnit.SECONDS)) {376throw new RuntimeException("Timestamp Copy Failed!");377}378Files.delete(fsPath);379}380381static void test8069211() throws Exception {382// create a new filesystem, copy this file into it383Map<String, Object> env = new HashMap<String, Object>();384env.put("create", "true");385Path fsPath = getTempPath();386try (FileSystem fs = newZipFileSystem(fsPath, env);) {387OutputStream out = Files.newOutputStream(fs.getPath("/foo"));388out.write("hello".getBytes());389out.close();390out.close();391}392try (FileSystem fs = newZipFileSystem(fsPath, new HashMap<String, Object>())) {393if (!Arrays.equals(Files.readAllBytes(fs.getPath("/foo")),394"hello".getBytes())) {395throw new RuntimeException("entry close() failed");396}397} catch (Exception x) {398throw new RuntimeException("entry close() failed", x);399} finally {400Files.delete(fsPath);401}402}403404private static FileSystem newZipFileSystem(Path path, Map<String, ?> env)405throws Exception406{407return FileSystems.newFileSystem(408new URI("jar", path.toUri().toString(), null), env, null);409}410411private static Path getTempPath() throws IOException412{413File tmp = File.createTempFile("testzipfs_", "zip");414tmp.delete(); // we need a clean path, no file415return tmp.toPath();416}417418private static void list(Path path, List<String> files, List<String> dirs )419throws IOException420{421if (Files.isDirectory(path)) {422try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {423for (Path child : ds)424list(child, files, dirs);425}426dirs.add(path.toString());427} else {428files.add(path.toString());429}430}431432private static void z2zcopy(FileSystem src, FileSystem dst, String path,433int method)434throws IOException435{436Path srcPath = src.getPath(path);437Path dstPath = dst.getPath(path);438439if (Files.isDirectory(srcPath)) {440if (!Files.exists(dstPath)) {441try {442mkdirs(dstPath);443} catch (FileAlreadyExistsException x) {}444}445try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {446for (Path child : ds) {447z2zcopy(src, dst,448path + (path.endsWith("/")?"":"/") + child.getFileName(),449method);450}451}452} else {453try {454if (Files.exists(dstPath))455return;456switch (method) {457case 0:458Files.copy(srcPath, dstPath);459break;460case 1:461chCopy(srcPath, dstPath);462break;463case 2:464//fchCopy(srcPath, dstPath);465streamCopy(srcPath, dstPath);466break;467}468} catch (FileAlreadyExistsException x) {}469}470}471472private static void z2zmove(FileSystem src, FileSystem dst, String path)473throws IOException474{475Path srcPath = src.getPath(path);476Path dstPath = dst.getPath(path);477478if (Files.isDirectory(srcPath)) {479if (!Files.exists(dstPath))480mkdirs(dstPath);481try (DirectoryStream<Path> ds = Files.newDirectoryStream(srcPath)) {482for (Path child : ds) {483z2zmove(src, dst,484path + (path.endsWith("/")?"":"/") + child.getFileName());485}486}487} else {488//System.out.println("moving..." + path);489Path parent = dstPath.getParent();490if (parent != null && Files.notExists(parent))491mkdirs(parent);492Files.move(srcPath, dstPath);493}494}495496private static void walk(Path path) throws IOException497{498Files.walkFileTree(499path,500new SimpleFileVisitor<Path>() {501private int indent = 0;502private void indent() {503int n = 0;504while (n++ < indent)505System.out.printf(" ");506}507508@Override509public FileVisitResult visitFile(Path file,510BasicFileAttributes attrs)511{512indent();513System.out.printf("%s%n", file.getFileName().toString());514return FileVisitResult.CONTINUE;515}516517@Override518public FileVisitResult preVisitDirectory(Path dir,519BasicFileAttributes attrs)520{521indent();522System.out.printf("[%s]%n", dir.toString());523indent += 2;524return FileVisitResult.CONTINUE;525}526527@Override528public FileVisitResult postVisitDirectory(Path dir,529IOException ioe)530throws IOException531{532indent -= 2;533return FileVisitResult.CONTINUE;534}535});536}537538private static void mkdirs(Path path) throws IOException {539if (Files.exists(path))540return;541path = path.toAbsolutePath();542Path parent = path.getParent();543if (parent != null) {544if (Files.notExists(parent))545mkdirs(parent);546}547Files.createDirectory(path);548}549550private static void rmdirs(Path path) throws IOException {551while (path != null && path.getNameCount() != 0) {552Files.delete(path);553path = path.getParent();554}555}556557// check the content of two paths are equal558private static void checkEqual(Path src, Path dst) throws IOException559{560//System.out.printf("checking <%s> vs <%s>...%n",561// src.toString(), dst.toString());562563//streams564byte[] bufSrc = new byte[8192];565byte[] bufDst = new byte[8192];566try (InputStream isSrc = Files.newInputStream(src);567InputStream isDst = Files.newInputStream(dst))568{569int nSrc = 0;570while ((nSrc = isSrc.read(bufSrc)) != -1) {571int nDst = 0;572while (nDst < nSrc) {573int n = isDst.read(bufDst, nDst, nSrc - nDst);574if (n == -1) {575System.out.printf("checking <%s> vs <%s>...%n",576src.toString(), dst.toString());577throw new RuntimeException("CHECK FAILED!");578}579nDst += n;580}581while (--nSrc >= 0) {582if (bufSrc[nSrc] != bufDst[nSrc]) {583System.out.printf("checking <%s> vs <%s>...%n",584src.toString(), dst.toString());585throw new RuntimeException("CHECK FAILED!");586}587nSrc--;588}589}590}591592// channels593try (SeekableByteChannel chSrc = Files.newByteChannel(src);594SeekableByteChannel chDst = Files.newByteChannel(dst))595{596if (chSrc.size() != chDst.size()) {597System.out.printf("src[%s].size=%d, dst[%s].size=%d%n",598chSrc.toString(), chSrc.size(),599chDst.toString(), chDst.size());600throw new RuntimeException("CHECK FAILED!");601}602ByteBuffer bbSrc = ByteBuffer.allocate(8192);603ByteBuffer bbDst = ByteBuffer.allocate(8192);604605int nSrc = 0;606while ((nSrc = chSrc.read(bbSrc)) != -1) {607int nDst = chDst.read(bbDst);608if (nSrc != nDst) {609System.out.printf("checking <%s> vs <%s>...%n",610src.toString(), dst.toString());611throw new RuntimeException("CHECK FAILED!");612}613while (--nSrc >= 0) {614if (bbSrc.get(nSrc) != bbDst.get(nSrc)) {615System.out.printf("checking <%s> vs <%s>...%n",616src.toString(), dst.toString());617throw new RuntimeException("CHECK FAILED!");618}619nSrc--;620}621bbSrc.flip();622bbDst.flip();623}624625// Check if source read position is at the end626if (chSrc.position() != chSrc.size()) {627System.out.printf("src[%s]: size=%d, position=%d%n",628chSrc.toString(), chSrc.size(), chSrc.position());629throw new RuntimeException("CHECK FAILED!");630}631632// Check if destination read position is at the end633if (chDst.position() != chDst.size()) {634System.out.printf("dst[%s]: size=%d, position=%d%n",635chDst.toString(), chDst.size(), chDst.position());636throw new RuntimeException("CHECK FAILED!");637}638} catch (IOException x) {639x.printStackTrace();640}641}642643private static void fchCopy(Path src, Path dst) throws IOException644{645Set<OpenOption> read = new HashSet<>();646read.add(READ);647Set<OpenOption> openwrite = new HashSet<>();648openwrite.add(CREATE_NEW);649openwrite.add(WRITE);650651try (FileChannel srcFc = src.getFileSystem()652.provider()653.newFileChannel(src, read);654FileChannel dstFc = dst.getFileSystem()655.provider()656.newFileChannel(dst, openwrite))657{658ByteBuffer bb = ByteBuffer.allocate(8192);659while (srcFc.read(bb) >= 0) {660bb.flip();661dstFc.write(bb);662bb.clear();663}664}665}666667private static void chCopy(Path src, Path dst) throws IOException668{669Set<OpenOption> read = new HashSet<>();670read.add(READ);671Set<OpenOption> openwrite = new HashSet<>();672openwrite.add(CREATE_NEW);673openwrite.add(WRITE);674675try (SeekableByteChannel srcCh = Files.newByteChannel(src, read);676SeekableByteChannel dstCh = Files.newByteChannel(dst, openwrite))677{678679ByteBuffer bb = ByteBuffer.allocate(8192);680while (srcCh.read(bb) >= 0) {681bb.flip();682dstCh.write(bb);683bb.clear();684}685686// Check if source read position is at the end687if (srcCh.position() != srcCh.size()) {688System.out.printf("src[%s]: size=%d, position=%d%n",689srcCh.toString(), srcCh.size(), srcCh.position());690throw new RuntimeException("CHECK FAILED!");691}692693// Check if destination write position is at the end694if (dstCh.position() != dstCh.size()) {695System.out.printf("dst[%s]: size=%d, position=%d%n",696dstCh.toString(), dstCh.size(), dstCh.position());697throw new RuntimeException("CHECK FAILED!");698}699}700}701702private static void streamCopy(Path src, Path dst) throws IOException703{704byte[] buf = new byte[8192];705try (InputStream isSrc = Files.newInputStream(src);706OutputStream osDst = Files.newOutputStream(dst))707{708int n = 0;709while ((n = isSrc.read(buf)) != -1) {710osDst.write(buf, 0, n);711}712}713}714715static void channel(FileSystem fs, Path path)716throws Exception717{718System.out.println("test ByteChannel...");719Set<OpenOption> read = new HashSet<>();720read.add(READ);721int n = 0;722ByteBuffer bb = null;723ByteBuffer bb2 = null;724int N = 120;725726try (SeekableByteChannel sbc = Files.newByteChannel(path)) {727System.out.printf(" sbc[0]: pos=%d, size=%d%n", sbc.position(), sbc.size());728if (sbc.position() != 0) {729throw new RuntimeException("CHECK FAILED!");730}731732bb = ByteBuffer.allocate((int)sbc.size());733n = sbc.read(bb);734System.out.printf(" sbc[1]: read=%d, pos=%d, size=%d%n",735n, sbc.position(), sbc.size());736if (sbc.position() != sbc.size()) {737throw new RuntimeException("CHECK FAILED!");738}739bb2 = ByteBuffer.allocate((int)sbc.size());740}741742// sbc.position(pos) is not supported in current version743// try the FileChannel744try (SeekableByteChannel sbc = fs.provider().newFileChannel(path, read)) {745sbc.position(N);746System.out.printf(" sbc[2]: pos=%d, size=%d%n",747sbc.position(), sbc.size());748if (sbc.position() != N) {749throw new RuntimeException("CHECK FAILED!");750}751bb2.limit(100);752n = sbc.read(bb2);753System.out.printf(" sbc[3]: read=%d, pos=%d, size=%d%n",754n, sbc.position(), sbc.size());755if (n < 0 || sbc.position() != (N + n)) {756throw new RuntimeException("CHECK FAILED!");757}758System.out.printf(" sbc[4]: bb[%d]=%d, bb1[0]=%d%n",759N, bb.get(N) & 0xff, bb2.get(0) & 0xff);760}761}762763// create parents if does not exist764static Path getPathWithParents(FileSystem fs, String name)765throws Exception766{767Path path = fs.getPath(name);768Path parent = path.getParent();769if (parent != null && Files.notExists(parent))770mkdirs(parent);771return path;772}773}774775776