@SuppressWarnings("all") private Model findRelated(DMSFile file) { if (file.getRelatedId() == null || file.getRelatedModel() == null) { return null; } Class<? extends Model> klass = null; try { klass = (Class) ClassUtils.findClass(file.getRelatedModel()); } catch (Exception e) { return null; } final Model entity = JpaRepository.of(klass).find(file.getRelatedId()); return EntityHelper.getEntity(entity); }
@Override public DMSFile save(DMSFile entity) { final DMSFile parent = entity.getParent(); final Model related = findRelated(entity); final boolean isAttachment = related != null && entity.getMetaFile() != null; // if new attachment, save attachment reference if (isAttachment) { // remove old attachment if file is moved MetaAttachment attachmentOld = attachments .all() .filter( "self.metaFile.id = ? AND self.objectId != ? AND self.objectName != ?", entity.getMetaFile().getId(), related.getId(), related.getClass().getName()) .fetchOne(); if (attachmentOld != null) { System.err.println("OLD: " + attachmentOld); attachments.remove(attachmentOld); } MetaAttachment attachment = attachments .all() .filter( "self.metaFile.id = ? AND self.objectId = ? AND self.objectName = ?", entity.getMetaFile().getId(), related.getId(), related.getClass().getName()) .fetchOne(); if (attachment == null) { attachment = metaFiles.attach(entity.getMetaFile(), related); attachments.save(attachment); } } // if not an attachment or has parent, do nothing if (parent != null || related == null) { return super.save(entity); } // create parent folders Mapper mapper = Mapper.of(related.getClass()); String homeName = null; try { homeName = mapper.getNameField().get(related).toString(); } catch (Exception e) { } if (homeName == null) { homeName = Strings.padStart("" + related.getId(), 5, '0'); } DMSFile dmsRoot = all() .filter( "(self.relatedId is null OR self.relatedId = 0) AND self.relatedModel = ? and self.isDirectory = true", entity.getRelatedModel()) .fetchOne(); final Inflector inflector = Inflector.getInstance(); if (dmsRoot == null) { dmsRoot = new DMSFile(); dmsRoot.setFileName( inflector.pluralize(inflector.humanize(related.getClass().getSimpleName()))); dmsRoot.setRelatedModel(entity.getRelatedModel()); dmsRoot.setIsDirectory(true); dmsRoot = super.save(dmsRoot); // should get id before it's child } DMSFile dmsHome = new DMSFile(); dmsHome.setFileName(homeName); dmsHome.setRelatedId(entity.getRelatedId()); dmsHome.setRelatedModel(entity.getRelatedModel()); dmsHome.setParent(dmsRoot); dmsHome.setIsDirectory(true); dmsHome = super.save(dmsHome); // should get id before it's child entity.setParent(dmsHome); return super.save(entity); }