001/*
002 * Copyright (c) 2006-2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Nuxeo
011 */
012package org.nuxeo.ecm.automation.core.util;
013
014import java.io.ByteArrayOutputStream;
015import java.io.IOException;
016
017import org.codehaus.jackson.JsonFactory;
018import org.codehaus.jackson.JsonGenerator;
019import org.nuxeo.ecm.core.api.model.impl.ComplexProperty;
020import org.nuxeo.ecm.webengine.JsonFactoryManager;
021import org.nuxeo.runtime.api.Framework;
022
023/**
024 * Helper to handle marshalling of complex types into a JSON-encoded string.
025 *
026 * @since 7.1
027 */
028public class ComplexPropertyJSONEncoder {
029
030    private static JsonFactory getFactory() {
031        JsonFactoryManager jsonFactoryManager = Framework.getLocalService(JsonFactoryManager.class);
032        return jsonFactoryManager.getJsonFactory();
033    }
034
035    public static String encode(ComplexProperty cp) throws IOException {
036        return encode(cp, DateTimeFormat.W3C);
037    }
038
039    public static String encode(ComplexProperty cp, DateTimeFormat dateTimeFormat) throws IOException {
040        ByteArrayOutputStream out = new ByteArrayOutputStream();
041        JsonGenerator jg = getFactory().createJsonGenerator(out);
042        JSONPropertyWriter.writePropertyValue(jg, cp, dateTimeFormat, null);
043        jg.flush();
044        jg.close();
045        return out.toString("UTF-8");
046    }
047}