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