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