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;
024import java.util.Map;
025
026import org.codehaus.jackson.JsonGenerator;
027import org.nuxeo.ecm.core.api.DocumentModel;
028import org.nuxeo.ecm.core.io.registry.reflect.Setup;
029
030/**
031 * Enrich {@link DocumentModel} Json.
032 * <p>
033 * Add custom key/value information as json attachment.
034 * </p>
035 * <p>
036 * Enable if parameter enrichers.document=contextualParameters.
037 * </p>
038 * <p>
039 * Format is:
040 *
041 * <pre>
042 * {@code
043 * {
044 *   "entity-type":"document",
045 *   ...
046 *   "contextParameters": {
047 *     "KEY": "VALUE" <- key/value pairs come from context parameter "contextualParameters" - a Map<String, String> is expected.
048 *   }
049 * }
050 * </pre>
051 *
052 * </p>
053 *
054 * @since 7.2
055 */
056@Setup(mode = SINGLETON, priority = REFERENCE)
057public class ContextualParametersJsonEnricher extends AbstractJsonEnricher<DocumentModel> {
058
059    public static final String NAME = "contextualParameters";
060
061    public ContextualParametersJsonEnricher() {
062        super(NAME);
063    }
064
065    @Override
066    public void write(JsonGenerator jg, DocumentModel enriched) throws IOException {
067        Map<String, String> contextParameters = ctx.getParameter(NAME);
068        if (contextParameters != null && !contextParameters.isEmpty()) {
069            for (Map.Entry<String, String> parameter : contextParameters.entrySet()) {
070                jg.writeStringField(parameter.getKey(), parameter.getValue());
071            }
072        }
073    }
074
075}