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