001package org.nuxeo.template.context; 002 003import java.util.List; 004 005import org.apache.commons.logging.Log; 006import org.apache.commons.logging.LogFactory; 007import org.nuxeo.ecm.core.api.Blob; 008import org.nuxeo.ecm.core.api.DocumentModel; 009import org.nuxeo.ecm.core.api.blobholder.BlobHolder; 010import org.nuxeo.ecm.core.io.download.DownloadService; 011import org.nuxeo.runtime.api.Framework; 012 013/** 014 * Class helper used to expose Document as a {@link BlobHolder} in FreeMarker context 015 * 016 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a> 017 */ 018public class BlobHolderWrapper { 019 020 protected final BlobHolder bh; 021 022 protected final DocumentModel doc; 023 024 protected static final Log log = LogFactory.getLog(BlobHolderWrapper.class); 025 026 public BlobHolderWrapper(DocumentModel doc) { 027 bh = doc.getAdapter(BlobHolder.class); 028 this.doc = doc; 029 } 030 031 protected static String getContextPathProperty() { 032 return Framework.getProperty("org.nuxeo.ecm.contextPath", "/nuxeo"); 033 } 034 035 public Blob getBlob() { 036 if (bh == null) { 037 return null; 038 } 039 return bh.getBlob(); 040 } 041 042 public List<Blob> getBlobs() { 043 if (bh == null) { 044 return null; 045 } 046 return bh.getBlobs(); 047 } 048 049 public Blob getBlob(String name) { 050 051 List<Blob> blobs = getBlobs(); 052 if (blobs == null) { 053 return null; 054 } 055 for (Blob blob : blobs) { 056 if (name.equals(blob.getFilename())) { 057 return blob; 058 } 059 } 060 return null; 061 } 062 063 public Blob getBlob(int index) { 064 065 List<Blob> blobs = getBlobs(); 066 if (blobs == null) { 067 return null; 068 } 069 if (index >= blobs.size()) { 070 return null; 071 } 072 return blobs.get(index); 073 } 074 075 public String getBlobUrl(int index) { 076 077 List<Blob> blobs = getBlobs(); 078 if (blobs == null) { 079 return null; 080 } 081 if (index >= blobs.size()) { 082 return null; 083 } 084 085 DownloadService downloadService = Framework.getService(DownloadService.class); 086 String xpath = DownloadService.BLOBHOLDER_PREFIX + index; 087 String filename = blobs.get(index).getFilename(); 088 return getContextPathProperty() + "/" + downloadService.getDownloadUrl(doc, xpath, filename) + "?inline=true"; 089 } 090 091 public String getBlobUrl(String name) { 092 093 List<Blob> blobs = getBlobs(); 094 if (blobs == null) { 095 return null; 096 } 097 for (int index = 0; index < blobs.size(); index++) { 098 if (name.equals(blobs.get(index).getFilename())) { 099 return getBlobUrl(index); 100 } 101 } 102 return null; 103 } 104 105}