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