001/*
002 * (C) Copyright 2015 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nicolas Chapurlat <nchapurlat@nuxeo.com>
016 */
017
018package org.nuxeo.ecm.platform.preview.io;
019
020import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON;
021import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE;
022
023import java.io.IOException;
024
025import org.codehaus.jackson.JsonGenerator;
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.io.marshallers.json.enrichers.AbstractJsonEnricher;
028import org.nuxeo.ecm.core.io.registry.reflect.Setup;
029import org.nuxeo.ecm.platform.preview.helper.PreviewHelper;
030
031/**
032 * Enrich {@link DocumentModel} Json.
033 * <p>
034 * Add {@link DocumentModel}'s preview url as json attachment.
035 * </p>
036 * <p>
037 * Enable if parameter enrichers.document=preview is present.
038 * </p>
039 * <p>
040 * Format is:
041 *
042 * <pre>
043 * {@code
044 * {
045 *   "entity-type":"document",
046 *   ...
047 *   "contextParameters": {
048 *     "preview": {
049 *       "url": "PREVIEW_URL"
050 *     },
051 *   }
052 * }
053 * </pre>
054 *
055 * </p>
056 *
057 * @since 7.2
058 */
059@Setup(mode = SINGLETON, priority = REFERENCE)
060public class PreviewJsonEnricher extends AbstractJsonEnricher<DocumentModel> {
061
062    public static final String NAME = "preview";
063
064    private static final String PREVIEW_URL_LABEL = "url";
065
066    public PreviewJsonEnricher() {
067        super(NAME);
068    }
069
070    @Override
071    public void write(JsonGenerator jg, DocumentModel document) throws IOException {
072        String relativeUrl = PreviewHelper.getPreviewURL(document);
073        jg.writeFieldName(NAME);
074        jg.writeStartObject();
075        if (relativeUrl != null && !relativeUrl.isEmpty()) {
076            String url = ctx.getBaseUrl() + PreviewHelper.getPreviewURL(document);
077            jg.writeStringField(PREVIEW_URL_LABEL, url);
078        } else {
079            jg.writeNullField(PREVIEW_URL_LABEL);
080        }
081        jg.writeEndObject();
082    }
083
084}