001/*
002 * (C) Copyright 2013 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 *     dmetzler
016 */
017package org.nuxeo.ecm.automation.jaxrs.io;
018
019import java.io.IOException;
020import java.lang.annotation.Annotation;
021import java.lang.reflect.ParameterizedType;
022import java.lang.reflect.Type;
023import java.util.List;
024
025import javax.ws.rs.core.MediaType;
026
027import org.codehaus.jackson.JsonGenerator;
028import org.nuxeo.ecm.automation.core.util.Paginable;
029
030/**
031 * Abstract class that knows how to serialize List of nuxeo entities. The implementing classes should only implement
032 * {@link #getEntityType()} and {@link #writeItem(JsonGenerator, Object)}
033 *
034 * @since 5.7.3
035 */
036public abstract class EntityListWriter<T> extends EntityWriter<List<T>> {
037
038    /**
039     * Returns the entity-type value of the list (ie: users, groups....)
040     */
041    protected abstract String getEntityType();
042
043    /**
044     * Writes the item in a JsonGenerator.
045     */
046    protected abstract void writeItem(JsonGenerator jg, T item) throws IOException;
047
048    @Override
049    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
050        if (!List.class.isAssignableFrom(type)) {
051            return false;
052        }
053
054        // Verify the generic argument type
055        if (genericType instanceof ParameterizedType) {
056            ParameterizedType paramType = (ParameterizedType) genericType;
057            Type actualTypeArguments = paramType.getActualTypeArguments()[0];
058            if (type == null) {
059                throw new RuntimeException("Invalid class parameter type.");
060            }
061            return ((Class<?>) actualTypeArguments).isAssignableFrom(getItemClass());
062
063        }
064        return false;
065    }
066
067    private Class<?> getItemClass() {
068        return (Class<?>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
069    }
070
071    @Override
072    protected void writeEntityBody(JsonGenerator jg, List<T> list) throws IOException {
073        writePaginableHeader(jg, list);
074        writeHeader(jg, list);
075        jg.writeArrayFieldStart("entries");
076        for (T item : list) {
077            writeItem(jg, item);
078        }
079        jg.writeEndArray();
080    }
081
082    protected void writePaginableHeader(JsonGenerator jg, List<T> list) throws IOException {
083        if (list instanceof Paginable) {
084            @SuppressWarnings("rawtypes")
085            Paginable paginable = (Paginable) list;
086            jg.writeBooleanField("isPaginable", true);
087            jg.writeNumberField("resultsCount", paginable.getResultsCount());
088            jg.writeNumberField("pageSize", paginable.getPageSize());
089            jg.writeNumberField("maxPageSize", paginable.getMaxPageSize());
090            jg.writeNumberField("currentPageSize", paginable.getCurrentPageSize());
091            jg.writeNumberField("currentPageIndex", paginable.getCurrentPageIndex());
092            jg.writeNumberField("numberOfPages", paginable.getNumberOfPages());
093            jg.writeBooleanField("isPreviousPageAvailable", paginable.isPreviousPageAvailable());
094            jg.writeBooleanField("isNextPageAvailable", paginable.isNextPageAvailable());
095            jg.writeBooleanField("isLastPageAvailable", paginable.isLastPageAvailable());
096            jg.writeBooleanField("isSortable", paginable.isSortable());
097            jg.writeBooleanField("hasError", paginable.hasError());
098            jg.writeStringField("errorMessage", paginable.getErrorMessage());
099            if (paginable.hasAggregateSupport() && paginable.getAggregates() != null
100                    && !paginable.getAggregates().isEmpty()) {
101                jg.writeObjectField("aggregations", paginable.getAggregates());
102            }
103        }
104    }
105
106    /**
107     * Override this method to write into list header
108     */
109    protected void writeHeader(JsonGenerator jg, List<T> list) throws IOException {
110    }
111
112}