]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
38e35d17079c463610f90cc9b23099c346534674
[tmp/jakarta-migration.git] /
1 /**     \r
2  * NuxeoImageUtils.java\r
3  *\r
4  * {Purpose of This Class}\r
5  *\r
6  * {Other Notes Relating to This Class (Optional)}\r
7  *\r
8  * $LastChangedBy: $\r
9  * $LastChangedRevision: $\r
10  * $LastChangedDate: $\r
11  *\r
12  * This document is a part of the source code and related artifacts\r
13  * for CollectionSpace, an open source collections management system\r
14  * for museums and related institutions:\r
15  *\r
16  * http://www.collectionspace.org\r
17  * http://wiki.collectionspace.org\r
18  *\r
19  * Copyright © 2009 {Contributing Institution}\r
20  *\r
21  * Licensed under the Educational Community License (ECL), Version 2.0.\r
22  * You may not use this file except in compliance with this License.\r
23  *\r
24  * You may obtain a copy of the ECL 2.0 License at\r
25  * https://source.collectionspace.org/collection-space/LICENSE.txt\r
26  */\r
27 package org.collectionspace.services.common.imaging.nuxeo;\r
28 \r
29 import java.io.File;\r
30 import java.io.ByteArrayOutputStream;\r
31 import java.io.InputStream;\r
32 import java.io.FileInputStream;\r
33 import java.io.BufferedInputStream;\r
34 import java.io.IOException;\r
35 \r
36 import java.io.Serializable;\r
37 import java.util.ArrayList;\r
38 import java.util.HashMap;\r
39 import java.util.List;\r
40 import java.util.Map;\r
41 \r
42 import org.nuxeo.runtime.api.Framework;\r
43 import org.nuxeo.runtime.api.ServiceManager;\r
44 import org.nuxeo.runtime.api.ServiceDescriptor;\r
45 import org.nuxeo.runtime.services.streaming.RemoteInputStream;\r
46 import org.nuxeo.runtime.services.streaming.StreamSource;\r
47 import org.nuxeo.runtime.services.streaming.FileSource;\r
48 \r
49 \r
50 //import org.nuxeo.common.utils.FileUtils;\r
51 \r
52 import org.nuxeo.ecm.platform.picture.api.adapters.MultiviewPictureAdapter;\r
53 import org.nuxeo.ecm.platform.picture.api.adapters.MultiviewPictureAdapterFactory; \r
54 import org.nuxeo.ecm.platform.picture.api.PictureView;\r
55 \r
56 import org.nuxeo.ecm.platform.picture.api.adapters.PictureResourceAdapter;\r
57 import org.nuxeo.ecm.platform.mimetype.MimetypeDetectionException;\r
58 import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry;\r
59 import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolder;\r
60 import org.nuxeo.ecm.platform.picture.extension.ImagePlugin;\r
61 import org.nuxeo.ecm.platform.filemanager.api.FileManager;\r
62 import org.nuxeo.ecm.platform.filemanager.service.FileManagerService;\r
63 import org.nuxeo.ecm.platform.types.TypeManager;\r
64 import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolderFactory;\r
65 import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolder;\r
66 \r
67 import org.nuxeo.ecm.core.repository.RepositoryDescriptor;\r
68 import org.nuxeo.ecm.core.repository.RepositoryManager;\r
69 \r
70 import org.nuxeo.ecm.core.repository.RepositoryService;\r
71 import org.nuxeo.runtime.model.ComponentManager;\r
72 import org.nuxeo.runtime.model.ComponentInstance;\r
73 import org.nuxeo.runtime.model.impl.ComponentManagerImpl;\r
74 //import org.nuxeo.ecm.core.api.ejb.DocumentManagerBean;\r
75 //import org.nuxeo.ecm.core.storage.sql.RepositoryImpl;\r
76 //import org.nuxeo.ecm.core.storage.sql.Repository;\r
77 import org.nuxeo.ecm.core.storage.sql.BinaryManager;\r
78 import org.nuxeo.ecm.core.storage.sql.DefaultBinaryManager;\r
79 import org.nuxeo.ecm.core.storage.sql.coremodel.SQLRepository;\r
80 import org.nuxeo.ecm.core.storage.sql.coremodel.SQLBlob;\r
81 //import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor;\r
82 \r
83 //import org.nuxeo.ecm.core.api.DocumentResolver;\r
84 import org.nuxeo.ecm.core.api.IdRef;\r
85 import org.nuxeo.ecm.core.api.blobholder.BlobHolder;\r
86 import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder;\r
87 import org.nuxeo.ecm.core.api.impl.blob.FileBlob;\r
88 import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob;\r
89 import org.nuxeo.ecm.core.api.impl.blob.ByteArrayBlob;\r
90 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;\r
91 import org.nuxeo.ecm.core.api.repository.Repository;\r
92 import org.nuxeo.ecm.core.api.Blob;\r
93 import org.nuxeo.ecm.core.api.ClientException;\r
94 import org.nuxeo.ecm.core.api.DocumentModel;\r
95 import org.nuxeo.ecm.core.api.DocumentRef;\r
96 import org.nuxeo.ecm.core.api.blobholder.BlobHolder;\r
97 import org.nuxeo.ecm.core.api.blobholder.BlobHolderAdapterService;\r
98 import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;\r
99 import org.nuxeo.ecm.core.api.impl.blob.FileBlob;\r
100 \r
101 import org.nuxeo.ecm.core.model.Document;\r
102 import org.nuxeo.ecm.core.schema.SchemaManager;\r
103 import org.nuxeo.ecm.core.schema.types.Schema;\r
104 \r
105 import org.slf4j.Logger;\r
106 import org.slf4j.LoggerFactory;\r
107 //import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase;\r
108 \r
109 import org.collectionspace.services.common.ServiceMain;\r
110 import org.collectionspace.services.common.blob.BlobInput;\r
111 import org.collectionspace.services.common.context.ServiceContext;\r
112 import org.collectionspace.services.common.document.DocumentUtils;\r
113 import org.collectionspace.services.common.FileUtils;\r
114 import org.collectionspace.services.blob.BlobsCommon;\r
115 import org.collectionspace.services.blob.BlobsCommonList;\r
116 import org.collectionspace.services.blob.BlobsCommonList.BlobListItem;\r
117 import org.collectionspace.services.common.blob.BlobOutput;\r
118 \r
119 // TODO: Auto-generated Javadoc\r
120 /**\r
121  * The Class NuxeoImageUtils.\r
122  */\r
123 public class NuxeoImageUtils {\r
124         /** The Constant logger. */\r
125         private static final Logger logger = LoggerFactory.getLogger(NuxeoImageUtils.class);\r
126 \r
127         /*\r
128          * FIXME: REM - These constants should be coming from configuration and NOT hard coded.\r
129          */\r
130         public static final String DERIVATIVE_ORIGINAL = "Original";\r
131         public static final String DERIVATIVE_ORIGINAL_TAG = DERIVATIVE_ORIGINAL + "_";\r
132 \r
133         public static final String DERIVATIVE_ORIGINAL_JPEG = "OriginalJpeg";\r
134         public static final String DERIVATIVE_ORIGINAL_JPEG_TAG = DERIVATIVE_ORIGINAL_JPEG + "_";\r
135 \r
136         public static final String DERIVATIVE_MEDIUM = "Medium";\r
137         public static final String DERIVATIVE_MEDIUM_TAG = DERIVATIVE_MEDIUM + "_";\r
138 \r
139         public static final String DERIVATIVE_THUMBNAIL = "Thumbnail";\r
140         public static final String DERIVATIVE_THUMBNAIL_TAG = DERIVATIVE_THUMBNAIL + "_";\r
141 \r
142         public static final String DERIVATIVE_UNKNOWN = "_UNKNOWN_DERIVATIVE_NAME_";\r
143 \r
144         //      static DefaultBinaryManager binaryManager = new DefaultBinaryManager(); //can we get this from Nuxeo? i.e., Framework.getService(BinaryManger.class)\r
145 \r
146         //      /** The temp file name. */\r
147         //static String tempFileName = "sunset.jpg";\r
148         //      \r
149         //      /** The file separator. */\r
150         //      static String fileSeparator = System.getProperty("file.separator");\r
151         //      \r
152         //      /** The cur dir. */\r
153         //      static String curDir = System.getProperty("user.dir");\r
154 \r
155         /**\r
156          * Instantiates a new nuxeo image utils.\r
157          */\r
158         NuxeoImageUtils() {\r
159                 //empty constructor\r
160         }\r
161 \r
162         private static String toStringPictureView(PictureView pictureView) {\r
163                 StringBuffer strBuffer = new StringBuffer();\r
164                 strBuffer.append("Description: " + pictureView.getDescription() + '\n');\r
165                 strBuffer.append("FileName: " + pictureView.getFilename() + '\n');\r
166                 strBuffer.append("Height: " + pictureView.getHeight() + '\n');\r
167                 strBuffer.append("Width: " + pictureView.getWidth() + '\n');\r
168                 strBuffer.append("Tag: " + pictureView.getTag() + '\n');\r
169                 strBuffer.append("Title: " + pictureView.getTitle() + '\n');\r
170                 return strBuffer.toString();\r
171         }\r
172 \r
173         //FIXME: REM - This needs to be configuration-bases and NOT hard coded!\r
174         //FIXME: REM - Use MultiviewPicture adapter to get some of this information\r
175         static private String getDerivativeUri(String uri, String derivativeName) {\r
176                 String result = DERIVATIVE_UNKNOWN;\r
177 \r
178                 if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_TAG) == true) {\r
179                         result = DERIVATIVE_ORIGINAL;\r
180                 } else if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_JPEG_TAG) == true) {\r
181                         result = DERIVATIVE_ORIGINAL_JPEG;\r
182                 } else if (derivativeName.startsWith(DERIVATIVE_MEDIUM_TAG) == true) {\r
183                         result = DERIVATIVE_MEDIUM;\r
184                 } else if (derivativeName.startsWith(DERIVATIVE_THUMBNAIL_TAG) == true) {\r
185                         result = DERIVATIVE_THUMBNAIL;\r
186                 }\r
187 \r
188                 return uri + result + "/" + BlobInput.URI_CONTENT_PATH;\r
189         }\r
190 \r
191         static private BlobListItem createBlobListItem(Blob blob, String uri) {\r
192                 BlobListItem result = new BlobListItem();\r
193 \r
194                 result.setEncoding(blob.getEncoding());\r
195                 result.setLength(Long.toString(blob.getLength()));\r
196                 result.setMimeType(blob.getMimeType());\r
197                 result.setName(blob.getFilename());\r
198                 result.setUri(getDerivativeUri(uri, blob.getFilename()));\r
199 \r
200                 return result;\r
201         }\r
202 \r
203         static public BlobsCommonList getBlobDerivatives(RepositoryInstance repoSession,\r
204                         String repositoryId,\r
205                         String uri) throws Exception {\r
206                 BlobsCommonList result = new BlobsCommonList();\r
207 \r
208                 IdRef documentRef = new IdRef(repositoryId);\r
209                 DocumentModel documentModel = repoSession.getDocument(documentRef);             \r
210                 DocumentBlobHolder docBlobHolder = (DocumentBlobHolder)documentModel.getAdapter(BlobHolder.class);\r
211                 List<Blob> docBlobs = docBlobHolder.getBlobs();         \r
212                 List<BlobListItem> blobListItems = result.getBlobListItem();\r
213                 BlobListItem blobListItem = null;\r
214                 for (Blob blob : docBlobs) {\r
215                         blobListItem = createBlobListItem(blob, uri);\r
216                         blobListItems.add(blobListItem);\r
217                 }\r
218 \r
219                 return result;\r
220         }\r
221 \r
222         static private BlobsCommon createBlobsCommon(DocumentModel documentModel, Blob nuxeoBlob) {\r
223                 BlobsCommon result = new BlobsCommon();\r
224                 if (documentModel != null) {\r
225                         result.setMimeType(nuxeoBlob.getMimeType());\r
226                         result.setName(nuxeoBlob.getFilename());\r
227                         result.setLength(Long.toString(nuxeoBlob.getLength()));\r
228                         result.setRepositoryId(documentModel.getId());\r
229                 }\r
230                 return result;\r
231         }\r
232 \r
233         static private File getBlobFile(RepositoryInstance ri, DocumentModel documentModel, Blob blob) {\r
234                 DefaultBinaryManager binaryManager = null;\r
235                 RepositoryDescriptor descriptor = null;\r
236 \r
237                 try {\r
238                         ServiceManager sm = (ServiceManager) Framework.getService(ServiceManager.class);\r
239                         ServiceDescriptor[] sd = sm.getServiceDescriptors();\r
240 \r
241                         RepositoryService repositoryService1 = (RepositoryService) Framework.getRuntime().getComponent(\r
242                                         RepositoryService.NAME);\r
243                         RepositoryService repositoryService2 = (RepositoryService) Framework.getRuntime().getService(\r
244                                         RepositoryService.class);\r
245                         RepositoryService repositoryService3 = (RepositoryService) Framework.getService(\r
246                                         RepositoryService.class);\r
247                         RepositoryService repositoryService4 = (RepositoryService) Framework.getLocalService(\r
248                                         RepositoryService.class);\r
249                         ComponentManager componentManager1 = (ComponentManager) Framework.getService(ComponentManager.class);\r
250                         ComponentManager componentManager2 = (ComponentManager) Framework.getService(ComponentManagerImpl.class);\r
251 \r
252 \r
253                         //              RepositoryManager repositoryManager2 = (RepositoryManager) Framework.getService(RepositoryManager.class);\r
254                         //              Repository repository = repositoryManager2.getDefaultRepository();\r
255                         //              Map<String, String> repositoryMap = repository.getProperties();\r
256                         //              String streamURI = ri.getStreamURI(arg0)\r
257 \r
258                         String repositoryName = documentModel.getRepositoryName();\r
259                         //              RepositoryManager repositoryManager2 = (RepositoryManager) Framework.getService(RepositoryManager.class);               \r
260                         RepositoryManager repositoryManager = repositoryService1.getRepositoryManager();\r
261                         descriptor = repositoryManager.getDescriptor(repositoryName);\r
262 \r
263                         binaryManager = new DefaultBinaryManager();\r
264 \r
265                         File storageDir = binaryManager.getStorageDir();\r
266                         //            SQLBlob blob = (SQLBlob) doc.getPropertyValue("schema:blobField");\r
267                         File file = binaryManager.getFileForDigest(\r
268                                         blob.getDigest(), false); \r
269 \r
270                         //              binaryManager = new DefaultBinaryManager();\r
271                 } catch (Exception e) {\r
272                         e.printStackTrace();\r
273                 }\r
274 \r
275                 try {\r
276                         binaryManager.initialize(\r
277                                         SQLRepository.getDescriptor(descriptor));\r
278                 } catch (IOException e) {\r
279                         // TODO Auto-generated catch block\r
280                         e.printStackTrace();\r
281                 } catch (Exception e) {\r
282                         // TODO Auto-generated catch block\r
283                         e.printStackTrace();\r
284                 }\r
285 \r
286                 File storageDir = binaryManager.getStorageDir();\r
287                 //        SQLBlob blob = (SQLBlob) documentModel.getPropertyValue("schema:blobField");\r
288                 File file = binaryManager.getFileForDigest(\r
289                                 blob.getDigest(), false);\r
290 \r
291                 return file;\r
292         }\r
293 \r
294         /**\r
295          * Returns a schema, given the name of a schema.\r
296          *\r
297          * @param schemaName  a schema name.\r
298          * @return  a schema.\r
299          */\r
300         private static Schema getSchemaFromName(String schemaName) {\r
301                 SchemaManager schemaManager = null;\r
302                 try {\r
303                         schemaManager = Framework.getService(SchemaManager.class);\r
304                 } catch (Exception e) {\r
305                         // TODO Auto-generated catch block\r
306                         e.printStackTrace();\r
307                 }\r
308                 return schemaManager != null ? schemaManager.getSchema(schemaName) : null;\r
309         }\r
310 \r
311         /**\r
312          * Gets the blob.\r
313          *\r
314          * @param nuxeoSession the nuxeo session\r
315          * @param id the id\r
316          * @return the blob\r
317          */\r
318         static private Blob getBlob(RepositoryInstance nuxeoSession, String id) {\r
319                 Blob result = null;\r
320 \r
321                 try {\r
322                         Repository repository = nuxeoSession.getRepository();\r
323                         //                      binaryManager.initialize(new RepositoryDescriptor());\r
324                         //                      binaryManager.getBinary("a4cac052ae0281979f2dcf5ab2e61a6c");\r
325                         //              DocumentResolver.resolveReference(nuxeoSession, documentRef);\r
326                         //binaryManager = repository.getBinaryManager();\r
327                         //              documentModel.getr\r
328                 } catch (Exception x) {\r
329                         x.printStackTrace();\r
330                 }\r
331 \r
332                 return result;\r
333         }\r
334 \r
335         /**\r
336          * Gets the type service.\r
337          *\r
338          * @return the type service\r
339          * @throws ClientException the client exception\r
340          */\r
341         private static TypeManager getTypeService() throws ClientException {\r
342                 TypeManager typeService = null;\r
343                 try {\r
344                         typeService = Framework.getService(TypeManager.class);\r
345                 } catch (Exception e) {\r
346                         throw new ClientException(e);\r
347                 }\r
348                 return typeService;\r
349         }\r
350 \r
351         /**\r
352          * Gets the bytes.\r
353          *\r
354          * @param fis the fis\r
355          * @return the bytes\r
356          */\r
357         private static byte[] getBytes(InputStream fis) {\r
358                 ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
359                 byte[] buf = new byte[128 * 1024];\r
360                 try {\r
361                         for (int readNum; (readNum = fis.read(buf)) != -1;) {\r
362                                 bos.write(buf, 0, readNum); \r
363                                 //no doubt here is 0\r
364                                 /*Writes len bytes from the specified byte array starting at offset \r
365                 off to this byte array output stream.*/\r
366                                 System.out.println("read " + readNum + " bytes,");\r
367                         }\r
368                 } catch (IOException ex) {\r
369                         logger.error(ex.getMessage(), ex);\r
370                 }\r
371                 byte[] bytes = bos.toByteArray();\r
372                 //bytes is the ByteArray we need\r
373                 return bytes;\r
374         }\r
375 \r
376         /**\r
377          * Creates the serializable blob.\r
378          *\r
379          * @param fileInputStream the file input stream\r
380          * @param filename the filename\r
381          * @param mimeType the mime type\r
382          * @return the blob\r
383          */\r
384         private static Blob createSerializableBlob(InputStream fileInputStream,\r
385                         String filename, String mimeType) {\r
386                 Blob blob = null;\r
387                 try {\r
388                         // persisting the blob makes it possible to read the binary content\r
389                         // of the request stream several times (mimetype sniffing, digest\r
390                         // computation, core binary storage)\r
391                         byte[] bytes = getBytes(fileInputStream);\r
392                         blob = new ByteArrayBlob(bytes);\r
393                         // filename\r
394                         if (filename != null) {\r
395                                 filename = getCleanFileName(filename);\r
396                         }\r
397                         blob.setFilename(filename);\r
398                         // mimetype detection\r
399                         MimetypeRegistry mimeService = Framework.getService(MimetypeRegistry.class);\r
400                         String detectedMimeType = mimeService.getMimetypeFromFilenameAndBlobWithDefault(\r
401                                         filename, blob, null);\r
402                         if (detectedMimeType == null) {\r
403                                 if (mimeType != null) {\r
404                                         detectedMimeType = mimeType;\r
405                                 } else {\r
406                                         // default\r
407                                         detectedMimeType = "application/octet-stream";\r
408                                 }\r
409                         }\r
410                         blob.setMimeType(detectedMimeType);\r
411                 } catch (MimetypeDetectionException e) {\r
412                         logger.error(String.format("could not fetch mimetype for file %s",\r
413                                         filename), e);\r
414                 } catch (Exception e) {\r
415                         logger.error("", e);\r
416                 }\r
417                 return blob;\r
418         }\r
419 \r
420         /**\r
421          * Creates a serializable blob from a stream, with filename and mimetype\r
422          * detection.\r
423          * \r
424          * <p>\r
425          * Creates an in-memory blob if data is under 64K, otherwise constructs a\r
426          * serializable FileBlob which stores data in a temporary file on the hard\r
427          * disk.\r
428          * </p>\r
429          *\r
430          * @param file the input stream holding data\r
431          * @param filename the file name. Will be set on the blob and will used for\r
432          * mimetype detection.\r
433          * @param mimeType the detected mimetype at upload. Can be null. Will be\r
434          * verified by the mimetype service.\r
435          * @return the blob\r
436          */\r
437         private static Blob createStreamingBlob(InputStream file,\r
438                         String filename, String mimeType) {\r
439                 Blob blob = null;\r
440                 try {\r
441                         // persisting the blob makes it possible to read the binary content\r
442                         // of the request stream several times (mimetype sniffing, digest\r
443                         // computation, core binary storage)\r
444                         blob = StreamingBlob.createFromStream(file, mimeType).persist();\r
445                         // filename\r
446                         if (filename != null) {\r
447                                 filename = getCleanFileName(filename);\r
448                         }\r
449                         blob.setFilename(filename);\r
450                         // mimetype detection\r
451                         MimetypeRegistry mimeService = Framework.getService(MimetypeRegistry.class);\r
452                         String detectedMimeType = mimeService.getMimetypeFromFilenameAndBlobWithDefault(\r
453                                         filename, blob, null);\r
454                         if (detectedMimeType == null) {\r
455                                 if (mimeType != null) {\r
456                                         detectedMimeType = mimeType;\r
457                                 } else {\r
458                                         // default\r
459                                         detectedMimeType = "application/octet-stream";\r
460                                 }\r
461                         }\r
462                         blob.setMimeType(detectedMimeType);\r
463                 } catch (MimetypeDetectionException e) {\r
464                         logger.error(String.format("could not fetch mimetype for file %s",\r
465                                         filename), e);\r
466                 } catch (IOException e) {\r
467                         logger.error("", e);\r
468                 } catch (Exception e) {\r
469                         logger.error("", e);\r
470                 }\r
471                 return blob;\r
472         }\r
473 \r
474         /**\r
475          * Returns a clean filename, stripping upload path on client side.\r
476          * <p>\r
477          * Fixes NXP-544\r
478          * </p>\r
479          *\r
480          * @param filename the filename\r
481          * @return the clean file name\r
482          */\r
483         private static String getCleanFileName(String filename) {\r
484                 String res = null;\r
485                 int lastWinSeparator = filename.lastIndexOf('\\');\r
486                 int lastUnixSeparator = filename.lastIndexOf('/');\r
487                 int lastSeparator = Math.max(lastWinSeparator, lastUnixSeparator);\r
488                 if (lastSeparator != -1) {\r
489                         res = filename.substring(lastSeparator + 1, filename.length());\r
490                 } else {\r
491                         res = filename;\r
492                 }\r
493                 return res;\r
494         }\r
495 \r
496         /**\r
497          * Gets Nuxeo's file manager service.\r
498          *\r
499          * @return the file manager service\r
500          * @throws ClientException the client exception\r
501          */\r
502         private static FileManager getFileManagerService() throws ClientException {\r
503                 FileManager result = null;\r
504                 try {\r
505                         result = Framework.getService(FileManager.class);\r
506                 } catch (Exception e) {\r
507                         String msg = "Unable to get Nuxeo's FileManager service.";\r
508                         logger.error(msg, e);\r
509                         throw new ClientException("msg", e);\r
510                 }\r
511                 return result;\r
512         }\r
513 \r
514         /**\r
515          * Creates the picture.\r
516          *\r
517          * @param ctx the ctx\r
518          * @param repoSession the repo session\r
519          * @param filePath the file path\r
520          * @return the string\r
521          */\r
522         public static BlobsCommon createPicture(ServiceContext ctx,\r
523                         RepositoryInstance repoSession,\r
524                         BlobInput blobInput) {\r
525                 BlobsCommon result = null;\r
526 \r
527                 try {\r
528                         File blobFile = blobInput.getBlobFile();\r
529                         String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();\r
530                         DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);\r
531                         DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);\r
532 \r
533                         FileInputStream inputStream = new FileInputStream(blobFile);            \r
534                         if (inputStream != null) {\r
535                                 result = createImage(repoSession, wspaceDoc,\r
536                                                 inputStream, blobFile.getName(), null);\r
537                         }            \r
538                 } catch (Exception e) {\r
539                         logger.error("Could not create image blob", e);\r
540                 }               \r
541 \r
542                 return result;\r
543         }\r
544 \r
545         /**\r
546          * Creates the image blob.\r
547          *\r
548          * @param nuxeoSession the nuxeo session\r
549          * @param blobLocation the blob location\r
550          * @param file the file\r
551          * @param fileName the file name\r
552          * @param mimeType the mime type\r
553          * @return the string\r
554          */\r
555         static public BlobsCommon createImage(RepositoryInstance nuxeoSession,\r
556                         DocumentModel blobLocation,\r
557                         InputStream file,\r
558                         String fileName, \r
559                         String mimeType) {\r
560                 BlobsCommon result = null;\r
561 \r
562                 try {\r
563                         Blob fileBlob = createStreamingBlob(file, fileName, mimeType);\r
564                         String digestAlgorithm = getFileManagerService().getDigestAlgorithm(); //Need some way on initializing the FileManager with a call.\r
565                         DocumentModel documentModel = getFileManagerService().createDocumentFromBlob(nuxeoSession,\r
566                                         fileBlob, blobLocation.getPathAsString(), true, fileName);\r
567                         result = createBlobsCommon(documentModel, fileBlob);\r
568                 } catch (Exception e) {\r
569                         result = null;\r
570                         logger.error("Could not create new image blob", e);\r
571                 }\r
572 \r
573                 return result;\r
574         }\r
575 \r
576         /**\r
577          * Gets the image.\r
578          *\r
579          * @param repoSession the repo session\r
580          * @param repositoryId the repository id\r
581          * @param derivativeTerm the derivative term\r
582          * @return the image\r
583          */\r
584         static public BlobOutput getBlobOutput(ServiceContext ctx,\r
585                         RepositoryInstance repoSession,\r
586                         String repositoryId, \r
587                         String derivativeTerm,\r
588                         Boolean getContentFlag) {\r
589                 BlobOutput result = new BlobOutput();\r
590 \r
591                 try {\r
592                         IdRef documentRef = new IdRef(repositoryId);\r
593                         DocumentModel documentModel = repoSession.getDocument(documentRef);\r
594 \r
595                         /*\r
596                          * This is a second, and better, approach to getting information about an image\r
597                          * and its corresponding derivatives.\r
598                          */\r
599                         //                      MultiviewPictureAdapter multiviewPictureAdapter = documentModel.getAdapter(MultiviewPictureAdapter.class);\r
600                         MultiviewPictureAdapterFactory multiviewPictureAdapterFactory = new MultiviewPictureAdapterFactory();\r
601                         MultiviewPictureAdapter multiviewPictureAdapter =\r
602                                 (MultiviewPictureAdapter)multiviewPictureAdapterFactory.getAdapter(documentModel, null);\r
603                         if (multiviewPictureAdapter != null) {\r
604                                 PictureView[] pictureViewArray = multiviewPictureAdapter.getViews();\r
605                                 for (PictureView pictureView : pictureViewArray) {\r
606                                         if (logger.isDebugEnabled() == true) {\r
607                                                 logger.debug("-------------------------------------");\r
608                                                 logger.debug(toStringPictureView(pictureView));\r
609                                         }\r
610                                 }\r
611                         }\r
612 \r
613                         Blob docBlob = null;\r
614                         DocumentBlobHolder docBlobHolder = (DocumentBlobHolder)documentModel.getAdapter(BlobHolder.class);\r
615                         if (docBlobHolder instanceof PictureBlobHolder) { // if it is a PictureDocument then it has these Nuxeo schemas: [dublincore, uid, picture, iptc, common, image_metadata]\r
616                                 //\r
617                                 // Need to add the "MultiviewPictureAdapter" support here to get the view data, see above.\r
618                                 //\r
619                                 PictureBlobHolder pictureBlobHolder = (PictureBlobHolder) docBlobHolder;\r
620                                 if (derivativeTerm != null) {\r
621                                         docBlob = pictureBlobHolder.getBlob(derivativeTerm);\r
622                                 } else {\r
623                                         docBlob = pictureBlobHolder.getBlob();\r
624                                 }\r
625                         } else {\r
626                                 docBlob = docBlobHolder.getBlob();\r
627                         }\r
628 \r
629                         //\r
630                         // Create the result instance that will contain the blob metadata\r
631                         // and an InputStream with the bits if the 'getContentFlag' is set\r
632                         //\r
633                         BlobsCommon blobsCommon = createBlobsCommon(documentModel, docBlob);\r
634                         result.setBlobsCommon(blobsCommon);\r
635                         if (getContentFlag == true) {\r
636                                 InputStream remoteStream = docBlob.getStream();\r
637                                 BufferedInputStream bufferedInputStream = new BufferedInputStream(remoteStream);\r
638                                 result.setBlobInputStream(bufferedInputStream); // the input stream of blob bits\r
639                         }\r
640 \r
641                 } catch (Exception e) {\r
642                         if (logger.isErrorEnabled() == true) {\r
643                                 logger.error(e.getMessage(), e);\r
644                         }\r
645                         result = null;\r
646                 }\r
647 \r
648                 return result;\r
649         }\r
650 }\r
651 \r
652 /*\r
653  * Notes and code snippets about Nuxeo's support for binaries and image\r
654  * documents.\r
655  */\r
656 \r
657 /*\r
658  * \r
659  * \r
660  * MultiviewPictureAdapter org.nuxeo.ecm.platform.picture.api.adapters\r
661  * PictureResourceAdapter pictureResourceAdapter = (PictureResourceAdapter)\r
662  * documentModel.getAdapter(PictureResourceAdapter.class); String thumbnailPath\r
663  * = pictureResourceAdapter.getViewXPath("Thumbnail");\r
664  * \r
665  * Map<String,Serializable> blobHolderProps = docBlobHolder.getProperties();\r
666  * String filePath = docBlobHolder.getFilePath(); List<Blob> docBlobs =\r
667  * docBlobHolder.getBlobs();\r
668  * \r
669  * stream = new FileInputStream(fileUploadHolder.getTempFile());\r
670  * \r
671  * public String addFile(InputStream fileUpload, String fileName) fileName =\r
672  * FileUtils.getCleanFileName(fileName); DocumentModel currentDocument =\r
673  * navigationContext.getCurrentDocument(); String path =\r
674  * currentDocument.getPathAsString(); Blob blob =\r
675  * FileUtils.createSerializableBlob(fileUpload, fileName, null);\r
676  * \r
677  * DocumentModel createdDoc = getFileManagerService().createDocumentFromBlob(\r
678  * documentManager, blob, path, true, fileName);\r
679  * eventManager.raiseEventsOnDocumentSelected(createdDoc);\r
680  * \r
681  * protected FileManager fileManager;\r
682  * \r
683  * protected FileManager getFileManagerService() throws ClientException { if\r
684  * (fileManager == null) { try { fileManager =\r
685  * Framework.getService(FileManager.class); } catch (Exception e) {\r
686  * log.error("Unable to get FileManager service ", e); throw new\r
687  * ClientException("Unable to get FileManager service ", e); } } return\r
688  * fileManager; }\r
689  */\r
690 \r
691 /*\r
692  * RepositoryService repositoryService = (RepositoryService)\r
693  * Framework.getRuntime().getComponent( RepositoryService.NAME);\r
694  * RepositoryManager repositoryManager =\r
695  * repositoryService.getRepositoryManager(); RepositoryDescriptor descriptor =\r
696  * repositoryManager.getDescriptor(repositoryName); DefaultBinaryManager\r
697  * binaryManager = new DefaultBinaryManager(\r
698  * SQLRepository.getDescriptor(descriptor)));\r
699  * \r
700  * File storageDir = binaryManager.getStorageDir(); SQLBlob blob = (SQLBlob)\r
701  * doc.getPropertyValue("schema:blobField"); File file =\r
702  * binaryManager.getFileForDigest( blob.getBinary().getDigest(), false);\r
703  */\r
704 \r
705 /*\r
706  * RepositoryInstance.getStreamURI()\r
707  * \r
708  * String getStreamURI(String blobPropertyId) throws ClientException\r
709  * \r
710  * Returns an URI identifying the stream given the blob property id. This method\r
711  * should be used by a client to download the data of a blob property.\r
712  * \r
713  * The blob is fetched from the repository and the blob stream is registered\r
714  * against the streaming service so the stream will be available remotely\r
715  * through stream service API.\r
716  * \r
717  * After the client has called this method, it will be able to download the\r
718  * stream using streaming server API.\r
719  * \r
720  * Returns: an URI identifying the remote stream Throws: ClientException\r
721  */\r
722 \r
723 /*\r
724  * A blob contains usually large data.\r
725  * \r
726  * Document fields holding Blob data are by default fetched in a lazy manner.\r
727  * \r
728  * A Blob object hides the data source and it also describes data properties\r
729  * like the encoding or mime-type.\r
730  * \r
731  * The encoding is used to decode Unicode text content that was stored in an\r
732  * encoded form. If not encoding is specified, the default java encoding is\r
733  * used. The encoding is ignored for binary content.\r
734  * \r
735  * When retrieving the content from a document, it will be returned as source\r
736  * content instead of returning the content bytes.\r
737  * \r
738  * The same is true when setting the content for a document: you set a content\r
739  * source and not directly the content bytes. Ex:\r
740  * \r
741  * File file = new File("/tmp/index.html"); FileBlob fb = new FileBlob(file);\r
742  * fb.setMimeType("text/html"); fb.setEncoding("UTF-8"); // this specifies that\r
743  * content bytes will be stored as UTF-8 document.setProperty("file", "content",\r
744  * fb);\r
745  * \r
746  * \r
747  * Then you may want to retrieve the content as follow:\r
748  * \r
749  * Blob blob = document.getProperty("file:content"); htmlDoc = blob.getString();\r
750  * // the content is decoded from UTF-8 into a java string\r
751  */\r