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