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.restapi.test; 018 019import java.io.ByteArrayOutputStream; 020import java.io.IOException; 021import java.io.OutputStream; 022import java.util.Arrays; 023 024import org.codehaus.jackson.JsonGenerator; 025import org.nuxeo.ecm.automation.jaxrs.io.documents.JsonDocumentListWriter; 026import org.nuxeo.ecm.automation.jaxrs.io.documents.JsonDocumentWriter; 027import org.nuxeo.ecm.core.api.DocumentModel; 028import org.nuxeo.ecm.core.api.DocumentModelList; 029import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl; 030import org.nuxeo.ecm.webengine.JsonFactoryManager; 031import org.nuxeo.runtime.api.Framework; 032 033/** 034 * @since 5.7.3 035 */ 036public class JSONDocumentHelper { 037 038 private static final String[] DEFAULT_SCHEMAS = new String[] {}; 039 040 public static String getDocAsJson(String[] schemas, DocumentModel doc) throws Exception { 041 OutputStream out = new ByteArrayOutputStream(); 042 JsonGenerator jg = getJsonGenerator(out); 043 JsonDocumentWriter.writeDocument(jg, doc, DEFAULT_SCHEMAS, null); 044 return out.toString(); 045 046 } 047 048 private static JsonGenerator getJsonGenerator(OutputStream out) throws IOException { 049 JsonFactoryManager factoryProvider = Framework.getLocalService(JsonFactoryManager.class); 050 return factoryProvider.getJsonFactory().createJsonGenerator(out); 051 } 052 053 public static String getDocAsJson(DocumentModel doc) throws Exception { 054 return getDocAsJson(DEFAULT_SCHEMAS, doc); 055 } 056 057 public static String getDocsListAsJson(String[] schemas, DocumentModel... docs) throws Exception { 058 OutputStream out = new ByteArrayOutputStream(); 059 DocumentModelList docList = new DocumentModelListImpl(Arrays.asList(docs)); 060 JsonDocumentListWriter.writeDocuments(getJsonGenerator(out), docList, schemas, null); 061 return out.toString(); 062 } 063 064 public static String getDocsListAsJson(DocumentModel... docs) throws Exception { 065 return getDocsListAsJson(DEFAULT_SCHEMAS, docs); 066 } 067 068}