001 package org.crsh.vfs.spi.ram;
002
003 import org.crsh.vfs.Path;
004 import org.crsh.vfs.spi.AbstractFSDriver;
005
006 import java.io.IOException;
007 import java.lang.reflect.UndeclaredThrowableException;
008 import java.net.MalformedURLException;
009 import java.net.URL;
010 import java.util.ArrayList;
011 import java.util.Collections;
012 import java.util.HashMap;
013 import java.util.List;
014
015 /** @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a> */
016 public class RAMDriver extends AbstractFSDriver<Path> {
017
018 /** . */
019 private final Path root;
020
021 /** . */
022 final HashMap<Path, String> entries;
023
024 /** . */
025 URL baseURL;
026
027 public RAMDriver() {
028 try {
029 this.root = Path.get("/");
030 this.entries = new HashMap<Path, String>();
031 this.baseURL = new URL("ram", null, 0, "/", new RAMURLStreamHandler(this));
032 }
033 catch (MalformedURLException e) {
034 throw new UndeclaredThrowableException(e);
035 }
036 }
037
038 public void add(String path, String file) {
039 add(Path.get(path), file);
040 }
041
042 public void add(Path path, String file) {
043 entries.put(path, file);
044 }
045
046 public Path root() throws IOException {
047 return root;
048 }
049
050 public String name(Path handle) throws IOException {
051 return handle.getName();
052 }
053
054 public boolean isDir(Path handle) throws IOException {
055 return handle.isDir();
056 }
057
058 public Iterable<Path> children(Path handle) throws IOException {
059 List<Path> children = Collections.emptyList();
060 for (Path entry : entries.keySet()) {
061 if (entry.isChildOf(handle)) {
062 if (children.isEmpty()) {
063 children = new ArrayList<Path>();
064 }
065 children.add(entry);
066 }
067 }
068 return children;
069 }
070
071 public URL toURL(Path handle) throws IOException {
072 return new URL(baseURL, handle.getValue());
073 }
074 }