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.core.io.marshallers.json.enrichers;
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.api.DocumentModelList;
028import org.nuxeo.ecm.core.io.marshallers.json.document.DocumentModelListJsonWriter;
029import org.nuxeo.ecm.core.io.registry.context.RenderingContext.SessionWrapper;
030import org.nuxeo.ecm.core.io.registry.reflect.Setup;
031
032/**
033 * Enrich {@link DocumentModel} Json.
034 * <p>
035 * Add document children (list of document) as json attachment.
036 * </p>
037 * <p>
038 * Enable if parameter enrichers.document=children is present.
039 * </p>
040 * <p>
041 * Format is:
042 *
043 * <pre>
044 * {@code
045 * {
046 *   "entity-type":"document",
047 *   ...
048 *   "contextParameters": {
049 *     "children": { see {@link DocumentModelListJsonWriter} for format }
050 *   }
051 * }
052 * </pre>
053 *
054 * </p>
055 *
056 * @since 7.2
057 */
058@Setup(mode = SINGLETON, priority = REFERENCE)
059public class ChildrenJsonEnricher extends AbstractJsonEnricher<DocumentModel> {
060
061    public static final String NAME = "children";
062
063    public ChildrenJsonEnricher() {
064        super(NAME);
065    }
066
067    @Override
068    public void write(JsonGenerator jg, DocumentModel document) throws IOException {
069        DocumentModelList children = null;
070        try (SessionWrapper wrapper = ctx.getSession(document)) {
071            children = wrapper.getSession().getChildren(document.getRef());
072        }
073        jg.writeFieldName(NAME);
074        writeEntity(children, jg);
075    }
076
077}