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