001package systems.dmx.files; 002 003import systems.dmx.core.JSONEnabled; 004import systems.dmx.core.util.DMXUtils; 005import systems.dmx.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() 045 .put("items", DMXUtils.toJSONArray(fileItems)); 046 } catch (Exception e) { 047 throw new RuntimeException("Serialization failed", e); 048 } 049 } 050 051 // -------------------------------------------------------------------------------------------------- Nested Classes 052 053 public class FileItem implements JSONEnabled { 054 055 ItemKind kind; // FILE or DIRECTORY 056 String name; 057 String path; 058 long size; // for files only 059 String type; // for files only 060 061 FileItem(File file) { 062 this.kind = file.isDirectory() ? ItemKind.DIRECTORY : ItemKind.FILE; 063 this.name = file.getName(); 064 this.path = pathMapper.repoPath(file); 065 if (kind == ItemKind.FILE) { 066 this.size = file.length(); 067 this.type = JavaUtils.getFileType(name); 068 } 069 } 070 071 // --- 072 073 public ItemKind getItemKind() { 074 return kind; 075 } 076 077 public String getName() { 078 return name; 079 } 080 081 public String getPath() { 082 return path; 083 } 084 085 public long getSize() { 086 return size; 087 } 088 089 public String getMediaType() { 090 return type; 091 } 092 093 // --- 094 095 @Override 096 public JSONObject toJSON() { 097 try { 098 JSONObject item = new JSONObject(); 099 item.put("kind", kind.stringify()); 100 item.put("name", name); 101 item.put("path", path); 102 if (kind == ItemKind.FILE) { 103 item.put("size", size); 104 item.put("type", type); 105 } 106 return item; 107 } catch (Exception e) { 108 throw new RuntimeException("Serialization failed", e); 109 } 110 } 111 } 112}