001/* 002 * (C) Copyright 2015 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 * Nicolas Chapurlat <nchapurlat@nuxeo.com> 016 */ 017 018package org.nuxeo.ecm.core.io.marshallers.json; 019 020import java.io.IOException; 021import java.io.OutputStream; 022import java.io.Writer; 023 024import org.apache.commons.io.output.WriterOutputStream; 025import org.codehaus.jackson.JsonGenerator; 026 027/** 028 * This {@link OutputStream} is a technical wrapper for {@link JsonGenerator}. It's used to broadcast a 029 * {@link JsonGenerator} between marshallers. 030 * <p> 031 * take a look at {@link AbstractJsonWriter#getGenerator(OutputStream, boolean)} to understand the mechanism. 032 * </p> 033 * 034 * @since 7.2 035 */ 036public class OutputStreamWithJsonWriter extends OutputStream { 037 038 private OutputStream out; 039 040 private JsonGenerator jsonGenerator; 041 042 public OutputStreamWithJsonWriter(JsonGenerator jsonGenerator) { 043 super(); 044 this.jsonGenerator = jsonGenerator; 045 Object outputTarget = jsonGenerator.getOutputTarget(); 046 if (outputTarget instanceof OutputStream) { 047 out = (OutputStream) outputTarget; 048 } else if (outputTarget instanceof Writer) { 049 out = new WriterOutputStream((Writer) outputTarget); 050 } 051 } 052 053 public JsonGenerator getJsonGenerator() { 054 return jsonGenerator; 055 } 056 057 @Override 058 public void write(int b) throws IOException { 059 out.write(b); 060 } 061 062 @Override 063 public void write(byte[] b) throws IOException { 064 out.write(b); 065 } 066 067 @Override 068 public void write(byte[] b, int off, int len) throws IOException { 069 out.write(b, off, len); 070 } 071 072 @Override 073 public void flush() throws IOException { 074 out.flush(); 075 } 076 077 @Override 078 public void close() throws IOException { 079 out.close(); 080 } 081 082}