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