]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
67af453bcd539202bdd34f8a99b5ed435e8a0dfd
[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.awt.Color;\r
30 import java.awt.Font;\r
31 import java.awt.Graphics;\r
32 import java.awt.image.BufferedImage;\r
33 import java.io.ByteArrayInputStream;\r
34 import java.io.File;\r
35 import java.io.ByteArrayOutputStream;\r
36 import java.io.FileDescriptor;\r
37 import java.io.FileInputStream;\r
38 import java.io.FileNotFoundException;\r
39 import java.io.InputStream;\r
40 import java.io.BufferedInputStream;\r
41 import java.io.IOException;\r
42 import java.io.Serializable;\r
43 import java.math.BigDecimal;\r
44 import java.math.BigInteger;\r
45 import java.util.HashMap;\r
46 import java.util.List;\r
47 import java.util.Map;\r
48 import java.util.Random;\r
49 import java.util.Set;\r
50 import java.lang.reflect.Field;\r
51 \r
52 import javax.imageio.ImageIO;\r
53 \r
54 import org.nuxeo.runtime.api.Framework;\r
55 //import org.nuxeo.runtime.api.ServiceManager;\r
56 //import org.nuxeo.runtime.api.ServiceDescriptor;\r
57 \r
58 //import org.nuxeo.common.utils.FileUtils;\r
59 \r
60 import org.nuxeo.ecm.platform.picture.api.ImageInfo;\r
61 import org.nuxeo.ecm.platform.picture.api.ImagingDocumentConstants;\r
62 import org.nuxeo.ecm.platform.picture.api.ImagingService;\r
63 import org.nuxeo.ecm.platform.picture.api.PictureView;\r
64 \r
65 import org.nuxeo.ecm.platform.mimetype.MimetypeDetectionException;\r
66 import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry;\r
67 import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolder;\r
68 import org.nuxeo.ecm.platform.filemanager.api.FileManager;\r
69 import org.nuxeo.ecm.platform.types.TypeManager;\r
70 \r
71 import org.nuxeo.ecm.core.repository.RepositoryDescriptor;\r
72 import org.nuxeo.ecm.core.repository.RepositoryManager;\r
73 \r
74 import org.nuxeo.ecm.core.repository.RepositoryService;\r
75 //import org.nuxeo.runtime.model.ComponentManager;\r
76 //import org.nuxeo.runtime.model.impl.ComponentManagerImpl;\r
77 //import org.nuxeo.ecm.core.api.ejb.DocumentManagerBean;\r
78 //import org.nuxeo.ecm.core.storage.sql.RepositoryImpl;\r
79 //import org.nuxeo.ecm.core.storage.sql.Repository;\r
80 import org.nuxeo.ecm.core.storage.sql.Binary;\r
81 import org.nuxeo.ecm.core.storage.sql.BinaryManager;\r
82 import org.nuxeo.ecm.core.storage.sql.DefaultBinaryManager;\r
83 import org.nuxeo.ecm.core.storage.sql.RepositoryImpl;\r
84 import org.nuxeo.ecm.core.storage.sql.RepositoryResolver;\r
85 import org.nuxeo.ecm.core.storage.sql.coremodel.SQLBlob;\r
86 import org.nuxeo.ecm.core.storage.sql.coremodel.SQLRepository;\r
87 //import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor;\r
88 \r
89 //import org.nuxeo.ecm.core.api.DocumentResolver;\r
90 import org.nuxeo.ecm.core.api.IdRef;\r
91 import org.nuxeo.ecm.core.api.blobholder.BlobHolder;\r
92 import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder;\r
93 import org.nuxeo.ecm.core.api.impl.DocumentModelImpl;\r
94 import org.nuxeo.ecm.core.api.impl.blob.FileBlob;\r
95 import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob;\r
96 import org.nuxeo.ecm.core.api.impl.blob.ByteArrayBlob;\r
97 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;\r
98 import org.nuxeo.ecm.core.api.repository.Repository;\r
99 import org.nuxeo.ecm.core.api.Blob;\r
100 import org.nuxeo.ecm.core.api.ClientException;\r
101 import org.nuxeo.ecm.core.api.DocumentModel;\r
102 import org.nuxeo.ecm.core.api.DocumentRef;\r
103 \r
104 import org.nuxeo.ecm.core.schema.DocumentType;\r
105 import org.nuxeo.ecm.core.schema.SchemaManager;\r
106 import org.nuxeo.ecm.core.schema.types.Schema;\r
107 \r
108 import org.slf4j.Logger;\r
109 import org.slf4j.LoggerFactory;\r
110 //import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase;\r
111 \r
112 import org.collectionspace.services.common.ServiceMain;\r
113 import org.collectionspace.services.common.blob.BlobInput;\r
114 import org.collectionspace.services.common.context.ServiceContext;\r
115 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;\r
116 import org.collectionspace.services.blob.BlobsCommon;\r
117 import org.collectionspace.services.blob.DimensionSubGroup;\r
118 import org.collectionspace.services.blob.DimensionSubGroupList;\r
119 import org.collectionspace.services.blob.MeasuredPartGroup;\r
120 import org.collectionspace.services.blob.MeasuredPartGroupList;\r
121 //import org.collectionspace.services.blob.BlobsCommonList;\r
122 //import org.collectionspace.services.blob.BlobsCommonList.BlobListItem;\r
123 import org.collectionspace.services.jaxb.BlobJAXBSchema;\r
124 import org.collectionspace.services.nuxeo.client.java.CommonList;\r
125 import org.collectionspace.services.nuxeo.extension.thumbnail.ThumbnailConstants;\r
126 import org.collectionspace.services.nuxeo.util.NuxeoUtils;\r
127 import org.collectionspace.services.common.blob.BlobOutput;\r
128 \r
129 import org.collectionspace.services.config.service.ListResultField;\r
130 \r
131 \r
132 /**\r
133  * The Class NuxeoImageUtils.\r
134  */\r
135 public class NuxeoImageUtils {\r
136                 \r
137         /** The Constant logger. */\r
138         private static final Logger logger = LoggerFactory\r
139                         .getLogger(NuxeoImageUtils.class);\r
140 \r
141         public static final String DOCUMENT_PLACEHOLDER_IMAGE = "documentImage.jpg";\r
142         public static final String DOCUMENT_MISSING_PLACEHOLDER_IMAGE = "documentImageMissing.jpg";\r
143         public static final String MIME_JPEG = "image/jpeg";\r
144         /*\r
145          * FIXME: REM - These constants should be coming from configuration and NOT\r
146          * hard coded.\r
147          */\r
148         public static final String DERIVATIVE_ORIGINAL = "Original";\r
149         public static final String DERIVATIVE_ORIGINAL_TAG = DERIVATIVE_ORIGINAL\r
150                         + "_";\r
151 \r
152         public static final String DERIVATIVE_ORIGINAL_JPEG = "OriginalJpeg";\r
153         public static final String DERIVATIVE_ORIGINAL_JPEG_TAG = DERIVATIVE_ORIGINAL_JPEG\r
154                         + "_";\r
155 \r
156         public static final String DERIVATIVE_MEDIUM = "Medium";\r
157         public static final String DERIVATIVE_MEDIUM_TAG = DERIVATIVE_MEDIUM + "_";\r
158 \r
159         public static final String DERIVATIVE_THUMBNAIL = "Thumbnail";\r
160         public static final String DERIVATIVE_THUMBNAIL_TAG = DERIVATIVE_THUMBNAIL\r
161                         + "_";\r
162 \r
163         public static final String DERIVATIVE_UNKNOWN = "_UNKNOWN_DERIVATIVE_NAME_";\r
164 \r
165         //\r
166         // Image Dimension fields\r
167         //\r
168         public static final String PART_IMAGE = "digitalImage";\r
169         public static final String PART_SUMMARY = "The dimensions of a digital image -width, height, and pixel depth.";\r
170         public static final String WIDTH = "width";\r
171         public static final String HEIGHT = "height";\r
172         public static final String DEPTH = "depth";\r
173         public static final String UNIT_PIXELS = "pixels";\r
174         public static final String UNIT_BITS = "bits";\r
175         //\r
176         // Image Metadata schemas - These are Nuxeo defined schemas\r
177         //\r
178         public static final String SCHEMA_IPTC = "iptc";\r
179         public static final String SCHEMA_IMAGE_METADATA = "image_metadata";\r
180 \r
181         private static final int THUMB_SIZE_HEIGHT = 100;\r
182 \r
183         private static final int THUMB_SIZE_WIDTH = 75;\r
184 \r
185         // static DefaultBinaryManager binaryManager = new DefaultBinaryManager();\r
186         // //can we get this from Nuxeo? i.e.,\r
187         // Framework.getService(BinaryManger.class)\r
188 \r
189         // /** The temp file name. */\r
190         // static String tempFileName = "sunset.jpg";\r
191         //\r
192         // /** The file separator. */\r
193         // static String fileSeparator = System.getProperty("file.separator");\r
194         //\r
195         // /** The cur dir. */\r
196         // static String curDir = System.getProperty("user.dir");\r
197 \r
198         /**\r
199          * Instantiates a new nuxeo image utils.\r
200          */\r
201         NuxeoImageUtils() {\r
202                 // empty constructor\r
203         }\r
204 \r
205         /*\r
206          * Use this for debugging Nuxeo's PictureView class\r
207          */\r
208         private static String toStringPictureView(PictureView pictureView) {\r
209                 StringBuffer strBuffer = new StringBuffer();\r
210                 strBuffer.append("Description: " + pictureView.getDescription() + '\n');\r
211                 strBuffer.append("FileName: " + pictureView.getFilename() + '\n');\r
212                 strBuffer.append("Height: " + pictureView.getHeight() + '\n');\r
213                 strBuffer.append("Width: " + pictureView.getWidth() + '\n');\r
214                 strBuffer.append("Tag: " + pictureView.getTag() + '\n');\r
215                 strBuffer.append("Title: " + pictureView.getTitle() + '\n');\r
216                 return strBuffer.toString();\r
217         }\r
218 \r
219         // FIXME: REM - This needs to be configuration-bases and NOT hard coded!\r
220         // FIXME: REM - Use MultiviewPicture adapter to get some of this information\r
221         static private String getDerivativeUri(String uri, String derivativeName) {\r
222                 String result = DERIVATIVE_UNKNOWN;\r
223 \r
224                 if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_TAG) == true) {\r
225                         result = DERIVATIVE_ORIGINAL;\r
226                 } else if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_JPEG_TAG) == true) {\r
227                         result = DERIVATIVE_ORIGINAL_JPEG;\r
228                 } else if (derivativeName.startsWith(DERIVATIVE_MEDIUM_TAG) == true) {\r
229                         result = DERIVATIVE_MEDIUM;\r
230                 } else if (derivativeName.startsWith(DERIVATIVE_THUMBNAIL_TAG) == true) {\r
231                         result = DERIVATIVE_THUMBNAIL;\r
232                 }\r
233 \r
234                 return uri + result + "/" + BlobInput.URI_CONTENT_PATH;\r
235         }\r
236 \r
237         static private HashMap<String, Object> createBlobListItem(Blob blob,\r
238                         String uri) {\r
239                 HashMap<String, Object> item = new HashMap<String, Object>();\r
240 \r
241                 String value = blob.getEncoding();\r
242                 if (value != null && !value.trim().isEmpty()) {\r
243                         item.put(BlobJAXBSchema.encoding, value);\r
244                 }\r
245                 value = Long.toString(blob.getLength());\r
246                 if (value != null && !value.trim().isEmpty()) {\r
247                         item.put(BlobJAXBSchema.length, value);\r
248                 }\r
249                 value = blob.getMimeType();\r
250                 if (value != null && !value.trim().isEmpty()) {\r
251                         item.put(BlobJAXBSchema.mimeType, value);\r
252                 }\r
253                 value = blob.getFilename();\r
254                 if (value != null && !value.trim().isEmpty()) {\r
255                         item.put(BlobJAXBSchema.name, value);\r
256                 }\r
257                 value = getDerivativeUri(uri, blob.getFilename());\r
258                 if (value != null && !value.trim().isEmpty()) {\r
259                         item.put(BlobJAXBSchema.uri, value);\r
260                 }\r
261 \r
262                 return item;\r
263         }\r
264 \r
265         static public CommonList getBlobDerivatives(RepositoryInstance repoSession,\r
266                         String repositoryId, List<ListResultField> resultsFields, String uri)\r
267                         throws Exception {\r
268                 CommonList commonList = new CommonList();\r
269                 int nFields = resultsFields.size() + 2;\r
270                 String fields[] = new String[nFields];// FIXME: REM - Patrick needs to fix this hack.  It is a "common list" issue\r
271                 fields[0] = "csid";\r
272                 fields[1] = "uri";\r
273                 for (int i = 2; i < nFields; i++) {\r
274                         ListResultField field = resultsFields.get(i - 2);\r
275                         fields[i] = field.getElement();\r
276                 }\r
277                 commonList.setFieldsReturned(fields);\r
278 \r
279                 IdRef documentRef = new IdRef(repositoryId);\r
280                 DocumentModel documentModel = repoSession.getDocument(documentRef);\r
281                 DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel\r
282                                 .getAdapter(BlobHolder.class);\r
283                 List<Blob> docBlobs = docBlobHolder.getBlobs();\r
284                 // List<BlobListItem> blobListItems = result.getBlobListItem();\r
285                 HashMap<String, Object> item = null;\r
286                 for (Blob blob : docBlobs) {\r
287                         if (blob != null) {\r
288                                 item = createBlobListItem(blob, uri);\r
289                                 commonList.addItem(item);\r
290                         }\r
291                 }\r
292 \r
293                 return commonList;\r
294         }\r
295 \r
296         /*\r
297          * [dublincore, uid, picture, iptc, common, image_metadata]\r
298          */\r
299         static private Map<String, Object> getMetadata(Blob nuxeoBlob)\r
300                         throws Exception {\r
301                 ImagingService service = Framework.getService(ImagingService.class);\r
302                 Map<String, Object> metadataMap = service.getImageMetadata(nuxeoBlob);\r
303                 return metadataMap;\r
304         }\r
305 \r
306         private static String[] imageTypes = {"jpeg", "bmp", "gif", "png", "tiff", "octet-stream"};\r
307         static private boolean isImageMedia(Blob nuxeoBlob) {\r
308                 boolean result = false;\r
309                 \r
310                 String mimeType = nuxeoBlob.getMimeType().toLowerCase().trim();\r
311                 String[] parts = mimeType.split("/"); // split strings like "application/xml" into an array of two strings\r
312                 if (parts.length == 2) {\r
313                         for (String type : imageTypes) {\r
314                                 if (parts[1].equalsIgnoreCase(type)) {\r
315                                         result = true;\r
316                                         break;\r
317                                 }\r
318                         }\r
319                 }\r
320                 \r
321                 return result;\r
322         }\r
323         \r
324         static private MeasuredPartGroupList getDimensions(\r
325                         DocumentModel documentModel, Blob nuxeoBlob) {\r
326                 MeasuredPartGroupList result = null;\r
327                 \r
328                 if (isImageMedia(nuxeoBlob) == true) try {\r
329                         ImagingService service = Framework.getService(ImagingService.class);\r
330                         ImageInfo imageInfo = service.getImageInfo(nuxeoBlob);\r
331                         Map<String, Object> metadataMap = getMetadata(nuxeoBlob);\r
332 \r
333                         if (imageInfo != null) {\r
334                                 //\r
335                                 // Create a timestamp to add to all the image's dimensions\r
336                                 //\r
337                                 String valueDate = GregorianCalendarDateTimeUtils\r
338                                                 .timestampUTC();\r
339                                 \r
340                                 result = new MeasuredPartGroupList();\r
341                                 List<MeasuredPartGroup> measuredPartGroupList = \r
342                                                 (result).getMeasuredPartGroup();\r
343                                 //\r
344                                 // Create a new measured part for the "image"\r
345                                 //\r
346                                 MeasuredPartGroup mpGroup = new MeasuredPartGroup();\r
347                                 mpGroup.setMeasuredPart(PART_IMAGE);\r
348                                 mpGroup.setDimensionSummary(PART_SUMMARY);\r
349                                 mpGroup.setDimensionSubGroupList(new DimensionSubGroupList());\r
350                                 List<DimensionSubGroup> dimensionSubGroupList = mpGroup.getDimensionSubGroupList()\r
351                                                 .getDimensionSubGroup();\r
352 \r
353                                 //\r
354                                 // Set the width\r
355                                 //\r
356                                 DimensionSubGroup widthDimension = new DimensionSubGroup();\r
357                                 widthDimension.setDimension(WIDTH);\r
358                                 widthDimension.setMeasurementUnit(UNIT_PIXELS);\r
359                                 widthDimension.setValue(intToBigDecimal(imageInfo.getWidth()));\r
360                                 widthDimension.setValueDate(valueDate);\r
361                                 dimensionSubGroupList.add(widthDimension);\r
362                                 //\r
363                                 // Set the height\r
364                                 //\r
365                                 DimensionSubGroup heightDimension = new DimensionSubGroup();\r
366                                 heightDimension.setDimension(HEIGHT);\r
367                                 heightDimension.setMeasurementUnit(UNIT_PIXELS);\r
368                                 heightDimension\r
369                                                 .setValue(intToBigDecimal(imageInfo.getHeight()));\r
370                                 heightDimension.setValueDate(valueDate);\r
371                                 dimensionSubGroupList.add(heightDimension);\r
372                                 //\r
373                                 // Set the depth\r
374                                 //\r
375                                 DimensionSubGroup depthDimension = new DimensionSubGroup();\r
376                                 depthDimension.setDimension(DEPTH);\r
377                                 depthDimension.setMeasurementUnit(UNIT_BITS);\r
378                                 depthDimension.setValue(intToBigDecimal(imageInfo.getDepth()));\r
379                                 depthDimension.setValueDate(valueDate);\r
380                                 dimensionSubGroupList.add(depthDimension);\r
381                                 //\r
382                                 // Now set out result\r
383                                 //\r
384                                 measuredPartGroupList.add(mpGroup);\r
385                         } else {\r
386                                 if (logger.isWarnEnabled() == true) {\r
387                                         logger.warn("Could not synthesize a dimension list of the blob: "\r
388                                                         + documentModel.getName());\r
389                                 }\r
390                         }\r
391                 } catch (Exception e) {\r
392                         logger.warn("Could not extract image information for blob: "\r
393                                         + documentModel.getName(), e);\r
394                 }\r
395 \r
396                 return result;\r
397         }\r
398 \r
399         // FIXME: Add error checking here, as none of these calls return an\r
400         // Exception\r
401         static private BigDecimal intToBigDecimal(int i) {\r
402                 BigInteger bigint = BigInteger.valueOf(i);\r
403                 BigDecimal bigdec = new BigDecimal(bigint);\r
404                 return bigdec;\r
405         }\r
406 \r
407         static private BlobsCommon createBlobsCommon(DocumentModel documentModel,\r
408                         Blob nuxeoBlob) {\r
409                 BlobsCommon result = new BlobsCommon();\r
410 \r
411                 if (documentModel != null) {\r
412                         result.setMimeType(nuxeoBlob.getMimeType());\r
413                         result.setName(nuxeoBlob.getFilename());\r
414                         result.setLength(Long.toString(nuxeoBlob.getLength()));\r
415                         result.setRepositoryId(documentModel.getId());\r
416                         MeasuredPartGroupList measuredPartGroupList = getDimensions(\r
417                                         documentModel, nuxeoBlob);\r
418                         if (measuredPartGroupList != null) {\r
419                                 result.setMeasuredPartGroupList(measuredPartGroupList);\r
420                         }\r
421                         \r
422                         // Check to see if a thumbnail preview was created by Nuxeo\r
423             if (documentModel.hasFacet(ThumbnailConstants.THUMBNAIL_FACET)) {\r
424                         String errorMsg = null;\r
425                 String thumbnailName = null;\r
426                                 try {\r
427                                         thumbnailName = (String)documentModel.getProperty(ThumbnailConstants.THUMBNAIL_SCHEMA_NAME,\r
428                                                 ThumbnailConstants.THUMBNAIL_FILENAME_PROPERTY_NAME);\r
429                                         Blob thumbnailBlob = (Blob)documentModel.getProperty(ThumbnailConstants.THUMBNAIL_SCHEMA_NAME,\r
430                                                 ThumbnailConstants.THUMBNAIL_PROPERTY_NAME);\r
431                                 } catch (ClientException e) {\r
432                                         errorMsg = "Could not extract the name of the thumbnail preview image file.";\r
433                                         if (logger.isTraceEnabled()) {\r
434                                                 logger.trace(errorMsg, e);\r
435                                         }\r
436                                 }\r
437                                 \r
438                                 if (errorMsg == null) {\r
439                                         logger.info("A thumbnail preview was created for this document blob: " + thumbnailName);\r
440                                 } else {\r
441                                         logger.warn(errorMsg);\r
442                                 }\r
443             }\r
444                 }\r
445 \r
446                 return result;\r
447         }\r
448 \r
449         /*\r
450          * This is a prototype method that is not currently used as of 1/1/2012.  However,\r
451          * it may be useful now that we've transitioned to using an embedded Nuxeo server.\r
452          */\r
453         static private File getBlobFile(RepositoryInstance ri,\r
454                         DocumentModel documentModel, Blob blob) {\r
455                 DefaultBinaryManager binaryManager = null;\r
456                 RepositoryDescriptor descriptor = null;\r
457                 File file = null;\r
458 \r
459                 try {\r
460                         RepositoryService repositoryService1 = (RepositoryService) Framework\r
461                                         .getRuntime().getComponent(RepositoryService.NAME);\r
462 \r
463                         String repositoryName = documentModel.getRepositoryName();\r
464                         RepositoryManager repositoryManager = repositoryService1\r
465                                         .getRepositoryManager();\r
466                         descriptor = repositoryManager.getDescriptor(repositoryName);\r
467 \r
468 // Keep this code around for future work/enhancements                   \r
469 //                      binaryManager = new DefaultBinaryManager();\r
470 //\r
471 //                      File storageDir = binaryManager.getStorageDir();\r
472 //                      // SQLBlob blob = (SQLBlob)\r
473 //                      // doc.getPropertyValue("schema:blobField");\r
474 //                      File file = binaryManager.getFileForDigest(blob.getDigest(), false);\r
475 \r
476                 } catch (Exception e) {\r
477                         e.printStackTrace();\r
478                 }\r
479 \r
480 // Keep this code around for future work/enhancements\r
481 //              try {\r
482 //                      binaryManager.initialize(SQLRepository.getDescriptor(descriptor));\r
483 //              } catch (IOException e) {\r
484 //                      // TODO Auto-generated catch block\r
485 //                      e.printStackTrace();\r
486 //              } catch (Exception e) {\r
487 //                      // TODO Auto-generated catch block\r
488 //                      e.printStackTrace();\r
489 //              }\r
490 \r
491 // Keep this code around for future work/enhancements\r
492 //              File storageDir = binaryManager.getStorageDir();\r
493 //              SQLBlob blob = (SQLBlob)\r
494 //              documentModel.getPropertyValue("schema:blobField");\r
495 //              File file = binaryManager.getFileForDigest(blob.getDigest(), false);\r
496 \r
497                 return file;\r
498         }\r
499 \r
500         /**\r
501          * Returns a schema, given the name of a schema.  Possibly usefule in the future\r
502          * \r
503          * @param schemaName\r
504          *            a schema name.\r
505          * @return a schema.\r
506          */\r
507         private static Schema getSchemaFromName(String schemaName) {\r
508                 SchemaManager schemaManager = null;\r
509                 try {\r
510                         schemaManager = Framework.getService(SchemaManager.class);\r
511                 } catch (Exception e) {\r
512                         // TODO Auto-generated catch block\r
513                         e.printStackTrace();\r
514                 }\r
515                 return schemaManager != null ? schemaManager.getSchema(schemaName)\r
516                                 : null;\r
517         }\r
518 \r
519         /**\r
520          * Gets the blob.  Not in use now, but might be useful in the future.\r
521          * \r
522          * @param nuxeoSession\r
523          *            the nuxeo session\r
524          * @param id\r
525          *            the id\r
526          * @return the blob\r
527          */\r
528         static private Blob getBlob(RepositoryInstance nuxeoSession, String id) {\r
529                 Blob result = null;\r
530 \r
531                 try {\r
532                         Repository repository = nuxeoSession.getRepository();\r
533                         // binaryManager.initialize(new RepositoryDescriptor());\r
534                         // binaryManager.getBinary("a4cac052ae0281979f2dcf5ab2e61a6c");\r
535                         // DocumentResolver.resolveReference(nuxeoSession, documentRef);\r
536                         // binaryManager = repository.getBinaryManager();\r
537                         // documentModel.getr\r
538                 } catch (Exception x) {\r
539                         x.printStackTrace();\r
540                 }\r
541 \r
542                 return result;\r
543         }\r
544 \r
545         /**\r
546          * Gets the type service.  Not in use, but please keep for future reference\r
547          * \r
548          * @return the type service\r
549          * @throws ClientException\r
550          *             the client exception\r
551          */\r
552         private static TypeManager getTypeService() throws ClientException {\r
553                 TypeManager typeService = null;\r
554                 try {\r
555                         typeService = Framework.getService(TypeManager.class);\r
556                 } catch (Exception e) {\r
557                         throw new ClientException(e);\r
558                 }\r
559                 return typeService;\r
560         }\r
561 \r
562         /**\r
563          * Gets the bytes.\r
564          * \r
565          * @param fis\r
566          *            the fis\r
567          * @return the bytes\r
568          */\r
569         private static byte[] getBytes(InputStream fis) {\r
570                 ByteArrayOutputStream bos = new ByteArrayOutputStream();\r
571                 byte[] buf = new byte[128 * 1024];\r
572                 try {\r
573                         for (int readNum; (readNum = fis.read(buf)) != -1;) {\r
574                                 bos.write(buf, 0, readNum);\r
575                                 // no doubt here is 0\r
576                                 /*\r
577                                  * Writes len bytes from the specified byte array starting at\r
578                                  * offset off to this byte array output stream.\r
579                                  */\r
580                                 System.out.println("read " + readNum + " bytes,");\r
581                         }\r
582                 } catch (IOException ex) {\r
583                         logger.error(ex.getMessage(), ex);\r
584                 }\r
585                 byte[] bytes = bos.toByteArray();\r
586                 // bytes is the ByteArray we need\r
587                 return bytes;\r
588         }\r
589 \r
590         /**\r
591          * Creates the serializable blob.  We may need this code, do not remove.\r
592          * \r
593          * @param fileInputStream\r
594          *            the file input stream\r
595          * @param filename\r
596          *            the filename\r
597          * @param mimeType\r
598          *            the mime type\r
599          * @return the blob\r
600          */\r
601         private static Blob createSerializableBlob(InputStream fileInputStream,\r
602                         String filename, String mimeType) {\r
603                 Blob blob = null;\r
604                 try {\r
605                         // persisting the blob makes it possible to read the binary content\r
606                         // of the request stream several times (mimetype sniffing, digest\r
607                         // computation, core binary storage)\r
608                         byte[] bytes = getBytes(fileInputStream);\r
609                         blob = new ByteArrayBlob(bytes);\r
610                         // filename\r
611                         if (filename != null) {\r
612                                 filename = getCleanFileName(filename);\r
613                         }\r
614                         blob.setFilename(filename);\r
615                         // mimetype detection\r
616                         MimetypeRegistry mimeService = Framework\r
617                                         .getService(MimetypeRegistry.class);\r
618                         String detectedMimeType = mimeService\r
619                                         .getMimetypeFromFilenameAndBlobWithDefault(filename, blob,\r
620                                                         null);\r
621                         if (detectedMimeType == null) {\r
622                                 if (mimeType != null) {\r
623                                         detectedMimeType = mimeType;\r
624                                 } else {\r
625                                         // default\r
626                                         detectedMimeType = "application/octet-stream";\r
627                                 }\r
628                         }\r
629                         blob.setMimeType(detectedMimeType);\r
630                 } catch (MimetypeDetectionException e) {\r
631                         logger.error(String.format("could not fetch mimetype for file %s",\r
632                                         filename), e);\r
633                 } catch (Exception e) {\r
634                         logger.error("", e);\r
635                 }\r
636                 return blob;\r
637         }\r
638 \r
639         /**\r
640          * Creates a serializable blob from a stream, with filename and mimetype\r
641          * detection.\r
642          * \r
643          * <p>\r
644          * Creates an in-memory blob if data is under 64K, otherwise constructs a\r
645          * serializable FileBlob which stores data in a temporary file on the hard\r
646          * disk.\r
647          * </p>\r
648          * \r
649          * @param file\r
650          *            the input stream holding data\r
651          * @param filename\r
652          *            the file name. Will be set on the blob and will used for\r
653          *            mimetype detection.\r
654          * @param mimeType\r
655          *            the detected mimetype at upload. Can be null. Will be verified\r
656          *            by the mimetype service.\r
657          * @return the blob\r
658          */\r
659         private static Blob createStreamingBlob(File file, String filename,\r
660                         String mimeType) {\r
661                 Blob blob = null;\r
662                 try {\r
663                         // persisting the blob makes it possible to read the binary content\r
664                         // of the request stream several times (mimetype sniffing, digest\r
665                         // computation, core binary storage)\r
666                         blob = StreamingBlob.createFromFile(file, mimeType).persist();\r
667                         // filename\r
668                         if (filename != null) {\r
669                                 filename = getCleanFileName(filename);\r
670                         }\r
671                         blob.setFilename(filename);\r
672                         // mimetype detection\r
673                         MimetypeRegistry mimeService = Framework\r
674                                         .getService(MimetypeRegistry.class);\r
675                         String detectedMimeType = mimeService\r
676                                         .getMimetypeFromFilenameAndBlobWithDefault(filename, blob,\r
677                                                         null);\r
678                         if (detectedMimeType == null) {\r
679                                 if (mimeType != null) {\r
680                                         detectedMimeType = mimeType;\r
681                                 } else {\r
682                                         // default\r
683                                         detectedMimeType = "application/octet-stream";\r
684                                 }\r
685                         }\r
686                         blob.setMimeType(detectedMimeType);\r
687                 } catch (MimetypeDetectionException e) {\r
688                         logger.error(String.format("could not fetch mimetype for file %s",\r
689                                         filename), e);\r
690                 } catch (IOException e) {\r
691                         logger.error("", e);\r
692                 } catch (Exception e) {\r
693                         logger.error("", e);\r
694                 }\r
695                 return blob;\r
696         }\r
697 \r
698         private static Blob createNuxeoFileBasedBlob(File file) {\r
699                 Blob result = null;\r
700 \r
701                 result = new FileBlob(file);\r
702                 return result;\r
703         }\r
704 \r
705         /**\r
706          * Returns a clean filename, stripping upload path on client side.\r
707          * <p>\r
708          * Fixes NXP-544\r
709          * </p>\r
710          * \r
711          * @param filename\r
712          *            the filename\r
713          * @return the clean file name\r
714          */\r
715         private static String getCleanFileName(String filename) {\r
716                 String res = null;\r
717                 int lastWinSeparator = filename.lastIndexOf('\\');\r
718                 int lastUnixSeparator = filename.lastIndexOf('/');\r
719                 int lastSeparator = Math.max(lastWinSeparator, lastUnixSeparator);\r
720                 if (lastSeparator != -1) {\r
721                         res = filename.substring(lastSeparator + 1, filename.length());\r
722                 } else {\r
723                         res = filename;\r
724                 }\r
725                 return res;\r
726         }\r
727 \r
728         /**\r
729          * Gets Nuxeo's file manager service.\r
730          * \r
731          * @return the file manager service\r
732          * @throws ClientException\r
733          *             the client exception\r
734          */\r
735         private static FileManager getFileManagerService() throws ClientException {\r
736                 FileManager result = null;\r
737                 try {\r
738                         result = Framework.getService(FileManager.class);\r
739                 } catch (Exception e) {\r
740                         String msg = "Unable to get Nuxeo's FileManager service.";\r
741                         logger.error(msg, e);\r
742                         throw new ClientException("msg", e);\r
743                 }\r
744                 return result;\r
745         }\r
746         \r
747         private static BinaryManager getBinaryManagerService() throws ClientException {\r
748                 BinaryManager result = null;\r
749                 try {\r
750                         result = Framework.getService(BinaryManager.class);\r
751                 } catch (Exception e) {\r
752                         String msg = "Unable to get Nuxeo's BinaryManager service.";\r
753                         logger.error(msg, e);\r
754                         throw new ClientException("msg", e);\r
755                 }\r
756                 return result;\r
757         }\r
758         \r
759 \r
760         /**\r
761          * Creates the picture.\r
762          * \r
763          * @param ctx\r
764          *            the ctx\r
765          * @param repoSession\r
766          *            the repo session\r
767          * @param filePath\r
768          *            the file path\r
769          * @return the string\r
770          * @throws Exception \r
771          */\r
772         public static BlobsCommon createBlobInRepository(ServiceContext ctx,\r
773                         RepositoryInstance repoSession,\r
774                         BlobInput blobInput,\r
775                         boolean purgeOriginal) throws Exception {\r
776                 BlobsCommon result = null;\r
777 \r
778                 try {\r
779                         File blobFile = blobInput.getBlobFile();\r
780                         String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();\r
781                         DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);\r
782                         DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);\r
783                         \r
784             if (logger.isTraceEnabled()) {\r
785                     for (String facet : wspaceDoc.getFacets()) {\r
786                         logger.trace("Facet: " + facet);\r
787                     }\r
788                     for (String docType : wspaceDoc.getDocumentType().getChildrenTypes()) {\r
789                         logger.trace("Child type: " + docType);\r
790                     }\r
791             }                   \r
792 \r
793                         result = createBlobInRepository(repoSession, wspaceDoc, purgeOriginal, blobFile, null /*mime type*/);\r
794                 } catch (Exception e) {\r
795                         logger.error("Could not create image blob", e);\r
796                         throw e;\r
797                 }\r
798 \r
799                 return result;\r
800         }\r
801 \r
802         /**\r
803          * Creates the image blob.\r
804          * \r
805          * @param nuxeoSession\r
806          *            the nuxeo session\r
807          * @param blobLocation\r
808          *            the blob location\r
809          * @param file\r
810          *            the file\r
811          * @param fileName\r
812          *            the file name\r
813          * @param mimeType\r
814          *            the mime type\r
815          * @return the string\r
816          */\r
817         static public BlobsCommon createBlobInRepository(RepositoryInstance nuxeoSession,\r
818                         DocumentModel blobLocation,\r
819                         boolean purgeOriginal,\r
820                         File file,\r
821                         String mimeType) {\r
822                 BlobsCommon result = null;\r
823 \r
824                 try {\r
825                         // Blob fileBlob = createStreamingBlob(blobFile, blobFile.getName(),\r
826                         // mimeType);\r
827                         Blob fileBlob = createNuxeoFileBasedBlob(file);\r
828                         String digestAlgorithm = getFileManagerService()\r
829                                         .getDigestAlgorithm(); // Only call this because we seem to need some way of initializing Nuxeo's FileManager with a call.\r
830                         \r
831                         logger.debug("Start --> Starting call to Nuxeo to create the blob document."); // For example, see Nuxeo's DefaultPictureAdapter class for details\r
832                         DocumentModel documentModel = getFileManagerService()\r
833                                         .createDocumentFromBlob(nuxeoSession, fileBlob,\r
834                                                         blobLocation.getPathAsString(), true,\r
835                                                         file.getName());\r
836                         logger.debug("Stop --> Finished calling Nuxeo to create the blob document.");\r
837 \r
838                         result = createBlobsCommon(documentModel, fileBlob); // Now create our metadata resource document\r
839 \r
840                         // If the sender only wanted use to generate derivatives, we need to clear the original content\r
841                         if (purgeOriginal == true) {\r
842                                 // Empty the document model's "content" property -this does not delete the actual file/blob\r
843                                 documentModel.setPropertyValue("file:content", (Serializable) null);\r
844                                 \r
845                                 if (documentModel.hasFacet(ImagingDocumentConstants.PICTURE_FACET)) {\r
846                                         // Now with no content, the derivative listener wants to update the derivatives. So to\r
847                                         // prevent the listener, we remove the "Picture" facet from the document\r
848                                         NuxeoUtils.removeFacet(documentModel, ImagingDocumentConstants.PICTURE_FACET); // Removing this facet ensures the original derivatives are unchanged.\r
849                                         nuxeoSession.saveDocument(documentModel);\r
850                                         // Now that we've emptied the document model's content field, we can add back the Picture facet\r
851                                         NuxeoUtils.addFacet(documentModel, ImagingDocumentConstants.PICTURE_FACET);\r
852                                 }\r
853                                 \r
854                                 nuxeoSession.saveDocument(documentModel);\r
855                                 // Next, we need to remove the actual file from Nuxeo's data directory\r
856                                 DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel\r
857                                                 .getAdapter(BlobHolder.class);\r
858                                 boolean deleteSuccess = NuxeoUtils.deleteFileOfBlob(docBlobHolder.getBlob());\r
859                         }\r
860                 } catch (Exception e) {\r
861                         result = null;\r
862                         logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception?\r
863                 }\r
864 \r
865                 return result;\r
866         }\r
867 \r
868         // /*\r
869         // * This is an alternate approach to getting information about an image\r
870         // * and its corresponding derivatives.\r
871         // */\r
872         // // MultiviewPictureAdapter multiviewPictureAdapter =\r
873         // documentModel.getAdapter(MultiviewPictureAdapter.class);\r
874         // MultiviewPictureAdapterFactory multiviewPictureAdapterFactory = new\r
875         // MultiviewPictureAdapterFactory();\r
876         // MultiviewPictureAdapter multiviewPictureAdapter =\r
877         // (MultiviewPictureAdapter)multiviewPictureAdapterFactory.getAdapter(documentModel,\r
878         // null);\r
879         // if (multiviewPictureAdapter != null) {\r
880         // PictureView[] pictureViewArray = multiviewPictureAdapter.getViews();\r
881         // for (PictureView pictureView : pictureViewArray) {\r
882         // if (logger.isDebugEnabled() == true) {\r
883         // logger.debug("-------------------------------------");\r
884         // logger.debug(toStringPictureView(pictureView));\r
885         // }\r
886         // }\r
887         // }\r
888         \r
889         public static InputStream getResource(String resourceName) {\r
890                 InputStream result = null;\r
891                 \r
892                 try {\r
893                         result = ServiceMain.getInstance().getResourceAsStream(resourceName);\r
894                 } catch (FileNotFoundException e) {\r
895                         logger.error("Missing Services resource: " + resourceName, e);\r
896                 }\r
897         \r
898                 return result;\r
899         }\r
900 \r
901         /**\r
902          * Gets the image.\r
903          * \r
904          * @param repoSession\r
905          *            the repo session\r
906          * @param repositoryId\r
907          *            the repository id\r
908          * @param derivativeTerm\r
909          *            the derivative term\r
910          * @return the image\r
911          */\r
912         static public BlobOutput getBlobOutput(ServiceContext ctx,\r
913                         RepositoryInstance repoSession,\r
914                         String repositoryId,\r
915                         String derivativeTerm,\r
916                         Boolean getContentFlag,\r
917                         StringBuffer outMimeType) {\r
918                 BlobOutput result = new BlobOutput();\r
919                 boolean isNonImageDerivative = false;\r
920 \r
921                 if (repositoryId != null && repositoryId.isEmpty() == false)\r
922                         try {\r
923                                 IdRef documentRef = new IdRef(repositoryId);\r
924                                 DocumentModel documentModel = repoSession.getDocument(documentRef);\r
925 \r
926                                 Blob docBlob = null;\r
927                                 DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel\r
928                                                 .getAdapter(BlobHolder.class);\r
929                                 if (docBlobHolder instanceof PictureBlobHolder) {\r
930                                         // if it is a PictureDocument then it has these\r
931                                         // Nuxeo schemas: [dublincore, uid, picture, iptc, common, image_metadata]\r
932                                         //\r
933                                         // Need to add the "MultiviewPictureAdapter" support here to\r
934                                         // get the view data, see above.\r
935                                         //\r
936                                         PictureBlobHolder pictureBlobHolder = (PictureBlobHolder) docBlobHolder;\r
937                                         if (derivativeTerm != null) {\r
938                                                 docBlob = pictureBlobHolder.getBlob(derivativeTerm);\r
939                                                 // Nuxeo derivatives are all JPEG\r
940                                                 outMimeType.append(MIME_JPEG); // All Nuxeo image derivatives are JPEG images.\r
941                                         } else {\r
942                                                 docBlob = pictureBlobHolder.getBlob();\r
943                                         }\r
944                                 } else {\r
945                                         docBlob = docBlobHolder.getBlob();\r
946                                         if (derivativeTerm != null) { // If its a derivative request on a non-image blob, then return just a document image thumnail\r
947                                                 isNonImageDerivative = true;\r
948                                         }\r
949                                 }\r
950 \r
951                                 //\r
952                                 // Create the result instance that will contain the blob metadata\r
953                                 // and an InputStream with the bits if the 'getContentFlag' is\r
954                                 // set.\r
955                                 //\r
956                                 BlobsCommon blobsCommon = createBlobsCommon(documentModel, docBlob);\r
957                                 result.setBlobsCommon(blobsCommon);\r
958                                 if (getContentFlag == true) {\r
959                                         InputStream remoteStream = null;\r
960                                         if (isNonImageDerivative == false) {\r
961                                                 remoteStream = docBlob.getStream(); // This will fail if the blob's file has been deleted. FileNotFoundException thrown.\r
962                                         } else {\r
963                                                 remoteStream = getResource(DOCUMENT_PLACEHOLDER_IMAGE);\r
964                                                 outMimeType.append(MIME_JPEG);\r
965                                         }\r
966                                         BufferedInputStream bufferedInputStream = new BufferedInputStream(\r
967                                                         remoteStream);  \r
968                                         result.setBlobInputStream(bufferedInputStream);\r
969                                 }\r
970                         } catch (Exception e) {\r
971                                 if (logger.isErrorEnabled() == true) {\r
972                                         logger.error(e.getMessage(), e);\r
973                                 }\r
974                                 result = null;\r
975                         }\r
976 \r
977                 return result;\r
978         }\r
979         \r
980 }\r
981 \r
982 /*\r
983  * Notes and code snippets about Nuxeo's support for binaries and image\r
984  * documents.\r
985  */\r
986 \r
987 /*\r
988  * \r
989  * \r
990  * MultiviewPictureAdapter org.nuxeo.ecm.platform.picture.api.adapters\r
991  * PictureResourceAdapter pictureResourceAdapter = (PictureResourceAdapter)\r
992  * documentModel.getAdapter(PictureResourceAdapter.class); String thumbnailPath\r
993  * = pictureResourceAdapter.getViewXPath("Thumbnail");\r
994  * \r
995  * Map<String,Serializable> blobHolderProps = docBlobHolder.getProperties();\r
996  * String filePath = docBlobHolder.getFilePath(); List<Blob> docBlobs =\r
997  * docBlobHolder.getBlobs();\r
998  * \r
999  * stream = new FileInputStream(fileUploadHolder.getTempFile());\r
1000  * \r
1001  * public String addFile(InputStream fileUpload, String fileName) fileName =\r
1002  * FileUtils.getCleanFileName(fileName); DocumentModel currentDocument =\r
1003  * navigationContext.getCurrentDocument(); String path =\r
1004  * currentDocument.getPathAsString(); Blob blob =\r
1005  * FileUtils.createSerializableBlob(fileUpload, fileName, null);\r
1006  * \r
1007  * DocumentModel createdDoc = getFileManagerService().createDocumentFromBlob(\r
1008  * documentManager, blob, path, true, fileName);\r
1009  * eventManager.raiseEventsOnDocumentSelected(createdDoc);\r
1010  * \r
1011  * protected FileManager fileManager;\r
1012  * \r
1013  * protected FileManager getFileManagerService() throws ClientException { if\r
1014  * (fileManager == null) { try { fileManager =\r
1015  * Framework.getService(FileManager.class); } catch (Exception e) {\r
1016  * log.error("Unable to get FileManager service ", e); throw new\r
1017  * ClientException("Unable to get FileManager service ", e); } } return\r
1018  * fileManager; }\r
1019  */\r
1020 \r
1021 /*\r
1022  * RepositoryService repositoryService = (RepositoryService)\r
1023  * Framework.getRuntime().getComponent( RepositoryService.NAME);\r
1024  * RepositoryManager repositoryManager =\r
1025  * repositoryService.getRepositoryManager(); RepositoryDescriptor descriptor =\r
1026  * repositoryManager.getDescriptor(repositoryName); DefaultBinaryManager\r
1027  * binaryManager = new DefaultBinaryManager(\r
1028  * SQLRepository.getDescriptor(descriptor)));\r
1029  * \r
1030  * File storageDir = binaryManager.getStorageDir(); SQLBlob blob = (SQLBlob)\r
1031  * doc.getPropertyValue("schema:blobField"); File file =\r
1032  * binaryManager.getFileForDigest( blob.getBinary().getDigest(), false);\r
1033  */\r
1034 \r
1035 /*\r
1036  * RepositoryInstance.getStreamURI()\r
1037  * \r
1038  * String getStreamURI(String blobPropertyId) throws ClientException\r
1039  * \r
1040  * Returns an URI identifying the stream given the blob property id. This method\r
1041  * should be used by a client to download the data of a blob property.\r
1042  * \r
1043  * The blob is fetched from the repository and the blob stream is registered\r
1044  * against the streaming service so the stream will be available remotely\r
1045  * through stream service API.\r
1046  * \r
1047  * After the client has called this method, it will be able to download the\r
1048  * stream using streaming server API.\r
1049  * \r
1050  * Returns: an URI identifying the remote stream Throws: ClientException\r
1051  */\r
1052 \r
1053 /*\r
1054  * A blob contains usually large data.\r
1055  * \r
1056  * Document fields holding Blob data are by default fetched in a lazy manner.\r
1057  * \r
1058  * A Blob object hides the data source and it also describes data properties\r
1059  * like the encoding or mime-type.\r
1060  * \r
1061  * The encoding is used to decode Unicode text content that was stored in an\r
1062  * encoded form. If not encoding is specified, the default java encoding is\r
1063  * used. The encoding is ignored for binary content.\r
1064  * \r
1065  * When retrieving the content from a document, it will be returned as source\r
1066  * content instead of returning the content bytes.\r
1067  * \r
1068  * The same is true when setting the content for a document: you set a content\r
1069  * source and not directly the content bytes. Ex:\r
1070  * \r
1071  * File file = new File("/tmp/index.html"); FileBlob fb = new FileBlob(file);\r
1072  * fb.setMimeType("text/html"); fb.setEncoding("UTF-8"); // this specifies that\r
1073  * content bytes will be stored as UTF-8 document.setProperty("file", "content",\r
1074  * fb);\r
1075  * \r
1076  * \r
1077  * Then you may want to retrieve the content as follow:\r
1078  * \r
1079  * Blob blob = document.getProperty("file:content"); htmlDoc = blob.getString();\r
1080  * // the content is decoded from UTF-8 into a java string\r
1081  */\r