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