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.awt.Color;
\r
30 import java.awt.Font;
\r
31 import java.awt.Graphics;
\r
32 import java.awt.image.BufferedImage;
\r
33 import java.io.File;
\r
34 import java.io.ByteArrayOutputStream;
\r
35 import java.io.InputStream;
\r
36 import java.io.BufferedInputStream;
\r
37 import java.io.IOException;
\r
38 import java.math.BigDecimal;
\r
39 import java.math.BigInteger;
\r
40 import java.util.HashMap;
\r
41 import java.util.List;
\r
42 import java.util.Map;
\r
43 import java.util.Random;
\r
45 import javax.imageio.ImageIO;
\r
47 import org.nuxeo.runtime.api.Framework;
\r
48 //import org.nuxeo.runtime.api.ServiceManager;
\r
49 //import org.nuxeo.runtime.api.ServiceDescriptor;
\r
51 //import org.nuxeo.common.utils.FileUtils;
\r
53 import org.nuxeo.ecm.platform.picture.api.ImageInfo;
\r
54 import org.nuxeo.ecm.platform.picture.api.ImagingService;
\r
55 import org.nuxeo.ecm.platform.picture.api.PictureView;
\r
57 import org.nuxeo.ecm.platform.mimetype.MimetypeDetectionException;
\r
58 import org.nuxeo.ecm.platform.mimetype.interfaces.MimetypeRegistry;
\r
59 import org.nuxeo.ecm.platform.picture.api.adapters.PictureBlobHolder;
\r
60 import org.nuxeo.ecm.platform.filemanager.api.FileManager;
\r
61 import org.nuxeo.ecm.platform.types.TypeManager;
\r
63 import org.nuxeo.ecm.core.repository.RepositoryDescriptor;
\r
64 import org.nuxeo.ecm.core.repository.RepositoryManager;
\r
66 import org.nuxeo.ecm.core.repository.RepositoryService;
\r
67 //import org.nuxeo.runtime.model.ComponentManager;
\r
68 //import org.nuxeo.runtime.model.impl.ComponentManagerImpl;
\r
69 //import org.nuxeo.ecm.core.api.ejb.DocumentManagerBean;
\r
70 //import org.nuxeo.ecm.core.storage.sql.RepositoryImpl;
\r
71 //import org.nuxeo.ecm.core.storage.sql.Repository;
\r
72 import org.nuxeo.ecm.core.storage.sql.DefaultBinaryManager;
\r
73 import org.nuxeo.ecm.core.storage.sql.coremodel.SQLRepository;
\r
74 //import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor;
\r
76 //import org.nuxeo.ecm.core.api.DocumentResolver;
\r
77 import org.nuxeo.ecm.core.api.IdRef;
\r
78 import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
\r
79 import org.nuxeo.ecm.core.api.blobholder.DocumentBlobHolder;
\r
80 import org.nuxeo.ecm.core.api.impl.blob.FileBlob;
\r
81 import org.nuxeo.ecm.core.api.impl.blob.StreamingBlob;
\r
82 import org.nuxeo.ecm.core.api.impl.blob.ByteArrayBlob;
\r
83 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
\r
84 import org.nuxeo.ecm.core.api.repository.Repository;
\r
85 import org.nuxeo.ecm.core.api.Blob;
\r
86 import org.nuxeo.ecm.core.api.ClientException;
\r
87 import org.nuxeo.ecm.core.api.DocumentModel;
\r
88 import org.nuxeo.ecm.core.api.DocumentRef;
\r
90 import org.nuxeo.ecm.core.schema.DocumentType;
\r
91 import org.nuxeo.ecm.core.schema.SchemaManager;
\r
92 import org.nuxeo.ecm.core.schema.types.Schema;
\r
94 import org.slf4j.Logger;
\r
95 import org.slf4j.LoggerFactory;
\r
96 //import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase;
\r
98 import org.collectionspace.services.common.blob.BlobInput;
\r
99 import org.collectionspace.services.common.context.ServiceContext;
\r
100 import org.collectionspace.services.common.datetime.GregorianCalendarDateTimeUtils;
\r
101 import org.collectionspace.services.blob.BlobsCommon;
\r
102 import org.collectionspace.services.blob.DimensionSubGroup;
\r
103 import org.collectionspace.services.blob.DimensionSubGroupList;
\r
104 import org.collectionspace.services.blob.MeasuredPartGroup;
\r
105 import org.collectionspace.services.blob.MeasuredPartGroupList;
\r
106 //import org.collectionspace.services.blob.BlobsCommonList;
\r
107 //import org.collectionspace.services.blob.BlobsCommonList.BlobListItem;
\r
108 import org.collectionspace.services.jaxb.BlobJAXBSchema;
\r
109 import org.collectionspace.services.nuxeo.client.java.CommonList;
\r
110 import org.collectionspace.services.common.blob.BlobOutput;
\r
112 import org.collectionspace.services.config.service.ListResultField;
\r
114 //import org.collectionspace.ecm.platform.quote.api.QuoteManager;
\r
116 // TODO: Auto-generated Javadoc
\r
118 * The Class NuxeoImageUtils.
\r
120 public class NuxeoImageUtils {
\r
121 /** The Constant logger. */
\r
122 private static final Logger logger = LoggerFactory
\r
123 .getLogger(NuxeoImageUtils.class);
\r
125 private static final String MIME_JPEG = "image/jpeg";
\r
127 * FIXME: REM - These constants should be coming from configuration and NOT
\r
130 public static final String DERIVATIVE_ORIGINAL = "Original";
\r
131 public static final String DERIVATIVE_ORIGINAL_TAG = DERIVATIVE_ORIGINAL
\r
134 public static final String DERIVATIVE_ORIGINAL_JPEG = "OriginalJpeg";
\r
135 public static final String DERIVATIVE_ORIGINAL_JPEG_TAG = DERIVATIVE_ORIGINAL_JPEG
\r
138 public static final String DERIVATIVE_MEDIUM = "Medium";
\r
139 public static final String DERIVATIVE_MEDIUM_TAG = DERIVATIVE_MEDIUM + "_";
\r
141 public static final String DERIVATIVE_THUMBNAIL = "Thumbnail";
\r
142 public static final String DERIVATIVE_THUMBNAIL_TAG = DERIVATIVE_THUMBNAIL
\r
145 public static final String DERIVATIVE_UNKNOWN = "_UNKNOWN_DERIVATIVE_NAME_";
\r
148 // Image Dimension fields
\r
150 public static final String PART_IMAGE = "digitalImage";
\r
151 public static final String PART_SUMMARY = "The dimensions of a digital image -width, height, and pixel depth.";
\r
152 public static final String WIDTH = "width";
\r
153 public static final String HEIGHT = "height";
\r
154 public static final String DEPTH = "depth";
\r
155 public static final String UNIT_PIXELS = "pixels";
\r
156 public static final String UNIT_BITS = "bits";
\r
158 // Image Metadata schemas - These are Nuxeo defined schemas
\r
160 public static final String SCHEMA_IPTC = "iptc";
\r
161 public static final String SCHEMA_IMAGE_METADATA = "image_metadata";
\r
163 private static final int THUMB_SIZE_HEIGHT = 100;
\r
165 private static final int THUMB_SIZE_WIDTH = 75;
\r
167 // static DefaultBinaryManager binaryManager = new DefaultBinaryManager();
\r
168 // //can we get this from Nuxeo? i.e.,
\r
169 // Framework.getService(BinaryManger.class)
\r
171 // /** The temp file name. */
\r
172 // static String tempFileName = "sunset.jpg";
\r
174 // /** The file separator. */
\r
175 // static String fileSeparator = System.getProperty("file.separator");
\r
177 // /** The cur dir. */
\r
178 // static String curDir = System.getProperty("user.dir");
\r
181 * Instantiates a new nuxeo image utils.
\r
183 NuxeoImageUtils() {
\r
184 // empty constructor
\r
188 * Use this for debugging Nuxeo's PictureView class
\r
190 private static String toStringPictureView(PictureView pictureView) {
\r
191 StringBuffer strBuffer = new StringBuffer();
\r
192 strBuffer.append("Description: " + pictureView.getDescription() + '\n');
\r
193 strBuffer.append("FileName: " + pictureView.getFilename() + '\n');
\r
194 strBuffer.append("Height: " + pictureView.getHeight() + '\n');
\r
195 strBuffer.append("Width: " + pictureView.getWidth() + '\n');
\r
196 strBuffer.append("Tag: " + pictureView.getTag() + '\n');
\r
197 strBuffer.append("Title: " + pictureView.getTitle() + '\n');
\r
198 return strBuffer.toString();
\r
201 // FIXME: REM - This needs to be configuration-bases and NOT hard coded!
\r
202 // FIXME: REM - Use MultiviewPicture adapter to get some of this information
\r
203 static private String getDerivativeUri(String uri, String derivativeName) {
\r
204 String result = DERIVATIVE_UNKNOWN;
\r
206 if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_TAG) == true) {
\r
207 result = DERIVATIVE_ORIGINAL;
\r
208 } else if (derivativeName.startsWith(DERIVATIVE_ORIGINAL_JPEG_TAG) == true) {
\r
209 result = DERIVATIVE_ORIGINAL_JPEG;
\r
210 } else if (derivativeName.startsWith(DERIVATIVE_MEDIUM_TAG) == true) {
\r
211 result = DERIVATIVE_MEDIUM;
\r
212 } else if (derivativeName.startsWith(DERIVATIVE_THUMBNAIL_TAG) == true) {
\r
213 result = DERIVATIVE_THUMBNAIL;
\r
216 return uri + result + "/" + BlobInput.URI_CONTENT_PATH;
\r
219 static private HashMap<String, Object> createBlobListItem(Blob blob,
\r
221 HashMap<String, Object> item = new HashMap<String, Object>();
\r
223 String value = blob.getEncoding();
\r
224 if (value != null && !value.trim().isEmpty()) {
\r
225 item.put(BlobJAXBSchema.encoding, value);
\r
227 value = Long.toString(blob.getLength());
\r
228 if (value != null && !value.trim().isEmpty()) {
\r
229 item.put(BlobJAXBSchema.length, value);
\r
231 value = blob.getMimeType();
\r
232 if (value != null && !value.trim().isEmpty()) {
\r
233 item.put(BlobJAXBSchema.mimeType, value);
\r
235 value = blob.getFilename();
\r
236 if (value != null && !value.trim().isEmpty()) {
\r
237 item.put(BlobJAXBSchema.name, value);
\r
239 value = getDerivativeUri(uri, blob.getFilename());
\r
240 if (value != null && !value.trim().isEmpty()) {
\r
241 item.put(BlobJAXBSchema.uri, value);
\r
247 static public CommonList getBlobDerivatives(RepositoryInstance repoSession,
\r
248 String repositoryId, List<ListResultField> resultsFields, String uri)
\r
250 CommonList commonList = new CommonList();
\r
251 int nFields = resultsFields.size() + 2;
\r
252 String fields[] = new String[nFields];// FIXME: REM - Patrick needs to fix this hack. It is a "common list" issue
\r
253 fields[0] = "csid";
\r
255 for (int i = 2; i < nFields; i++) {
\r
256 ListResultField field = resultsFields.get(i - 2);
\r
257 fields[i] = field.getElement();
\r
259 commonList.setFieldsReturned(fields);
\r
261 IdRef documentRef = new IdRef(repositoryId);
\r
262 DocumentModel documentModel = repoSession.getDocument(documentRef);
\r
263 DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel
\r
264 .getAdapter(BlobHolder.class);
\r
265 List<Blob> docBlobs = docBlobHolder.getBlobs();
\r
266 // List<BlobListItem> blobListItems = result.getBlobListItem();
\r
267 HashMap<String, Object> item = null;
\r
268 for (Blob blob : docBlobs) {
\r
269 item = createBlobListItem(blob, uri);
\r
270 commonList.addItem(item);
\r
277 * [dublincore, uid, picture, iptc, common, image_metadata]
\r
279 static private Map<String, Object> getMetadata(Blob nuxeoBlob)
\r
281 ImagingService service = Framework.getService(ImagingService.class);
\r
282 Map<String, Object> metadataMap = service.getImageMetadata(nuxeoBlob);
\r
283 return metadataMap;
\r
286 private static String[] imageTypes = {"jpeg", "bmp", "gif", "png", "tiff", "octet-stream"};
\r
287 static private boolean isImageMedia(Blob nuxeoBlob) {
\r
288 boolean result = false;
\r
290 String mimeType = nuxeoBlob.getMimeType().toLowerCase().trim();
\r
291 String[] parts = mimeType.split("/"); // split strings like "application/xml" into an array of two strings
\r
292 if (parts.length == 2) {
\r
293 for (String type : imageTypes) {
\r
294 if (parts[1].equalsIgnoreCase(type)) {
\r
304 static private MeasuredPartGroupList getDimensions(
\r
305 DocumentModel documentModel, Blob nuxeoBlob) {
\r
306 MeasuredPartGroupList result = null;
\r
308 if (isImageMedia(nuxeoBlob) == true) try {
\r
309 ImagingService service = Framework.getService(ImagingService.class);
\r
310 ImageInfo imageInfo = service.getImageInfo(nuxeoBlob);
\r
311 Map<String, Object> metadataMap = getMetadata(nuxeoBlob);
\r
313 if (imageInfo != null) {
\r
315 // Create a timestamp to add to all the image's dimensions
\r
317 String valueDate = GregorianCalendarDateTimeUtils
\r
320 result = new MeasuredPartGroupList();
\r
321 List<MeasuredPartGroup> measuredPartGroupList =
\r
322 (result).getMeasuredPartGroup();
\r
324 // Create a new measured part for the "image"
\r
326 MeasuredPartGroup mpGroup = new MeasuredPartGroup();
\r
327 mpGroup.setMeasuredPart(PART_IMAGE);
\r
328 mpGroup.setDimensionSummary(PART_SUMMARY);
\r
329 mpGroup.setDimensionSubGroupList(new DimensionSubGroupList());
\r
330 List<DimensionSubGroup> dimensionSubGroupList = mpGroup.getDimensionSubGroupList()
\r
331 .getDimensionSubGroup();
\r
336 DimensionSubGroup widthDimension = new DimensionSubGroup();
\r
337 widthDimension.setDimension(WIDTH);
\r
338 widthDimension.setMeasurementUnit(UNIT_PIXELS);
\r
339 widthDimension.setValue(intToBigDecimal(imageInfo.getWidth()));
\r
340 widthDimension.setValueDate(valueDate);
\r
341 dimensionSubGroupList.add(widthDimension);
\r
345 DimensionSubGroup heightDimension = new DimensionSubGroup();
\r
346 heightDimension.setDimension(HEIGHT);
\r
347 heightDimension.setMeasurementUnit(UNIT_PIXELS);
\r
349 .setValue(intToBigDecimal(imageInfo.getHeight()));
\r
350 heightDimension.setValueDate(valueDate);
\r
351 dimensionSubGroupList.add(heightDimension);
\r
355 DimensionSubGroup depthDimension = new DimensionSubGroup();
\r
356 depthDimension.setDimension(DEPTH);
\r
357 depthDimension.setMeasurementUnit(UNIT_BITS);
\r
358 depthDimension.setValue(intToBigDecimal(imageInfo.getDepth()));
\r
359 depthDimension.setValueDate(valueDate);
\r
360 dimensionSubGroupList.add(depthDimension);
\r
362 // Now set out result
\r
364 measuredPartGroupList.add(mpGroup);
\r
366 if (logger.isWarnEnabled() == true) {
\r
367 logger.warn("Could not synthesize a dimension list of the blob: "
\r
368 + documentModel.getName());
\r
371 } catch (Exception e) {
\r
372 logger.warn("Could not extract image information for blob: "
\r
373 + documentModel.getName(), e);
\r
379 // FIXME: Add error checking here, as none of these calls return an
\r
381 static private BigDecimal intToBigDecimal(int i) {
\r
382 BigInteger bigint = BigInteger.valueOf(i);
\r
383 BigDecimal bigdec = new BigDecimal(bigint);
\r
387 static private BlobsCommon createBlobsCommon(DocumentModel documentModel,
\r
389 BlobsCommon result = new BlobsCommon();
\r
391 if (documentModel != null) {
\r
392 result.setMimeType(nuxeoBlob.getMimeType());
\r
393 result.setName(nuxeoBlob.getFilename());
\r
394 result.setLength(Long.toString(nuxeoBlob.getLength()));
\r
395 result.setRepositoryId(documentModel.getId());
\r
396 MeasuredPartGroupList measuredPartGroupList = getDimensions(
\r
397 documentModel, nuxeoBlob);
\r
398 if (measuredPartGroupList != null) {
\r
399 result.setMeasuredPartGroupList(measuredPartGroupList);
\r
407 * This is a prototype method that is not currently used as of 1/1/2012. However,
\r
408 * it may be useful now that we've transitioned to using an embedded Nuxeo server.
\r
410 static private File getBlobFile(RepositoryInstance ri,
\r
411 DocumentModel documentModel, Blob blob) {
\r
412 DefaultBinaryManager binaryManager = null;
\r
413 RepositoryDescriptor descriptor = null;
\r
417 RepositoryService repositoryService1 = (RepositoryService) Framework
\r
418 .getRuntime().getComponent(RepositoryService.NAME);
\r
420 String repositoryName = documentModel.getRepositoryName();
\r
421 RepositoryManager repositoryManager = repositoryService1
\r
422 .getRepositoryManager();
\r
423 descriptor = repositoryManager.getDescriptor(repositoryName);
\r
425 // Keep this code around for future work/enhancements
\r
426 // binaryManager = new DefaultBinaryManager();
\r
428 // File storageDir = binaryManager.getStorageDir();
\r
429 // // SQLBlob blob = (SQLBlob)
\r
430 // // doc.getPropertyValue("schema:blobField");
\r
431 // File file = binaryManager.getFileForDigest(blob.getDigest(), false);
\r
433 } catch (Exception e) {
\r
434 e.printStackTrace();
\r
437 // Keep this code around for future work/enhancements
\r
439 // binaryManager.initialize(SQLRepository.getDescriptor(descriptor));
\r
440 // } catch (IOException e) {
\r
441 // // TODO Auto-generated catch block
\r
442 // e.printStackTrace();
\r
443 // } catch (Exception e) {
\r
444 // // TODO Auto-generated catch block
\r
445 // e.printStackTrace();
\r
448 // Keep this code around for future work/enhancements
\r
449 // File storageDir = binaryManager.getStorageDir();
\r
450 // SQLBlob blob = (SQLBlob)
\r
451 // documentModel.getPropertyValue("schema:blobField");
\r
452 // File file = binaryManager.getFileForDigest(blob.getDigest(), false);
\r
458 * Returns a schema, given the name of a schema. Possibly usefule in the future
\r
460 * @param schemaName
\r
462 * @return a schema.
\r
464 private static Schema getSchemaFromName(String schemaName) {
\r
465 SchemaManager schemaManager = null;
\r
467 schemaManager = Framework.getService(SchemaManager.class);
\r
468 } catch (Exception e) {
\r
469 // TODO Auto-generated catch block
\r
470 e.printStackTrace();
\r
472 return schemaManager != null ? schemaManager.getSchema(schemaName)
\r
477 * Gets the blob. Not in use now, but might be useful in the future.
\r
479 * @param nuxeoSession
\r
480 * the nuxeo session
\r
485 static private Blob getBlob(RepositoryInstance nuxeoSession, String id) {
\r
486 Blob result = null;
\r
489 Repository repository = nuxeoSession.getRepository();
\r
490 // binaryManager.initialize(new RepositoryDescriptor());
\r
491 // binaryManager.getBinary("a4cac052ae0281979f2dcf5ab2e61a6c");
\r
492 // DocumentResolver.resolveReference(nuxeoSession, documentRef);
\r
493 // binaryManager = repository.getBinaryManager();
\r
494 // documentModel.getr
\r
495 } catch (Exception x) {
\r
496 x.printStackTrace();
\r
503 * Gets the type service. Not in use, but please keep for future reference
\r
505 * @return the type service
\r
506 * @throws ClientException
\r
507 * the client exception
\r
509 private static TypeManager getTypeService() throws ClientException {
\r
510 TypeManager typeService = null;
\r
512 typeService = Framework.getService(TypeManager.class);
\r
513 } catch (Exception e) {
\r
514 throw new ClientException(e);
\r
516 return typeService;
\r
524 * @return the bytes
\r
526 private static byte[] getBytes(InputStream fis) {
\r
527 ByteArrayOutputStream bos = new ByteArrayOutputStream();
\r
528 byte[] buf = new byte[128 * 1024];
\r
530 for (int readNum; (readNum = fis.read(buf)) != -1;) {
\r
531 bos.write(buf, 0, readNum);
\r
532 // no doubt here is 0
\r
534 * Writes len bytes from the specified byte array starting at
\r
535 * offset off to this byte array output stream.
\r
537 System.out.println("read " + readNum + " bytes,");
\r
539 } catch (IOException ex) {
\r
540 logger.error(ex.getMessage(), ex);
\r
542 byte[] bytes = bos.toByteArray();
\r
543 // bytes is the ByteArray we need
\r
548 * Creates the serializable blob. We may need this code, do not remove.
\r
550 * @param fileInputStream
\r
551 * the file input stream
\r
558 private static Blob createSerializableBlob(InputStream fileInputStream,
\r
559 String filename, String mimeType) {
\r
562 // persisting the blob makes it possible to read the binary content
\r
563 // of the request stream several times (mimetype sniffing, digest
\r
564 // computation, core binary storage)
\r
565 byte[] bytes = getBytes(fileInputStream);
\r
566 blob = new ByteArrayBlob(bytes);
\r
568 if (filename != null) {
\r
569 filename = getCleanFileName(filename);
\r
571 blob.setFilename(filename);
\r
572 // mimetype detection
\r
573 MimetypeRegistry mimeService = Framework
\r
574 .getService(MimetypeRegistry.class);
\r
575 String detectedMimeType = mimeService
\r
576 .getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
\r
578 if (detectedMimeType == null) {
\r
579 if (mimeType != null) {
\r
580 detectedMimeType = mimeType;
\r
583 detectedMimeType = "application/octet-stream";
\r
586 blob.setMimeType(detectedMimeType);
\r
587 } catch (MimetypeDetectionException e) {
\r
588 logger.error(String.format("could not fetch mimetype for file %s",
\r
590 } catch (Exception e) {
\r
591 logger.error("", e);
\r
597 * Creates a serializable blob from a stream, with filename and mimetype
\r
601 * Creates an in-memory blob if data is under 64K, otherwise constructs a
\r
602 * serializable FileBlob which stores data in a temporary file on the hard
\r
607 * the input stream holding data
\r
609 * the file name. Will be set on the blob and will used for
\r
610 * mimetype detection.
\r
612 * the detected mimetype at upload. Can be null. Will be verified
\r
613 * by the mimetype service.
\r
616 private static Blob createStreamingBlob(File file, String filename,
\r
620 // persisting the blob makes it possible to read the binary content
\r
621 // of the request stream several times (mimetype sniffing, digest
\r
622 // computation, core binary storage)
\r
623 blob = StreamingBlob.createFromFile(file, mimeType).persist();
\r
625 if (filename != null) {
\r
626 filename = getCleanFileName(filename);
\r
628 blob.setFilename(filename);
\r
629 // mimetype detection
\r
630 MimetypeRegistry mimeService = Framework
\r
631 .getService(MimetypeRegistry.class);
\r
632 String detectedMimeType = mimeService
\r
633 .getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
\r
635 if (detectedMimeType == null) {
\r
636 if (mimeType != null) {
\r
637 detectedMimeType = mimeType;
\r
640 detectedMimeType = "application/octet-stream";
\r
643 blob.setMimeType(detectedMimeType);
\r
644 } catch (MimetypeDetectionException e) {
\r
645 logger.error(String.format("could not fetch mimetype for file %s",
\r
647 } catch (IOException e) {
\r
648 logger.error("", e);
\r
649 } catch (Exception e) {
\r
650 logger.error("", e);
\r
655 private static Blob createNuxeoFileBasedBlob(File file) {
\r
656 Blob result = null;
\r
658 result = new FileBlob(file);
\r
663 * Returns a clean filename, stripping upload path on client side.
\r
670 * @return the clean file name
\r
672 private static String getCleanFileName(String filename) {
\r
674 int lastWinSeparator = filename.lastIndexOf('\\');
\r
675 int lastUnixSeparator = filename.lastIndexOf('/');
\r
676 int lastSeparator = Math.max(lastWinSeparator, lastUnixSeparator);
\r
677 if (lastSeparator != -1) {
\r
678 res = filename.substring(lastSeparator + 1, filename.length());
\r
686 * Gets Nuxeo's file manager service.
\r
688 * @return the file manager service
\r
689 * @throws ClientException
\r
690 * the client exception
\r
692 private static FileManager getFileManagerService() throws ClientException {
\r
693 FileManager result = null;
\r
695 result = Framework.getService(FileManager.class);
\r
696 } catch (Exception e) {
\r
697 String msg = "Unable to get Nuxeo's FileManager service.";
\r
698 logger.error(msg, e);
\r
699 throw new ClientException("msg", e);
\r
705 * Creates the picture.
\r
709 * @param repoSession
\r
713 * @return the string
\r
714 * @throws Exception
\r
716 public static BlobsCommon createBlobInRepository(ServiceContext ctx,
\r
717 RepositoryInstance repoSession, BlobInput blobInput) throws Exception {
\r
718 BlobsCommon result = null;
\r
721 File blobFile = blobInput.getBlobFile();
\r
722 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
\r
723 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
\r
724 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
\r
726 if (logger.isTraceEnabled()) {
\r
727 for (String facet : wspaceDoc.getFacets()) {
\r
728 logger.trace("Facet: " + facet);
\r
730 for (String docType : wspaceDoc.getDocumentType().getChildrenTypes()) {
\r
731 logger.trace("Child type: " + docType);
\r
735 result = createBlobInRepository(repoSession, wspaceDoc, blobFile, null /*mime type*/);
\r
736 } catch (Exception e) {
\r
737 logger.error("Could not create image blob", e);
\r
745 * Creates the image blob.
\r
747 * @param nuxeoSession
\r
748 * the nuxeo session
\r
749 * @param blobLocation
\r
750 * the blob location
\r
757 * @return the string
\r
759 static public BlobsCommon createBlobInRepository(RepositoryInstance nuxeoSession,
\r
760 DocumentModel blobLocation,
\r
761 // InputStream file,
\r
762 File file, String mimeType) {
\r
763 BlobsCommon result = null;
\r
766 // Blob fileBlob = createStreamingBlob(blobFile, blobFile.getName(),
\r
768 Blob fileBlob = createNuxeoFileBasedBlob(file);
\r
769 String digestAlgorithm = getFileManagerService()
\r
770 .getDigestAlgorithm(); // Only call this because we seem to need some way of initializing Nuxeo's FileManager with a call.
\r
772 logger.debug("Start --> Starting call to Nuxeo to create the blob document."); // For example, see Nuxeo's DefaultPictureAdapter class for details
\r
773 DocumentModel documentModel = getFileManagerService()
\r
774 .createDocumentFromBlob(nuxeoSession, fileBlob,
\r
775 blobLocation.getPathAsString(), true,
\r
777 logger.debug("Stop --> Finished calling Nuxeo to create the blob document.");
\r
779 result = createBlobsCommon(documentModel, fileBlob); // Now create our metadata resource document
\r
780 } catch (Exception e) {
\r
782 logger.error("Could not create new Nuxeo blob document.", e); //FIXME: REM - This should probably be re-throwing the exception?
\r
789 // * This is an alternate approach to getting information about an image
\r
790 // * and its corresponding derivatives.
\r
792 // // MultiviewPictureAdapter multiviewPictureAdapter =
\r
793 // documentModel.getAdapter(MultiviewPictureAdapter.class);
\r
794 // MultiviewPictureAdapterFactory multiviewPictureAdapterFactory = new
\r
795 // MultiviewPictureAdapterFactory();
\r
796 // MultiviewPictureAdapter multiviewPictureAdapter =
\r
797 // (MultiviewPictureAdapter)multiviewPictureAdapterFactory.getAdapter(documentModel,
\r
799 // if (multiviewPictureAdapter != null) {
\r
800 // PictureView[] pictureViewArray = multiviewPictureAdapter.getViews();
\r
801 // for (PictureView pictureView : pictureViewArray) {
\r
802 // if (logger.isDebugEnabled() == true) {
\r
803 // logger.debug("-------------------------------------");
\r
804 // logger.debug(toStringPictureView(pictureView));
\r
812 * @param repoSession
\r
814 * @param repositoryId
\r
815 * the repository id
\r
816 * @param derivativeTerm
\r
817 * the derivative term
\r
818 * @return the image
\r
820 static public BlobOutput getBlobOutput(ServiceContext ctx,
\r
821 RepositoryInstance repoSession,
\r
822 String repositoryId,
\r
823 String derivativeTerm,
\r
824 Boolean getContentFlag,
\r
825 StringBuffer outMimeType) {
\r
826 BlobOutput result = new BlobOutput();
\r
827 boolean isNonImageDerivative = false;
\r
829 if (repositoryId != null && repositoryId.isEmpty() == false)
\r
831 IdRef documentRef = new IdRef(repositoryId);
\r
832 DocumentModel documentModel = repoSession.getDocument(documentRef);
\r
834 Blob docBlob = null;
\r
835 DocumentBlobHolder docBlobHolder = (DocumentBlobHolder) documentModel
\r
836 .getAdapter(BlobHolder.class);
\r
837 if (docBlobHolder instanceof PictureBlobHolder) {
\r
838 // if it is a PictureDocument then it has these
\r
839 // Nuxeo schemas: [dublincore, uid, picture, iptc, common, image_metadata]
\r
841 // Need to add the "MultiviewPictureAdapter" support here to
\r
842 // get the view data, see above.
\r
844 PictureBlobHolder pictureBlobHolder = (PictureBlobHolder) docBlobHolder;
\r
845 if (derivativeTerm != null) {
\r
846 docBlob = pictureBlobHolder.getBlob(derivativeTerm);
\r
847 // Nuxeo derivatives are all JPEG
\r
848 outMimeType.append(MIME_JPEG);
\r
850 docBlob = pictureBlobHolder.getBlob();
\r
853 docBlob = docBlobHolder.getBlob();
\r
854 if (derivativeTerm != null) { // If its a derivative request on a non-image blob, then return just a document image thumnail
\r
855 isNonImageDerivative = true;
\r
860 // Create the result instance that will contain the blob metadata
\r
861 // and an InputStream with the bits if the 'getContentFlag' is
\r
864 BlobsCommon blobsCommon = createBlobsCommon(documentModel, docBlob);
\r
865 result.setBlobsCommon(blobsCommon);
\r
866 if (getContentFlag == true) {
\r
867 InputStream remoteStream = null;
\r
868 if (isNonImageDerivative == false) {
\r
869 remoteStream = docBlob.getStream();
\r
871 remoteStream = NuxeoImageUtils.class.getClassLoader() // for now, non-image derivatives are just placeholder document images
\r
872 .getResourceAsStream("documentImage.jpg");
\r
873 outMimeType.append(MIME_JPEG);
\r
875 BufferedInputStream bufferedInputStream = new BufferedInputStream(
\r
876 remoteStream); // FIXME: REM - To improve performance, try
\r
877 // BufferedInputStream(InputStream in, int size)?
\r
878 result.setBlobInputStream(bufferedInputStream);
\r
880 } catch (Exception e) {
\r
881 if (logger.isErrorEnabled() == true) {
\r
882 logger.error(e.getMessage(), e);
\r
893 * Notes and code snippets about Nuxeo's support for binaries and image
\r
900 * MultiviewPictureAdapter org.nuxeo.ecm.platform.picture.api.adapters
\r
901 * PictureResourceAdapter pictureResourceAdapter = (PictureResourceAdapter)
\r
902 * documentModel.getAdapter(PictureResourceAdapter.class); String thumbnailPath
\r
903 * = pictureResourceAdapter.getViewXPath("Thumbnail");
\r
905 * Map<String,Serializable> blobHolderProps = docBlobHolder.getProperties();
\r
906 * String filePath = docBlobHolder.getFilePath(); List<Blob> docBlobs =
\r
907 * docBlobHolder.getBlobs();
\r
909 * stream = new FileInputStream(fileUploadHolder.getTempFile());
\r
911 * public String addFile(InputStream fileUpload, String fileName) fileName =
\r
912 * FileUtils.getCleanFileName(fileName); DocumentModel currentDocument =
\r
913 * navigationContext.getCurrentDocument(); String path =
\r
914 * currentDocument.getPathAsString(); Blob blob =
\r
915 * FileUtils.createSerializableBlob(fileUpload, fileName, null);
\r
917 * DocumentModel createdDoc = getFileManagerService().createDocumentFromBlob(
\r
918 * documentManager, blob, path, true, fileName);
\r
919 * eventManager.raiseEventsOnDocumentSelected(createdDoc);
\r
921 * protected FileManager fileManager;
\r
923 * protected FileManager getFileManagerService() throws ClientException { if
\r
924 * (fileManager == null) { try { fileManager =
\r
925 * Framework.getService(FileManager.class); } catch (Exception e) {
\r
926 * log.error("Unable to get FileManager service ", e); throw new
\r
927 * ClientException("Unable to get FileManager service ", e); } } return
\r
932 * RepositoryService repositoryService = (RepositoryService)
\r
933 * Framework.getRuntime().getComponent( RepositoryService.NAME);
\r
934 * RepositoryManager repositoryManager =
\r
935 * repositoryService.getRepositoryManager(); RepositoryDescriptor descriptor =
\r
936 * repositoryManager.getDescriptor(repositoryName); DefaultBinaryManager
\r
937 * binaryManager = new DefaultBinaryManager(
\r
938 * SQLRepository.getDescriptor(descriptor)));
\r
940 * File storageDir = binaryManager.getStorageDir(); SQLBlob blob = (SQLBlob)
\r
941 * doc.getPropertyValue("schema:blobField"); File file =
\r
942 * binaryManager.getFileForDigest( blob.getBinary().getDigest(), false);
\r
946 * RepositoryInstance.getStreamURI()
\r
948 * String getStreamURI(String blobPropertyId) throws ClientException
\r
950 * Returns an URI identifying the stream given the blob property id. This method
\r
951 * should be used by a client to download the data of a blob property.
\r
953 * The blob is fetched from the repository and the blob stream is registered
\r
954 * against the streaming service so the stream will be available remotely
\r
955 * through stream service API.
\r
957 * After the client has called this method, it will be able to download the
\r
958 * stream using streaming server API.
\r
960 * Returns: an URI identifying the remote stream Throws: ClientException
\r
964 * A blob contains usually large data.
\r
966 * Document fields holding Blob data are by default fetched in a lazy manner.
\r
968 * A Blob object hides the data source and it also describes data properties
\r
969 * like the encoding or mime-type.
\r
971 * The encoding is used to decode Unicode text content that was stored in an
\r
972 * encoded form. If not encoding is specified, the default java encoding is
\r
973 * used. The encoding is ignored for binary content.
\r
975 * When retrieving the content from a document, it will be returned as source
\r
976 * content instead of returning the content bytes.
\r
978 * The same is true when setting the content for a document: you set a content
\r
979 * source and not directly the content bytes. Ex:
\r
981 * File file = new File("/tmp/index.html"); FileBlob fb = new FileBlob(file);
\r
982 * fb.setMimeType("text/html"); fb.setEncoding("UTF-8"); // this specifies that
\r
983 * content bytes will be stored as UTF-8 document.setProperty("file", "content",
\r
987 * Then you may want to retrieve the content as follow:
\r
989 * Blob blob = document.getProperty("file:content"); htmlDoc = blob.getString();
\r
990 * // the content is decoded from UTF-8 into a java string
\r