1 /* 2 * Copyright (C) 2009-2010, Google Inc. and others 3 * 4 * This program and the accompanying materials are made available under the 5 * terms of the Eclipse Distribution License v. 1.0 which is available at 6 * https://www.eclipse.org/org/documents/edl-v10.php. 7 * 8 * SPDX-License-Identifier: BSD-3-Clause 9 */ 10 11 package org.eclipse.jgit.util.io; 12 13 import static java.nio.charset.StandardCharsets.UTF_8; 14 15 import java.io.ByteArrayOutputStream; 16 import java.io.IOException; 17 import java.io.OutputStream; 18 import java.io.OutputStreamWriter; 19 import java.io.Writer; 20 21 import org.eclipse.jgit.util.RawParseUtils; 22 23 /** 24 * Combines messages from an OutputStream (hopefully in UTF-8) and a Writer. 25 * <p> 26 * This class is primarily meant for {@code BaseConnection} in contexts where a 27 * standard error stream from a command execution, as well as messages from a 28 * side-band channel, need to be combined together into a buffer to represent 29 * the complete set of messages from a remote repository. 30 * <p> 31 * Writes made to the writer are re-encoded as UTF-8 and interleaved into the 32 * buffer that {@link #getRawStream()} also writes to. 33 * <p> 34 * {@link #toString()} returns all written data, after converting it to a String 35 * under the assumption of UTF-8 encoding. 36 * <p> 37 * Internally {@link org.eclipse.jgit.util.RawParseUtils#decode(byte[])} is used 38 * by {@code toString()} tries to work out a reasonably correct character set 39 * for the raw data. 40 */ 41 public class MessageWriter extends Writer { 42 private final ByteArrayOutputStream buf; 43 44 private final OutputStreamWriter enc; 45 46 /** 47 * Create an empty writer. 48 */ 49 public MessageWriter() { 50 buf = new ByteArrayOutputStream(); 51 enc = new OutputStreamWriter(getRawStream(), UTF_8); 52 } 53 54 /** {@inheritDoc} */ 55 @Override 56 public void write(char[] cbuf, int off, int len) throws IOException { 57 synchronized (buf) { 58 enc.write(cbuf, off, len); 59 enc.flush(); 60 } 61 } 62 63 /** 64 * Get the underlying byte stream that character writes to this writer drop 65 * into. 66 * 67 * @return the underlying byte stream that character writes to this writer 68 * drop into. Writes to this stream should should be in UTF-8. 69 */ 70 public OutputStream getRawStream() { 71 return buf; 72 } 73 74 /** {@inheritDoc} */ 75 @Override 76 public void close() throws IOException { 77 // Do nothing, we are buffered with no resources. 78 } 79 80 /** {@inheritDoc} */ 81 @Override 82 public void flush() throws IOException { 83 // Do nothing, we are buffered with no resources. 84 } 85 86 /** @return string version of all buffered data. */ 87 /** {@inheritDoc} */ 88 @Override 89 public String toString() { 90 return RawParseUtils.decode(buf.toByteArray()); 91 } 92 }