001/* 002 * (C) Copyright 2020 Nuxeo (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nelson Silva <nsilva@nuxeo.com> 018 */ 019 020package org.nuxeo.ecm.platform.preview.io; 021 022import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON; 023import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE; 024 025import java.io.IOException; 026import java.net.URI; 027 028import org.nuxeo.ecm.core.api.Blob; 029import org.nuxeo.ecm.core.api.model.impl.primitives.BlobProperty; 030import org.nuxeo.ecm.core.blob.BlobManager; 031import org.nuxeo.ecm.core.blob.ManagedBlob; 032import org.nuxeo.ecm.core.io.marshallers.json.enrichers.AbstractJsonEnricher; 033import org.nuxeo.ecm.core.io.registry.reflect.Setup; 034import org.nuxeo.runtime.api.Framework; 035 036import com.fasterxml.jackson.core.JsonGenerator; 037 038/** 039 * Enriches {@link Blob} json with embed preview link when available. 040 * <p> 041 * Enabled when parameter enrichers-blob=preview is present. 042 * <p> 043 * Blob format is: 044 * 045 * <pre> 046 * {@code 047 * { 048 * "name": "...", 049 * "mime-type": "...", 050 * ... 051 * "preview": "<url>" 052 * } 053 * } 054 * </pre> 055 * 056 * @since 11.2 057 */ 058@Setup(mode = SINGLETON, priority = REFERENCE) 059public class BlobPreviewJsonEnricher extends AbstractJsonEnricher<BlobProperty> { 060 061 public static final String NAME = "preview"; 062 063 public BlobPreviewJsonEnricher() { 064 super(NAME); 065 } 066 067 @Override 068 public void write(JsonGenerator jg, BlobProperty blobProperty) throws IOException { 069 Blob blob = (Blob) blobProperty.getValue(); 070 if (!(blob instanceof ManagedBlob)) { 071 return; 072 } 073 074 // if it's a managed blob try to use the embed uri for preview 075 BlobManager blobManager = Framework.getService(BlobManager.class); 076 URI uri = blobManager.getURI(blob, BlobManager.UsageHint.EMBED, null); 077 if (uri != null) { 078 jg.writeStringField(NAME, uri.toASCIIString()); 079 } 080 } 081 082}