001/* 002 * Copyright (C) 2012 eXo Platform SAS. 003 * 004 * This is free software; you can redistribute it and/or modify it 005 * under the terms of the GNU Lesser General Public License as 006 * published by the Free Software Foundation; either version 2.1 of 007 * the License, or (at your option) any later version. 008 * 009 * This software is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * You should have received a copy of the GNU Lesser General Public 015 * License along with this software; if not, write to the Free 016 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 017 * 02110-1301 USA, or see the FSF site: http://www.fsf.org. 018 */ 019 020package org.crsh.vfs; 021 022import org.crsh.util.Utils; 023import org.crsh.vfs.spi.FSDriver; 024 025import java.io.IOException; 026import java.io.InputStream; 027import java.util.ArrayList; 028import java.util.Iterator; 029import java.util.LinkedList; 030import java.util.List; 031 032class Handle<H> { 033 034 /** . */ 035 private final FSDriver<H> driver; 036 037 /** . */ 038 final Key key; 039 040 /** . */ 041 final H handle; 042 043 Handle(FSDriver<H> driver, H handle) throws IOException { 044 String name = driver.name(handle); 045 boolean dir = driver.isDir(handle); 046 047 // 048 this.driver = driver; 049 this.handle = handle; 050 this.key = new Key(name, dir); 051 } 052 053 Iterable<Handle<H>> children() throws IOException { 054 List<Handle<H>> children = new ArrayList<Handle<H>>(); 055 for (H h : driver.children(handle)) { 056 children.add(new Handle<H>(driver, h)); 057 } 058 return children; 059 } 060 061 Resource getResource() throws IOException { 062 InputStream in = open(); 063 byte[] bytes = Utils.readAsBytes(in); 064 long lastModified = getLastModified(); 065 return new Resource(key.name, bytes, lastModified); 066 } 067 068 Iterator<Resource> getResources() throws IOException { 069 Iterator<InputStream> i = driver.open(handle); 070 if (i.hasNext()) { 071 LinkedList<Resource> resources = new LinkedList<Resource>(); 072 while (i.hasNext()) { 073 InputStream in = i.next(); 074 byte[] bytes = Utils.readAsBytes(in); 075 long lastModified = getLastModified(); 076 resources.add(new Resource(key.name, bytes, lastModified)); 077 } 078 return resources.iterator(); 079 } else { 080 return Utils.iterator(); 081 } 082 } 083 084 private InputStream open() throws IOException { 085 Iterator<InputStream> i = driver.open(handle); 086 if (i.hasNext()) { 087 return i.next(); 088 } else { 089 throw new IOException("No stream"); 090 } 091 } 092 093 long getLastModified() throws IOException { 094 return driver.getLastModified(handle); 095 } 096}