001/*
002 * (C) Copyright 2014 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 *     bstefanescu
016 *     vpasquier
017 */
018package org.nuxeo.ecm.webengine.app;
019
020import org.codehaus.jackson.JsonEncoding;
021import org.codehaus.jackson.JsonFactory;
022import org.codehaus.jackson.JsonGenerator;
023import org.nuxeo.ecm.webengine.JsonFactoryManager;
024import org.nuxeo.ecm.webengine.WebException;
025import org.nuxeo.runtime.api.Framework;
026
027import javax.ws.rs.core.MediaType;
028import java.io.IOException;
029import java.io.OutputStream;
030
031/**
032 * @since 6.0
033 */
034public class JsonWebengineWriter {
035
036    static JsonFactoryManager jsonFactoryManager;
037
038    private static JsonFactory getFactory() {
039        jsonFactoryManager = Framework.getLocalService(JsonFactoryManager.class);
040        return jsonFactoryManager.getJsonFactory();
041    }
042
043    private static JsonGenerator createGenerator(OutputStream out) throws IOException {
044        return getFactory().createJsonGenerator(out, JsonEncoding.UTF8);
045    }
046
047    public static void writeException(OutputStream out, WebException webException, MediaType mediaType)
048            throws IOException {
049        writeException(createGenerator(out), webException, mediaType);
050    }
051
052    public static void writeException(JsonGenerator jg, WebException webException, MediaType mediaType)
053            throws IOException {
054        jg.writeStartObject();
055        jg.writeStringField("entity-type", "exception");
056        jg.writeStringField("code", webException.getType());
057        jg.writeNumberField("status", webException.getStatus());
058        // jg.writeStringField("help_url", eh.getHelpUrl());
059        // jg.writeStringField("request_id", eh.getRequestId());
060        jg.writeStringField("message", webException.getMessage());
061        if (jsonFactoryManager.isStackDisplay()
062                || MediaType.valueOf(MediaType.APPLICATION_JSON + "+nxentity").equals(mediaType)) {
063            jg.writeStringField("stacktrace", webException.getStackTraceString());
064            jg.writeObjectField("exception", webException.getCause());
065        }
066        jg.writeEndObject();
067        jg.flush();
068    }
069
070}