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