001/*
002 * (C) Copyright 2006-2012 Nuxeo SA (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 *     Nuxeo
018 */
019
020package org.nuxeo.ecm.automation.jaxrs.io;
021
022import java.io.IOException;
023import java.io.OutputStream;
024import java.io.Serializable;
025import java.lang.annotation.Annotation;
026import java.lang.reflect.Type;
027import java.util.Map;
028
029import javax.ws.rs.Produces;
030import javax.ws.rs.WebApplicationException;
031import javax.ws.rs.core.Context;
032import javax.ws.rs.core.MediaType;
033import javax.ws.rs.core.MultivaluedMap;
034import javax.ws.rs.ext.MessageBodyWriter;
035import javax.ws.rs.ext.Provider;
036
037import org.apache.commons.logging.Log;
038import org.apache.commons.logging.LogFactory;
039import org.codehaus.jackson.JsonEncoding;
040import org.codehaus.jackson.JsonFactory;
041import org.codehaus.jackson.JsonGenerator;
042import org.nuxeo.ecm.automation.core.util.PaginableRecordSet;
043import org.nuxeo.ecm.automation.core.util.RecordSet;
044
045/**
046 * Manage JSON Marshalling for {@link RecordSet} objects
047 *
048 * @author <a href="mailto:tdelprat@nuxeo.com">Tiry</a>
049 * @since 5.7
050 */
051@Provider
052@Produces({ "application/json+nxentity", "application/json" })
053public class JsonRecordSetWriter implements MessageBodyWriter<RecordSet> {
054
055    protected static Log log = LogFactory.getLog(JsonRecordSetWriter.class);
056
057    @Context
058    JsonFactory factory;
059
060    @Override
061    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
062        boolean canUse = RecordSet.class.isAssignableFrom(type);
063        return canUse;
064    }
065
066    @Override
067    public long getSize(RecordSet t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
068        return -1L;
069    }
070
071    @Override
072    public void writeTo(RecordSet records, Class<?> type, Type genericType, Annotation[] annotations,
073            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream out) throws IOException,
074            WebApplicationException {
075        try {
076            writeRecords(out, records);
077        } catch (IOException e) {
078            log.error("Failed to serialize recordset", e);
079            throw new WebApplicationException(500);
080        }
081
082    }
083
084    protected void writeRecords(OutputStream out, RecordSet records) throws IOException {
085
086        JsonGenerator jg = factory.createJsonGenerator(out, JsonEncoding.UTF8);
087
088        jg.writeStartObject();
089        jg.writeStringField("entity-type", "recordSet");
090
091        if (records instanceof PaginableRecordSet) {
092            PaginableRecordSet pRecord = (PaginableRecordSet) records;
093            jg.writeBooleanField("isPaginable", true);
094            jg.writeNumberField("resultsCount", pRecord.getResultsCount());
095            jg.writeNumberField("pageSize", pRecord.getPageSize());
096            jg.writeNumberField("maxPageSize", pRecord.getMaxPageSize());
097            jg.writeNumberField("currentPageSize", pRecord.getCurrentPageSize());
098            jg.writeNumberField("currentPageIndex", pRecord.getCurrentPageIndex());
099            jg.writeNumberField("numberOfPages", pRecord.getNumberOfPages());
100            jg.writeBooleanField("isPreviousPageAvailable", pRecord.isPreviousPageAvailable());
101            jg.writeBooleanField("isNextPageAvailable", pRecord.isNextPageAvailable());
102            jg.writeBooleanField("isLastPageAvailable", pRecord.isLastPageAvailable());
103            jg.writeBooleanField("isSortable", pRecord.isSortable());
104            jg.writeBooleanField("hasError", pRecord.hasError());
105            jg.writeStringField("errorMessage", pRecord.getErrorMessage());
106        }
107
108        jg.writeArrayFieldStart("entries");
109        for (Map<String, Serializable> entry : records) {
110            jg.writeObject(entry);
111        }
112
113        if (records instanceof PaginableRecordSet) {
114            PaginableRecordSet pRecord = (PaginableRecordSet) records;
115            if (pRecord.hasAggregateSupport() && pRecord.getAggregates() != null && !pRecord.getAggregates().isEmpty()) {
116                jg.writeObjectField("aggregations", pRecord.getAggregates());
117            }
118        }
119
120        jg.writeEndArray();
121        jg.writeEndObject();
122        jg.flush();
123    }
124
125}