001/*
002 * (C) Copyright 2018 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 *     Guillaume Renard <grenard@nuxeo.com>
018 */
019package org.nuxeo.ecm.core.io.marshallers.json.enrichers;
020
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.IOException;
025
026import org.nuxeo.ecm.core.api.DocumentModel;
027import org.nuxeo.ecm.core.api.trash.TrashService;
028import org.nuxeo.ecm.core.io.registry.context.RenderingContext.SessionWrapper;
029import org.nuxeo.ecm.core.io.registry.reflect.Setup;
030import org.nuxeo.runtime.api.Framework;
031
032import com.fasterxml.jackson.core.JsonGenerator;
033
034/**
035 * Gets the closest document's ancestor.
036 * <p>
037 * This is used to find what safe document to redirect to when deleting some.
038 *
039 * @since 10.1
040 */
041@Setup(mode = SINGLETON, priority = REFERENCE)
042public class FirstAccessibleAncestorJsonEnricher extends AbstractJsonEnricher<DocumentModel> {
043
044    public static final String NAME = "firstAccessibleAncestor";
045
046    public FirstAccessibleAncestorJsonEnricher() {
047        super(NAME);
048    }
049
050    @Override
051    public void write(JsonGenerator jg, DocumentModel document) throws IOException {
052        TrashService trashService = Framework.getService(TrashService.class);
053        try (SessionWrapper wrapper = ctx.getSession(document)) {
054            DocumentModel above = trashService.getAboveDocument(document, wrapper.getSession().getPrincipal());
055            if (above != null) {
056                writeEntityField(NAME, above, jg);
057            }
058        }
059    }
060
061}