@Transactional public void createDocument(Document info, String folder, InputStream docData, User user) throws IOException { boolean created = false; File file = null; try { info.setId(null); documentDao.makePersistent(info); String uuid = UUID.randomUUID().toString(); file = new File(docsFolderPath + uuid); while (file.exists()) { uuid = UUID.randomUUID().toString(); file = new File(docsFolderPath + uuid); } created = file.createNewFile(); info.setUuid(uuid); Folder f = folderDao.getFolderByPath(folder, user); if (f == null) { if (folder != null && !folder.equals("")) { f = new Folder(); f.setPath(folder); folderDao.makePersistent(f); } } if (f == null) { throw new IOException("Internal Error"); } if (!f.canWrite(user)) throw new InsufficientPrivilagesException(); f.getDocs().add(info); Integer id = info.getId(); OutputStream out = new FileOutputStream(file); ByteUtils.write(docData, out); out.flush(); out.close(); File fi = new File(docsFolderPath + id); info.setSize((int) fi.length()); documentDao.makePersistent(info); } catch (Throwable t) { if (created && file != null) { file.delete(); } throw new RuntimeException(t); } }
@Transactional public Object[] getDocumentWithData(String path, User user) throws InsufficientPrivilagesException { Document doc = getDocumentByPath(path, user); File f = new File(docsFolderPath + doc.getUuid()); try { return new Object[] {doc, new FileInputStream(f)}; } catch (FileNotFoundException e) { return null; } }
@Transactional public void deleteDocument(String path, User user) throws InsufficientPrivilagesException { String folderPath = path.substring(0, path.lastIndexOf('/')); Folder f = getFolderByPath(folderPath, user); if (!f.getOwner().getUsername().equals(user.getUsername()) && !f.canWrite(user)) throw new InsufficientPrivilagesException( "User " + user + " does not have permission to delete documents from this folder"); Document doc = f.getDocumentByName(path.substring(path.lastIndexOf('/') + 1)); File docFile = new File(docsFolderPath + doc.getUuid()); f.removeDocument(doc); documentDao.makeTransient(doc); docFile.delete(); }
@Transactional public InputStream getDocumentData(Document doc) { File f = new File(docsFolderPath + doc.getUuid()); try { return new FileInputStream(f); } catch (FileNotFoundException e) { return null; } }