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