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.document;
019
020import static org.nuxeo.ecm.automation.core.util.PaginableDocumentModelList.CODEC_PARAMETER_NAME;
021import static org.nuxeo.ecm.core.io.registry.reflect.Instantiations.SINGLETON;
022import static org.nuxeo.ecm.core.io.registry.reflect.Priorities.REFERENCE;
023
024import java.io.Closeable;
025import java.io.IOException;
026import java.util.List;
027
028import org.codehaus.jackson.JsonGenerator;
029import org.nuxeo.ecm.automation.core.util.PaginableDocumentModelList;
030import org.nuxeo.ecm.core.api.DocumentModel;
031import org.nuxeo.ecm.core.io.marshallers.json.DefaultListJsonWriter;
032import org.nuxeo.ecm.core.io.registry.reflect.Setup;
033
034/**
035 * see {@link DefaultListJsonWriter}
036 *
037 * @since 7.2
038 */
039@Setup(mode = SINGLETON, priority = REFERENCE)
040public class DocumentModelListJsonWriter extends DefaultListJsonWriter<DocumentModel> {
041
042    public static final String ENTITY_DOCUMENT_LIST = "documents";
043
044    public DocumentModelListJsonWriter() {
045        super(ENTITY_DOCUMENT_LIST, DocumentModel.class);
046    }
047
048    @Override
049    public void write(List<DocumentModel> docs, JsonGenerator jg) throws IOException {
050        if (docs instanceof PaginableDocumentModelList) {
051            PaginableDocumentModelList paginable = (PaginableDocumentModelList) docs;
052            String codecName = paginable.getDocumentLinkBuilder();
053            try (Closeable resource = ctx.wrap().with(CODEC_PARAMETER_NAME, codecName).open()) {
054                super.write(docs, jg);
055            }
056        } else {
057            super.write(docs, jg);
058        }
059    }
060
061}