Java Code Examples for de.waldheinz.fs.FsDirectoryEntry

Following code examples demonstrate how to use de.waldheinz.fs.FsDirectoryEntryfrom android. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use de.waldheinz.fs.FsDirectoryEntryand various code implementation of this class.

    private ByteBuffer getFileContent(FileSystem fs, String filename) throws IOException {
        FsDirectoryEntry entry = fs.getRoot().getEntry(filename);
        assertThat(entry).isNotNull();
        assertThat(entry.isFile()).isTrue();

        FsFile file = entry.getFile();
        assertThat(file).isNotNull();
        ByteBuffer buffer = ByteBuffer.allocate((int) file.getLength());
        file.read(0, buffer);
        return buffer;
    } 


    protected static List<FileInfo> readDirRecur(String parent, FsDirectory dir) throws IOException {
    	List <FileInfo>files = new ArrayList<FileInfo>();
        Iterator<FsDirectoryEntry> itr = dir.iterator();
    	while(itr.hasNext()) {
    		FsDirectoryEntry entry = itr.next();
    		if (entry.isDirectory()) {
    			if (entry.getName().equals(".") || entry.getName().equals(".."))
    				continue;
    			System.out.format("DIR: %s\n", entry.getName());
    			files.addAll(readDirRecur(parent + entry.getName() + "/", entry.getDirectory()));
    		} else {
    			files.add(new FileInfo(parent + entry.getName(), (int)entry.getFile().getLength()));
    			System.out.format("FILE: %s (%d)\n", entry.getName(), entry.getFile().getLength());
    		}
    	}
    	return files;
    } 

    private void iterateReadDirectory(VirtualDirectory parent, FsDirectory directory) throws IOException {
        Iterator<FsDirectoryEntry> iterator = directory.iterator();
        while(iterator.hasNext()) {
            FsDirectoryEntry entry = iterator.next();
            if(entry.isFile()) {
                try {
                    VirtualFile virtualFile = new VirtualFile(parent, entry.getName());
                    FsFile fsFile = entry.getFile();
                    ByteBuffer bb = ByteBuffer.allocate((int) fsFile.getLength());
                    fsFile.read(0, bb);
                    virtualFile.setContent(bb);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            } else {
                VirtualDirectory newParent = new VirtualDirectory(parent, entry.getName());
                iterateReadDirectory(newParent, entry.getDirectory());
            }
        }
    } 

    protected void postVisitDirectory(FsDirectoryEntry directory, File targetDirectory) throws IOException {
        if (delete) {
            List<String> toDeletes = fileToDelete.pop();
            for (String toDelete : toDeletes) {
                directory.getDirectory().remove(toDelete);
            }
        }
    } 

    protected void preVisitDirectory(FsDirectoryEntry directory, File targetDirectory) throws IOException {
        if (!targetDirectory.exists()) {
            if (!targetDirectory.mkdirs()) {
                Log.w("BackupTask", "Failed to create directory "+targetDirectory.getAbsolutePath());
            }
        }
        if (delete) {
            fileToDelete.push(new ArrayList<String>());
        }
    } 

    protected void visitFile(FsDirectoryEntry file, File targetDirectory) throws IOException {
        if (file == null || !file.isFile()) {
            throw new IllegalArgumentException("entry must be an existing file");
        }
        if (targetDirectory == null || !targetDirectory.exists() || !targetDirectory.isDirectory()
                || !targetDirectory.canWrite()) {
            throw new IllegalArgumentException(
                    "targetDirectory '" + targetDirectory + "' must be an existing writable directory");
        }
        String entryName = file.getName();
        String extensionUpper = FilenameUtils.getExtension(entryName).toUpperCase();
        String extensionLower = FilenameUtils.getExtension(entryName).toLowerCase();
        if (!extensions.isEmpty() && !extensions.contains(extensionUpper) && !extensions.contains(extensionLower)) {
            return;
        }
        if (copyFile(file.getFile(), new File(targetDirectory, entryName))) {
            if (delete) {
                fileToDelete.peek().add(entryName);
            }
        } else {
            failedToBackup.add(entryName);
        }
    } 

    protected Iterator<FsDirectoryEntry> dirIterator(final DevoFSDirectory parent) {
    	return new Iterator<FsDirectoryEntry>() {
    		private int idx = 0;
    		final DevoFSDirectory dir = parent;

    		public boolean hasNext() {
    			int nextIdx = idx;
    			while (nextIdx < elems.size() && elems.get(nextIdx).getParent() != dir) {
    				nextIdx++;
    			}
    			return nextIdx == elems.size() ? false: true;
    		}

    		public FsDirectoryEntry next() {
    			while (idx < elems.size() && elems.get(idx).getParent() != dir) {
    				idx++;
    			}
    			return elems.get(idx++);
    		}

    		
    		public void remove() {
    			throw new UnsupportedOperationException();
    		}
    	};
    } 

    		public FsDirectoryEntry next() {
    			while (idx < elems.size() && elems.get(idx).getParent() != dir) {
    				idx++;
    			}
    			return elems.get(idx++);
    		} 

    private FileSystem mountMockDevice() throws IOException {
        Log.d("MountTask", "creating fs hierarchy...");
        BlockDevice dev = new RamDisk(100 * 1024 * 1024);
        Log.d("MountTask", "BlockDevice created...");
        FileSystem fs = SuperFloppyFormatter.get(dev).format();
        Log.d("MountTask", "File system formatted...");
        FsDirectory rootDir = fs.getRoot();
        for (int i = 0; i < 10; i++) {
            addMockFile(rootDir, i, 1024 * 5);
        }
        FsDirectoryEntry dcim = rootDir.addDirectory("DCIM");
        FsDirectoryEntry subDir = dcim.getDirectory().addDirectory("100_PANO");
        for (int i = 0; i < 155; i++) {
            addMockFile(subDir.getDirectory(), i, 1024 * 100);
        }
        return fs;
    } 

    private void iterateReadDirectory(int indent, VirtualDirectory parent, FsDirectory directory) throws IOException {
        Iterator<FsDirectoryEntry> iterator = directory.iterator();
        while(iterator.hasNext()) {
            FsDirectoryEntry entry = iterator.next();
            if(entry.isFile()) {
                try {
                    VirtualFile virtualFile = new VirtualFile(parent, entry.getName());
                    FsFile fsFile = entry.getFile();
                    ByteBuffer bb = ByteBuffer.allocate((int) fsFile.getLength());
                    fsFile.read(0, bb);
                    virtualFile.setContent(bb);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            } else {
                if(!entry.getName().equals(".") && !entry.getName().equals("..")) {
                    VirtualDirectory newParent = new VirtualDirectory(parent, entry.getName());
                    iterateReadDirectory(indent + 4, newParent, entry.getDirectory());
                }
            }
        }
    } 

    public final void assertModificationDateWithPrecisionOfTen() throws IOException {
        FsDirectoryEntry entry = mock(FsDirectoryEntry.class);
        when(entry.getLastModified()).thenReturn(1000L);
        when(entry.getName()).thenReturn("entry name");

        assertThat(entry).hasBeenModifiedAt(new Date(1010L), 10);
    } 

    public final void failForDateOutOfPrecisionRange() throws IOException {
        FsDirectoryEntry entry = mock(FsDirectoryEntry.class);
        when(entry.getLastModified()).thenReturn(1000L);
        when(entry.getName()).thenReturn("entry name");

        assertThat(entry).hasBeenModifiedAt(new Date(1010L), 9);
    } 

    public final void assertModificationDateWithPrecisionOfZero() throws IOException {
        FsDirectoryEntry entry = mock(FsDirectoryEntry.class);
        when(entry.getLastModified()).thenReturn(1000L);
        when(entry.getName()).thenReturn("entry name");

        assertThat(entry).hasBeenModifiedAt(new Date(1000L), 0);
    } 

    public final void errorMessageContainsAllNeededInformation() throws IOException {
        try {
            FsDirectoryEntry entry = mock(FsDirectoryEntry.class);
            when(entry.getLastModified()).thenReturn(1000L);
            when(entry.getName()).thenReturn("entry name");

            assertThat(entry).hasBeenModifiedAt(new Date(100000L), 0);
        } catch (AssertionError error) {
            assertThat(error).hasMessageContaining("Entry <\"entry name");
            assertThat(error).hasMessageContaining("has not been modified at <\"" + DATE_FORMAT.format(new Date(100000L)));
            assertThat(error).hasMessageContaining("Last modification was on <\"" + DATE_FORMAT.format(new Date(1000L)));
        }
    } 

    public Iterable<Path> getEntries(Path path) {
        final List<Path> entries = new ArrayList<>();

        FatLfnDirectory directory;
        if (path.isRoot()) {
            directory = fs.getRoot();
        } else {
            directory = getDirectoryOrNull(getEntry(path));
        }

        if (directory != null) {
            for (FsDirectoryEntry entry : directory) {
                if (entry.getName().equals(".") || entry.getName().equals("..")) {
                    continue;
                }

                Path file = Path.createWithAppended(path, entry.getName());
                entries.add(file);
            }
        }

        return entries;
    } 

    private void listDirectories(FsDirectory dir, String ident) throws IOException {

        final Iterator<FsDirectoryEntry> i = dir.iterator();
        
        while (i.hasNext()) {
            final FsDirectoryEntry e = i.next();
            
            if (e.isDirectory()) {
                System.out.println(ident + "- " + e.getName());

                if (e.getName().equals(".") || e.getName().equals(".."))
                    continue;
                
                listDirectories(e.getDirectory(), ident + "   ");
            } else {
                checkFile(e, ident);
            }
        }
    } 

    private void checkFile(FsDirectoryEntry fe, String ident) throws IOException {
        System.out.print(ident + " + " + fe.getName());
        final FsFile f = fe.getFile();
        
        System.out.println(" [size=" + f.getLength() + "]");

        final ByteBuffer bb = ByteBuffer.allocate((int) f.getLength());
        f.read(0, bb);
    } 

    public void testFat32Write() throws Exception {
        System.out.println("fat32Write");

        this.dev = FileDisk.create(file, 128 * 1024 * 1024);
        SuperFloppyFormatter.get(dev).setFatType(FatType.FAT32).format();
        
        FatFileSystem fs = new FatFileSystem(dev, false);
        final FatLfnDirectory rootDir = (FatLfnDirectory) fs.getRoot();

        FatLfnDirectoryEntry entry = rootDir.addDirectory("Directory");
        
        for (int i = 0; i < 1; i++) {
            final FsDirectoryEntry e = entry.getDirectory().addFile(
                    "This is file number " + i);
            final FsFile fsFile = e.getFile();
            
            byte[] nullBytes = new byte[516];
            ByteBuffer buff = ByteBuffer.wrap(nullBytes);
            buff.rewind();
            fsFile.write(0, buff);
        }
        
        fs.flush();
        fs.close();
        runFsck();
    } 

    protected void walkFileTree(FsDirectory srcDir, File destDir) throws IOException {
        if (srcDir == null) {
            throw new IllegalArgumentException("srcDir can't be null");
        }
        if (destDir == null) {
            throw new IllegalArgumentException("destDir can't be null");
        }
        Iterator<FsDirectoryEntry> i = srcDir.iterator();
        while (i.hasNext()) {
            FsDirectoryEntry entry = i.next();
            if (entry.isFile()) {
                visitFile(entry, destDir);
            } else if (entry.isDirectory() && !".".equals(entry.getName()) && !"..".equals(entry.getName())) {
                File newSubDir = new File(destDir, entry.getName());
                preVisitDirectory(entry, newSubDir);
                walkFileTree(entry.getDirectory(), newSubDir);
                postVisitDirectory(entry, newSubDir);
            }
        }
    } 

    public final void addOrReplace(String name, ByteBuffer content) throws IOException {
        FsDirectoryEntry entry = fileSystem.getRoot().getEntry(name);
        if (entry == null) {
            entry = fileSystem.getRoot().addFile(name);
        }
        if (!entry.isFile()) {
            throw new IllegalStateException(format("Entry [%s] already exists and is a directory, not a file.", name));
        }
        entry.getFile().write(0, content);
    } 

    public final ByteBuffer getFileContent(String fileName) throws IOException {
        FsDirectoryEntry entry = fileSystem.getRoot().getEntry(fileName);
        if (entry == null) {
            throw new FileNotFoundException(fileName);
        }
        if (!entry.isFile()) {
            throw new IOException(String.format("Can only get getContent of files and [%s] is not a file.", fileName));
        }
        FsFile file = entry.getFile();
        ByteBuffer buffer = ByteBuffer.allocate((int) file.getLength());
        file.read(0, buffer);
        return buffer;
    } 

    private void iterateReadDirectory(int indent, VirtualDirectory parent, FsDirectory directory) throws IOException {
        Iterator<FsDirectoryEntry> iterator = directory.iterator();
        while(iterator.hasNext()) {
            FsDirectoryEntry entry = iterator.next();
            if(entry.isFile()) {
                try {
                    VirtualFile virtualFile = new VirtualFile(parent, entry.getName());
                    FsFile fsFile = entry.getFile();
                    ByteBuffer bb = ByteBuffer.allocate((int) fsFile.getLength());
                    fsFile.read(0, bb);
                    virtualFile.setContent(bb);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            } else {
                if(!entry.getName().equals(".") && !entry.getName().equals("..")) {
                    VirtualDirectory newParent = new VirtualDirectory(parent, entry.getName());
                    iterateReadDirectory(indent + 4, newParent, entry.getDirectory());
                }
            }
        }
    } 

    private void addAll(ContainerStream parentDir, FsDirectory fatDir) {
        boolean readError = false;
        for(FsDirectoryEntry e: fatDir) {
            if(e.isDirectory()) {
                try {
                    fatDir = e.getDirectory();
                }
                catch(IOException i) {
                    readError = true;
                }

                ContainerStream curr = new ContainerStream(parentDir, e.getName(), readError);
                addAll(curr, fatDir);
            }
            else {
                FsFile fatFile = null;

                try {
                    fatFile = e.getFile();
                }
                catch(IOException i) {
                    readError = true;
                }

                ByteBuffer buff = ByteBuffer.allocate((int)fatFile.getLength());

                try {
                    fatFile.read(0, buff);
                }
                catch(IOException i) {
                    readError = true;
                }

                new DocumentStream(parentDir, e.getName(), buff, readError);
            }
        }
    } 

    protected void visitFile(FsDirectoryEntry file, File targetDirectory) throws IOException {
        String entryName = file.getName();
        String extensionUpper = FilenameUtils.getExtension(entryName).toUpperCase();
        String extensionLower = FilenameUtils.getExtension(entryName).toLowerCase();
        if (!extensions.isEmpty() && !extensions.contains(extensionUpper) && !extensions.contains(extensionLower)) {
            return;
        }
        StringBuilder path = new StringBuilder("/");
        for (String pathFragment : pathFragments) {
            path.append(pathFragment).append("/");
        }
        path.append(file.getName());
        files.add(path.toString());
    } 

    protected void preVisitDirectory(FsDirectoryEntry directory, File targetDirectory) throws IOException {
        if (targetDirectory.getPath().equals(targetPath)) {
            navigateTo = directory.getDirectory();
        }
    } 

    public void createUsb() throws IOException {
        Date startTime = new Date();
        ByteBuffer sysLinuxCfg = ByteBuffer.wrap("sysLinuxCfg".getBytes());
        Set<Path> preseeds = Collections.singleton(HELLO_WORLD_TXT);

        try (InputStream srcBootImg = Files.newInputStream(VFAT_IMG_GZ);
             GZIPOutputStream newBootImg = new GZIPOutputStream(Files.newOutputStream(NEW_IMAGE))) {
            new UsbCreator().create(srcBootImg, newBootImg, sysLinuxCfg, preseeds);
        }

        assertThat(NEW_IMAGE).exists();

        FileSystem fileSystem = FileSystemFactory.create(RamDisk.readGzipped(NEW_IMAGE.toFile()), true);

        FsDirectoryEntry newInitRdGzEntry = fileSystem.getRoot().getEntry(INITRD_GZ);
        assertThat(newInitRdGzEntry).hasBeenModifiedAt(startTime, 2000);
        assertThat(fileSystem.getRoot().getEntry(SYSLINUX_CFG)).hasBeenModifiedAt(startTime, 2000);

        CpioArchiveInputStream initRdCpio = getCpioArchiveInputStream(newInitRdGzEntry);
        assertThat(initRdCpio).hasSingleEntry(HELLO_WORLD_TXT.getFileName().toString());
    } 

    private CpioArchiveInputStream getCpioArchiveInputStream(FsDirectoryEntry newInitRdGzEntry) throws IOException {
        FsFile initrdGzFile = newInitRdGzEntry.getFile();
        ByteBuffer initRdBuffer = ByteBuffer.allocate((int) initrdGzFile.getLength());
        initrdGzFile.read(0, initRdBuffer);
        initRdBuffer.rewind();
        return new CpioArchiveInputStream(new GZIPInputStream(new ByteBufferDataInputStream(initRdBuffer)));
    } 

    public void testAcceptedFileNames() throws Exception {
        System.out.println("acceptedFileNames");
        
        root.addFile("jdom-1.0.jar");
        final FsDirectoryEntry dir = root.addDirectory("testDir.test");
        dir.getDirectory().addFile("this.should.work.toooo");
        fs.flush();
    } 

    private void processEntry(FsDirectoryEntry entry, URI uri, String newPath) throws CommandExecutionException, IOException {
        String name = entry.getName();
        if (!entry.isDirectory()) {
            final RequestMetaData metaData = new RequestMetaData(entry.getFile().getLength(), 2L, name);
            final RequestIdentifier identifier = new RequestIdentifier(uri);
            FatFileIdentificationRequest req = new FatFileIdentificationRequest(metaData, identifier, getTmpDir());

            ByteBuffer buffer = ByteBuffer.allocate((int) entry.getFile().getLength());
            entry.getFile().read(0, buffer);
            buffer.flip();
            expandContainer(req, new ByteArrayInputStream(buffer.array(), buffer.position(), buffer.limit()), newPath);
        } else {
            log.trace("processing directory : " + entry.getName());
        }
    } 

    public void identify(final URI uri, final IdentificationRequest request) throws CommandExecutionException {

        final String newPath = makeContainerURI("fat", request.getFileName());
        setSlash1("");

        if (request.getClass().isAssignableFrom(FileSystemIdentificationRequest.class)) {

            FileSystemIdentificationRequest req = (FileSystemIdentificationRequest) request;

            try {
                FileDisk fileDisk = new FileDisk(req.getFile().toFile(), true);
                FileSystem fatSystem = FileSystemFactory.create(fileDisk, true);
                FsDirectory root = fatSystem.getRoot();
                    for (FsDirectoryEntry entry : root) {
                         processEntry(entry, uri, newPath);
                    }

            } catch (IOException e) {
                throw new CommandExecutionException("IO error in FatFileSystem", e);
            }
        } else {
            log.info("Identification request for Fat image ignored due to limited support.");
        }

    } 

    public BridgeUSBFile(FsDirectoryEntry entry) throws IOException {
        this.entry = entry;

        if(entry.isDirectory()) {
            directory = entry.getDirectory();
        } else {
            file = entry.getFile();
        }
    } 

    }

    protected void dumpDirectory(FsDirectory dir, int tabStop, File curDirectory, boolean hasOutputDirectory)
            throws
            IOException {
        Iterator<FsDirectoryEntry> i = dir.iterator();
        while (i.hasNext()) {
            final FsDirectoryEntry e = i.next();
            if (e.isDirectory()) {
                for (int idx = 0; idx < tabStop; idx++) {
                    System.out.print(' ');
                }
                if (e.getName().equals(".") || e.getName().equals("..")) {
                    continue;
                }
                for (int idx = 0; idx < tabStop; idx++) {
                    System.out.print("  ");
                }
                System.out.println("[" + e + "]");
                dumpDirectory(e.getDirectory(), tabStop + 1, new File(curDirectory, e.getName()),
                        hasOutputDirectory);
            } else {
                for (int idx = 0; idx < tabStop; idx++) {
                    System.out.print("  ");
                }

                System.out.println(e);

                if (!hasOutputDirectory) {
                    continue;
                }

                if (!curDirectory.exists()) {
                    if (false == curDirectory.mkdirs()) {
                        throw new IOException("Unable to create directory: " + curDirectory);
                    }
                }

                File curFile = new File(curDirectory, e.getName());
                if (curFile.exists()) {
                    throw new IOException("File exists: " + curFile);
                } else {
                    FsFile f = e.getFile();
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(curFile);
                        FileChannel outputChannel = fos.getChannel();
                        int capacity = tempBuf.capacity();
                        long length = f.getLength();
                        for (long pos = 0; pos < length; pos++) {
                            int readLength = (int) (length - pos > capacity ? capacity : length - pos);
                            tempBuf.rewind();
                            tempBuf.limit(readLength);
                            f.read(pos, tempBuf);
                            tempBuf.rewind();
                            while (tempBuf.remaining() > 0) {
                                outputChannel.write(tempBuf);
                            }
                            pos += readLength;
                        }
                    } finally {
                        if (null != fos) fos.close();
                    }
                }
            }
        }
    } 

    private void test1_recur(String indent, FsDirectory dir) {
        Iterator<FsDirectoryEntry> itr = dir.iterator();
        while (itr.hasNext()) {
            try {
                FsDirectoryEntry entry = itr.next();
                if (entry.isDirectory()) {
                    System.out.format("%sDIR: %s\n", indent, entry.getName());
                    test1_recur(indent + "    ", entry.getDirectory());
                } else {
                    System.out.format("%sFILE: %s (%d)\n", indent, entry.getName(), entry.getFile().getLength());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } 

	public static FsDirectory getFileDirectory(FileSystem fs, FileInfo file, boolean create) {
		String[]filepath = file.name().toUpperCase().split("/");
		
		String[]filedir;
		if (filepath.length > 1) {
			filedir = Arrays.copyOfRange(filepath, 0, filepath.length-1);
		} else {
			filedir = new String[0];
		}
		FsDirectory fsdir;
    	FsDirectoryEntry fs_entry;
		try {
			fsdir = fs.getRoot();
		} catch (Exception e) {
			System.err.println("Couldn't get root dir: " + e.getMessage());
			return null;
		}
        for (String subdir : filedir) {
            if (subdir.equals("")) {
               continue;
            }
            try {
            	fs_entry = fsdir.getEntry(subdir);
            	if (fs_entry == null) {
            		if (! create) {
            			return null;
            		}
            		fs_entry = fsdir.addDirectory(subdir);
            		if (fs_entry == null) {
            			System.err.println("Couldn't create directory '" + subdir);
            			return null;
            		}
            	}
            	fsdir = fs_entry.getDirectory();
            } catch (Exception e) {
            	e.printStackTrace();
            	return null;
            }
        }
		return fsdir;
	} 

	public static void copyFile(FileSystem fs, FileInfo file) {
    	FsDirectoryEntry fs_entry;
		String filename = file.baseName().toUpperCase();
		FsDirectory fsdir = getFileDirectory(fs, file, true);
		if (fsdir == null) {
			return;
		}
		try {
			fs_entry = fsdir.getEntry(filename);
			if (fs_entry == null) {
				if (file.deleted()) {
					return;
				}
				fs_entry = fsdir.addFile(filename);
				if (fs_entry == null) {
					System.err.println("Failed to create file '" + file.name());
					return;
				}
			}
			if (! fs_entry.isFile()) {
				System.err.println(file.name() + " exists but is not a file");
				return;
			}
			if (file.deleted()) {
				fsdir.remove(fs_entry.getName());
				return;
			}
			FsFile fs_file = fs_entry.getFile();
			ByteBuffer byteBuffer = ByteBuffer.allocate(file.data().length);
			byteBuffer.put(file.data());
			byteBuffer.flip();
			fs_file.write(0, byteBuffer);
			fs_entry.setLastModified(file.time());
		} catch (Exception e) {
			e.printStackTrace();
        	return;
		}
	} 

Advertisement
Javadoc
Represents one entry in a FsDirectory. @author Ewout Prangsma <epr at jnode.org> @author Matth

ias Treydte <waldheinz at gmail.com>

Read More
Advertisement