001package de.deepamehta.files; 002 003import de.deepamehta.core.JSONEnabled; 004import de.deepamehta.core.util.DeepaMehtaUtils; 005import de.deepamehta.core.util.JavaUtils; 006 007import org.codehaus.jettison.json.JSONObject; 008 009import java.io.File; 010import java.util.ArrayList; 011import java.util.List; 012 013 014 015public class DirectoryListing implements JSONEnabled { 016 017 // ---------------------------------------------------------------------------------------------- Instance Variables 018 019 private PathMapper pathMapper; 020 private FileItem dirInfo; 021 private List<FileItem> fileItems = new ArrayList<FileItem>(); 022 023 // ---------------------------------------------------------------------------------------------------- Constructors 024 025 public DirectoryListing(File directory, PathMapper pathMapper) { 026 this.pathMapper = pathMapper; 027 this.dirInfo = new FileItem(directory); 028 for (File file : directory.listFiles()) { 029 fileItems.add(new FileItem(file)); 030 } 031 } 032 033 // -------------------------------------------------------------------------------------------------- Public Methods 034 035 public List<FileItem> getFileItems() { 036 return fileItems; 037 } 038 039 // --- 040 041 @Override 042 public JSONObject toJSON() { 043 try { 044 return dirInfo.toJSON().put("items", DeepaMehtaUtils.toJSONArray(fileItems)); 045 } catch (Exception e) { 046 throw new RuntimeException("Serialization failed (" + this + ")", e); 047 } 048 } 049 050 // -------------------------------------------------------------------------------------------------- Nested Classes 051 052 public class FileItem implements JSONEnabled { 053 054 ItemKind kind; // FILE or DIRECTORY 055 String name; 056 String path; 057 long size; // for files only 058 String type; // for files only 059 060 FileItem(File file) { 061 this.kind = file.isDirectory() ? ItemKind.DIRECTORY : ItemKind.FILE; 062 this.name = file.getName(); 063 this.path = pathMapper.repoPath(file); 064 if (kind == ItemKind.FILE) { 065 this.size = file.length(); 066 this.type = JavaUtils.getFileType(name); 067 } 068 } 069 070 // --- 071 072 public ItemKind getItemKind() { 073 return kind; 074 } 075 076 public String getName() { 077 return name; 078 } 079 080 public String getPath() { 081 return path; 082 } 083 084 public long getSize() { 085 return size; 086 } 087 088 public String getMediaType() { 089 return type; 090 } 091 092 // --- 093 094 @Override 095 public JSONObject toJSON() { 096 try { 097 JSONObject item = new JSONObject(); 098 item.put("kind", kind.stringify()); 099 item.put("name", name); 100 item.put("path", path); 101 if (kind == ItemKind.FILE) { 102 item.put("size", size); 103 item.put("type", type); 104 } 105 return item; 106 } catch (Exception e) { 107 throw new RuntimeException("Serialization failed (" + this + ")", e); 108 } 109 } 110 } 111}