2 * NuxeoImageUtils.java
\r
4 * {Purpose of This Class}
\r
6 * {Other Notes Relating to This Class (Optional)}
\r
9 * $LastChangedRevision: $
\r
10 * $LastChangedDate: $
\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
16 * http://www.collectionspace.org
\r
17 * http://wiki.collectionspace.org
\r
19 * Copyright © 2009 {Contributing Institution}.
\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
24 * You may obtain a copy of the ECL 2.0 License at
\r
25 * https://source.collectionspace.org/collection-space/LICENSE.txt
\r
27 package org.collectionspace.services.common.imaging.nuxeo;
\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
40 import org.nuxeo.runtime.api.Framework;
\r
41 //import org.nuxeo.runtime.api.ServiceManager;
\r
42 //import org.nuxeo.runtime.api.ServiceDescriptor;
\r
44 //import org.nuxeo.common.utils.FileUtils;
\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
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
56 import org.nuxeo.ecm.core.repository.RepositoryDescriptor;
\r
57 import org.nuxeo.ecm.core.repository.RepositoryManager;
\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
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
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
87 import org.slf4j.Logger;
\r
88 import org.slf4j.LoggerFactory;
\r
89 //import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase;
\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
105 import org.collectionspace.services.config.service.ListResultField;
\r
107 //import org.collectionspace.ecm.platform.quote.api.QuoteManager;
\r
109 // TODO: Auto-generated Javadoc
\r
111 * The Class NuxeoImageUtils.
\r
113 public class NuxeoImageUtils {
\r
114 /** The Constant logger. */
\r
115 private static final Logger logger = LoggerFactory
\r
116 .getLogger(NuxeoImageUtils.class);
\r
119 * FIXME: REM - These constants should be coming from configuration and NOT
\r
122 public static final String DERIVATIVE_ORIGINAL = "Original";
\r
123 public static final String DERIVATIVE_ORIGINAL_TAG = DERIVATIVE_ORIGINAL
\r
126 public static final String DERIVATIVE_ORIGINAL_JPEG = "OriginalJpeg";
\r
127 public static final String DERIVATIVE_ORIGINAL_JPEG_TAG = DERIVATIVE_ORIGINAL_JPEG
\r
130 public static final String DERIVATIVE_MEDIUM = "Medium";
\r
131 public static final String DERIVATIVE_MEDIUM_TAG = DERIVATIVE_MEDIUM + "_";
\r
133 public static final String DERIVATIVE_THUMBNAIL = "Thumbnail";
\r
134 public static final String DERIVATIVE_THUMBNAIL_TAG = DERIVATIVE_THUMBNAIL
\r
137 public static final String DERIVATIVE_UNKNOWN = "_UNKNOWN_DERIVATIVE_NAME_";
\r
140 // Image Dimension fields
\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
150 // Image Metadata schemas - These are Nuxeo defined schemas
\r
152 public static final String SCHEMA_IPTC = "iptc";
\r
153 public static final String SCHEMA_IMAGE_METADATA = "image_metadata";
\r
155 // static DefaultBinaryManager binaryManager = new DefaultBinaryManager();
\r
156 // //can we get this from Nuxeo? i.e.,
\r
157 // Framework.getService(BinaryManger.class)
\r
159 // /** The temp file name. */
\r
160 // static String tempFileName = "sunset.jpg";
\r
162 // /** The file separator. */
\r
163 // static String fileSeparator = System.getProperty("file.separator");
\r
165 // /** The cur dir. */
\r
166 // static String curDir = System.getProperty("user.dir");
\r
169 * Instantiates a new nuxeo image utils.
\r
171 NuxeoImageUtils() {
\r
172 // empty constructor
\r
176 * Use this for debugging Nuxeo's PictureView class
\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
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
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
204 return uri + result + "/" + BlobInput.URI_CONTENT_PATH;
\r
207 static private HashMap<String, Object> createBlobListItem(Blob blob,
\r
209 HashMap<String, Object> item = new HashMap<String, Object>();
\r
211 String value = blob.getEncoding();
\r
212 if (value != null && !value.trim().isEmpty()) {
\r
213 item.put(BlobJAXBSchema.encoding, value);
\r
215 value = Long.toString(blob.getLength());
\r
216 if (value != null && !value.trim().isEmpty()) {
\r
217 item.put(BlobJAXBSchema.length, value);
\r
219 value = blob.getMimeType();
\r
220 if (value != null && !value.trim().isEmpty()) {
\r
221 item.put(BlobJAXBSchema.mimeType, value);
\r
223 value = blob.getFilename();
\r
224 if (value != null && !value.trim().isEmpty()) {
\r
225 item.put(BlobJAXBSchema.name, value);
\r
227 value = getDerivativeUri(uri, blob.getFilename());
\r
228 if (value != null && !value.trim().isEmpty()) {
\r
229 item.put(BlobJAXBSchema.uri, value);
\r
235 static public CommonList getBlobDerivatives(RepositoryInstance repoSession,
\r
236 String repositoryId, List<ListResultField> resultsFields, String uri)
\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
243 for (int i = 2; i < nFields; i++) {
\r
244 ListResultField field = resultsFields.get(i - 2);
\r
245 fields[i] = field.getElement();
\r
247 commonList.setFieldsReturned(fields);
\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
265 * [dublincore, uid, picture, iptc, common, image_metadata]
\r
267 static private Map<String, Object> getMetadata(Blob nuxeoBlob)
\r
269 ImagingService service = Framework.getService(ImagingService.class);
\r
270 Map<String, Object> metadataMap = service.getImageMetadata(nuxeoBlob);
\r
271 return metadataMap;
\r
274 static private MeasuredPartGroupList getDimensions(
\r
275 DocumentModel documentModel, Blob nuxeoBlob) {
\r
276 MeasuredPartGroupList result = null;
\r
278 ImagingService service = Framework.getService(ImagingService.class);
\r
279 ImageInfo imageInfo = service.getImageInfo(nuxeoBlob);
\r
280 Map<String, Object> metadataMap = getMetadata(nuxeoBlob);
\r
282 if (imageInfo != null) {
\r
284 // Create a timestamp to add to all the image's dimensions
\r
286 String valueDate = GregorianCalendarDateTimeUtils
\r
289 result = new MeasuredPartGroupList();
\r
290 List<MeasuredPartGroup> measuredPartGroupList =
\r
291 (result).getMeasuredPartGroup();
\r
293 // Create a new measured part for the "image"
\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
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
314 DimensionSubGroup heightDimension = new DimensionSubGroup();
\r
315 heightDimension.setDimension(HEIGHT);
\r
316 heightDimension.setMeasurementUnit(UNIT_PIXELS);
\r
318 .setValue(intToBigDecimal(imageInfo.getHeight()));
\r
319 heightDimension.setValueDate(valueDate);
\r
320 dimensionSubGroupList.add(heightDimension);
\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
331 // Now set out result
\r
333 measuredPartGroupList.add(mpGroup);
\r
335 if (logger.isWarnEnabled() == true) {
\r
336 logger.warn("Could not synthesize a dimension list of the blob: "
\r
337 + documentModel.getName());
\r
340 } catch (Exception e) {
\r
341 logger.warn("Could not extract image information for blob: "
\r
342 + documentModel.getName(), e);
\r
348 // FIXME: Add error checking here, as none of these calls return an
\r
350 static private BigDecimal intToBigDecimal(int i) {
\r
351 BigInteger bigint = BigInteger.valueOf(i);
\r
352 BigDecimal bigdec = new BigDecimal(bigint);
\r
356 static private BlobsCommon createBlobsCommon(DocumentModel documentModel,
\r
358 BlobsCommon result = new BlobsCommon();
\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
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
379 static private File getBlobFile(RepositoryInstance ri,
\r
380 DocumentModel documentModel, Blob blob) {
\r
381 DefaultBinaryManager binaryManager = null;
\r
382 RepositoryDescriptor descriptor = null;
\r
386 RepositoryService repositoryService1 = (RepositoryService) Framework
\r
387 .getRuntime().getComponent(RepositoryService.NAME);
\r
389 String repositoryName = documentModel.getRepositoryName();
\r
390 RepositoryManager repositoryManager = repositoryService1
\r
391 .getRepositoryManager();
\r
392 descriptor = repositoryManager.getDescriptor(repositoryName);
\r
394 // Keep this code around for future work/enhancements
\r
395 // binaryManager = new DefaultBinaryManager();
\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
402 } catch (Exception e) {
\r
403 e.printStackTrace();
\r
406 // Keep this code around for future work/enhancements
\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
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
427 * Returns a schema, given the name of a schema. Possibly usefule in the future
\r
429 * @param schemaName
\r
431 * @return a schema.
\r
433 private static Schema getSchemaFromName(String schemaName) {
\r
434 SchemaManager schemaManager = null;
\r
436 schemaManager = Framework.getService(SchemaManager.class);
\r
437 } catch (Exception e) {
\r
438 // TODO Auto-generated catch block
\r
439 e.printStackTrace();
\r
441 return schemaManager != null ? schemaManager.getSchema(schemaName)
\r
446 * Gets the blob. Not in use now, but might be useful in the future.
\r
448 * @param nuxeoSession
\r
449 * the nuxeo session
\r
454 static private Blob getBlob(RepositoryInstance nuxeoSession, String id) {
\r
455 Blob result = null;
\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
472 * Gets the type service. Not in use, but please keep for future reference
\r
474 * @return the type service
\r
475 * @throws ClientException
\r
476 * the client exception
\r
478 private static TypeManager getTypeService() throws ClientException {
\r
479 TypeManager typeService = null;
\r
481 typeService = Framework.getService(TypeManager.class);
\r
482 } catch (Exception e) {
\r
483 throw new ClientException(e);
\r
485 return typeService;
\r
493 * @return the bytes
\r
495 private static byte[] getBytes(InputStream fis) {
\r
496 ByteArrayOutputStream bos = new ByteArrayOutputStream();
\r
497 byte[] buf = new byte[128 * 1024];
\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
503 * Writes len bytes from the specified byte array starting at
\r
504 * offset off to this byte array output stream.
\r
506 System.out.println("read " + readNum + " bytes,");
\r
508 } catch (IOException ex) {
\r
509 logger.error(ex.getMessage(), ex);
\r
511 byte[] bytes = bos.toByteArray();
\r
512 // bytes is the ByteArray we need
\r
517 * Creates the serializable blob. We may need this code, do not remove.
\r
519 * @param fileInputStream
\r
520 * the file input stream
\r
527 private static Blob createSerializableBlob(InputStream fileInputStream,
\r
528 String filename, String mimeType) {
\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
537 if (filename != null) {
\r
538 filename = getCleanFileName(filename);
\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
547 if (detectedMimeType == null) {
\r
548 if (mimeType != null) {
\r
549 detectedMimeType = mimeType;
\r
552 detectedMimeType = "application/octet-stream";
\r
555 blob.setMimeType(detectedMimeType);
\r
556 } catch (MimetypeDetectionException e) {
\r
557 logger.error(String.format("could not fetch mimetype for file %s",
\r
559 } catch (Exception e) {
\r
560 logger.error("", e);
\r
566 * Creates a serializable blob from a stream, with filename and mimetype
\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
576 * the input stream holding data
\r
578 * the file name. Will be set on the blob and will used for
\r
579 * mimetype detection.
\r
581 * the detected mimetype at upload. Can be null. Will be verified
\r
582 * by the mimetype service.
\r
585 private static Blob createStreamingBlob(File file, String filename,
\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
594 if (filename != null) {
\r
595 filename = getCleanFileName(filename);
\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
604 if (detectedMimeType == null) {
\r
605 if (mimeType != null) {
\r
606 detectedMimeType = mimeType;
\r
609 detectedMimeType = "application/octet-stream";
\r
612 blob.setMimeType(detectedMimeType);
\r
613 } catch (MimetypeDetectionException e) {
\r
614 logger.error(String.format("could not fetch mimetype for file %s",
\r
616 } catch (IOException e) {
\r
617 logger.error("", e);
\r
618 } catch (Exception e) {
\r
619 logger.error("", e);
\r
624 private static Blob createNuxeoFileBasedBlob(File file) {
\r
625 Blob result = null;
\r
627 result = new FileBlob(file);
\r
632 * Returns a clean filename, stripping upload path on client side.
\r
639 * @return the clean file name
\r
641 private static String getCleanFileName(String filename) {
\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
655 * Gets Nuxeo's file manager service.
\r
657 * @return the file manager service
\r
658 * @throws ClientException
\r
659 * the client exception
\r
661 private static FileManager getFileManagerService() throws ClientException {
\r
662 FileManager result = null;
\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
674 * Creates the picture.
\r
678 * @param repoSession
\r
682 * @return the string
\r
683 * @throws Exception
\r
685 public static BlobsCommon createBlobInRepository(ServiceContext ctx,
\r
686 RepositoryInstance repoSession, BlobInput blobInput) throws Exception {
\r
687 BlobsCommon result = null;
\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
695 if (logger.isDebugEnabled()) {
\r
696 for (String facet : wspaceDoc.getFacets()) {
\r
697 logger.debug("Facet: " + facet);
\r
699 for (String docType : wspaceDoc.getDocumentType().getChildrenTypes()) {
\r
700 logger.debug("Child type: " + docType);
\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
714 * Creates the image blob.
\r
716 * @param nuxeoSession
\r
717 * the nuxeo session
\r
718 * @param blobLocation
\r
719 * the blob location
\r
726 * @return the string
\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
735 // Blob fileBlob = createStreamingBlob(blobFile, blobFile.getName(),
\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
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
746 logger.debug("Stop --> Finished calling Nuxeo to create the blob document.");
\r
748 result = createBlobsCommon(documentModel, fileBlob); // Now create our metadata resource document
\r
749 } catch (Exception e) {
\r
751 logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception?
\r
758 // * This is an alternate approach to getting information about an image
\r
759 // * and its corresponding derivatives.
\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
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
781 * @param repoSession
\r
783 * @param repositoryId
\r
784 * the repository id
\r
785 * @param derivativeTerm
\r
786 * the derivative term
\r
787 * @return the image
\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
796 if (repositoryId != null && repositoryId.isEmpty() == false)
\r
798 IdRef documentRef = new IdRef(repositoryId);
\r
799 DocumentModel documentModel = repoSession.getDocument(documentRef);
\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
808 // Need to add the "MultiviewPictureAdapter" support here to
\r
809 // get the view data, see above.
\r
811 PictureBlobHolder pictureBlobHolder = (PictureBlobHolder) docBlobHolder;
\r
812 if (derivativeTerm != null) {
\r
813 docBlob = pictureBlobHolder.getBlob(derivativeTerm);
\r
815 docBlob = pictureBlobHolder.getBlob();
\r
818 docBlob = docBlobHolder.getBlob();
\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
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
836 } catch (Exception e) {
\r
837 if (logger.isErrorEnabled() == true) {
\r
838 logger.error(e.getMessage(), e);
\r
848 * Notes and code snippets about Nuxeo's support for binaries and image
\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
860 * Map<String,Serializable> blobHolderProps = docBlobHolder.getProperties();
\r
861 * String filePath = docBlobHolder.getFilePath(); List<Blob> docBlobs =
\r
862 * docBlobHolder.getBlobs();
\r
864 * stream = new FileInputStream(fileUploadHolder.getTempFile());
\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
872 * DocumentModel createdDoc = getFileManagerService().createDocumentFromBlob(
\r
873 * documentManager, blob, path, true, fileName);
\r
874 * eventManager.raiseEventsOnDocumentSelected(createdDoc);
\r
876 * protected FileManager fileManager;
\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
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
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
901 * RepositoryInstance.getStreamURI()
\r
903 * String getStreamURI(String blobPropertyId) throws ClientException
\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
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
912 * After the client has called this method, it will be able to download the
\r
913 * stream using streaming server API.
\r
915 * Returns: an URI identifying the remote stream Throws: ClientException
\r
919 * A blob contains usually large data.
\r
921 * Document fields holding Blob data are by default fetched in a lazy manner.
\r
923 * A Blob object hides the data source and it also describes data properties
\r
924 * like the encoding or mime-type.
\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
930 * When retrieving the content from a document, it will be returned as source
\r
931 * content instead of returning the content bytes.
\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
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
942 * Then you may want to retrieve the content as follow:
\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