mirror of
https://github.com/openjdk/jdk.git
synced 2026-07-28 03:43:21 +00:00
8191441: (Process) add Readers and Writer access to java.lang.Process streams
Reviewed-by: naoto, alanb
This commit is contained in:
parent
7e55569ede
commit
81600dce24
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
@ -25,8 +25,13 @@
|
||||
|
||||
package java.lang;
|
||||
|
||||
import jdk.internal.util.StaticProperty;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.ProcessBuilder.Redirect;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.UnsupportedCharsetException;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@ -57,6 +62,10 @@ import java.util.stream.Stream;
|
||||
* {@link #getOutputStream()},
|
||||
* {@link #getInputStream()}, and
|
||||
* {@link #getErrorStream()}.
|
||||
* The I/O streams of characters and lines can be written and read using the methods
|
||||
* {@link #outputWriter()}, {@link #outputWriter(Charset)}},
|
||||
* {@link #inputReader()}, {@link #inputReader(Charset)},
|
||||
* {@link #errorReader()}, and {@link #errorReader(Charset)}.
|
||||
* The parent process uses these streams to feed input to and get output
|
||||
* from the process. Because some native platforms only provide
|
||||
* limited buffer size for standard input and output streams, failure
|
||||
@ -90,6 +99,16 @@ import java.util.stream.Stream;
|
||||
* @since 1.0
|
||||
*/
|
||||
public abstract class Process {
|
||||
|
||||
// Readers and Writers created for this process; so repeated calls return the same object
|
||||
// All updates must be done while synchronized on this Process.
|
||||
private BufferedWriter outputWriter;
|
||||
private Charset outputCharset;
|
||||
private BufferedReader inputReader;
|
||||
private Charset inputCharset;
|
||||
private BufferedReader errorReader;
|
||||
private Charset errorCharset;
|
||||
|
||||
/**
|
||||
* Default constructor for Process.
|
||||
*/
|
||||
@ -106,7 +125,13 @@ public abstract class Process {
|
||||
* then this method will return a
|
||||
* <a href="ProcessBuilder.html#redirect-input">null output stream</a>.
|
||||
*
|
||||
* <p>Implementation note: It is a good idea for the returned
|
||||
* @apiNote
|
||||
* When writing to both {@link #getOutputStream()} and either {@link #outputWriter()}
|
||||
* or {@link #outputWriter(Charset)}, {@link BufferedWriter#flush BufferedWriter.flush}
|
||||
* should be called before writes to the {@code OutputStream}.
|
||||
*
|
||||
* @implNote
|
||||
* Implementation note: It is a good idea for the returned
|
||||
* output stream to be buffered.
|
||||
*
|
||||
* @return the output stream connected to the normal input of the
|
||||
@ -132,7 +157,12 @@ public abstract class Process {
|
||||
* then the input stream returned by this method will receive the
|
||||
* merged standard output and the standard error of the process.
|
||||
*
|
||||
* <p>Implementation note: It is a good idea for the returned
|
||||
* @apiNote
|
||||
* Use {@link #getInputStream} and {@link #inputReader} with extreme care.
|
||||
* The {@code BufferedReader} may have buffered input from the input stream.
|
||||
*
|
||||
* @implNote
|
||||
* Implementation note: It is a good idea for the returned
|
||||
* input stream to be buffered.
|
||||
*
|
||||
* @return the input stream connected to the normal output of the
|
||||
@ -153,7 +183,12 @@ public abstract class Process {
|
||||
* then this method will return a
|
||||
* <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
|
||||
*
|
||||
* <p>Implementation note: It is a good idea for the returned
|
||||
* @apiNote
|
||||
* Use {@link #getInputStream} and {@link #inputReader} with extreme care.
|
||||
* The {@code BufferedReader} may have buffered input from the input stream.
|
||||
*
|
||||
* @implNote
|
||||
* Implementation note: It is a good idea for the returned
|
||||
* input stream to be buffered.
|
||||
*
|
||||
* @return the input stream connected to the error output of
|
||||
@ -161,6 +196,222 @@ public abstract class Process {
|
||||
*/
|
||||
public abstract InputStream getErrorStream();
|
||||
|
||||
/**
|
||||
* Returns a {@link BufferedReader BufferedReader} connected to the standard
|
||||
* output of the process. The {@link Charset} for the native encoding is used
|
||||
* to read characters, lines, or stream lines from standard output.
|
||||
*
|
||||
* <p>This method delegates to {@link #inputReader(Charset)} using the
|
||||
* {@link Charset} named by the {@code native.encoding} system property.
|
||||
* If the {@code native.encoding} is not a valid charset name or not supported
|
||||
* the {@link Charset#defaultCharset()} is used.
|
||||
*
|
||||
* @return a {@link BufferedReader BufferedReader} using the
|
||||
* {@code native.encoding} if supported, otherwise, the
|
||||
* {@link Charset#defaultCharset()}
|
||||
* @since 17
|
||||
*/
|
||||
public final BufferedReader inputReader() {
|
||||
return inputReader(CharsetHolder.nativeCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link BufferedReader BufferedReader} connected to the
|
||||
* standard output of this process using a Charset.
|
||||
* The {@code BufferedReader} can be used to read characters, lines,
|
||||
* or stream lines of the standard output.
|
||||
*
|
||||
* <p>Characters are read by an InputStreamReader that reads and decodes bytes
|
||||
* from this process {@link #getInputStream()}. Bytes are decoded to characters
|
||||
* using the {@code charset}; malformed-input and unmappable-character
|
||||
* sequences are replaced with the charset's default replacement.
|
||||
* The {@code BufferedReader} reads and buffers characters from the InputStreamReader.
|
||||
*
|
||||
* <p>The first call to this method creates the {@link BufferedReader BufferedReader},
|
||||
* if called again with the same {@code charset} the same {@code BufferedReader} is returned.
|
||||
* It is an error to call this method again with a different {@code charset}.
|
||||
*
|
||||
* <p>If the standard output of the process has been redirected using
|
||||
* {@link ProcessBuilder#redirectOutput(Redirect) ProcessBuilder.redirectOutput}
|
||||
* then the {@code InputStreamReader} will be reading from a
|
||||
* <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
|
||||
*
|
||||
* <p>Otherwise, if the standard error of the process has been redirected using
|
||||
* {@link ProcessBuilder#redirectErrorStream(boolean)
|
||||
* ProcessBuilder.redirectErrorStream} then the input reader returned by
|
||||
* this method will receive the merged standard output and the standard error
|
||||
* of the process.
|
||||
*
|
||||
* @apiNote
|
||||
* Using both {@link #getInputStream} and {@link #inputReader(Charset)} has
|
||||
* unpredictable behavior since the buffered reader reads ahead from the
|
||||
* input stream.
|
||||
*
|
||||
* <p>When the process has terminated, and the standard input has not been redirected,
|
||||
* reading of the bytes available from the underlying stream is on a best effort basis and
|
||||
* may be unpredictable.
|
||||
*
|
||||
* @param charset the {@code Charset} used to decode bytes to characters
|
||||
* @return a {@code BufferedReader} for the standard output of the process using the {@code charset}
|
||||
* @throws NullPointerException if the {@code charset} is {@code null}
|
||||
* @throws IllegalStateException if called more than once with different charset arguments
|
||||
* @since 17
|
||||
*/
|
||||
public final BufferedReader inputReader(Charset charset) {
|
||||
Objects.requireNonNull(charset, "charset");
|
||||
synchronized (this) {
|
||||
if (inputReader == null) {
|
||||
inputCharset = charset;
|
||||
inputReader = new BufferedReader(new InputStreamReader(getInputStream(), charset));
|
||||
} else {
|
||||
if (!inputCharset.equals(charset))
|
||||
throw new IllegalStateException("BufferedReader was created with charset: " + inputCharset);
|
||||
}
|
||||
return inputReader;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link BufferedReader BufferedReader} connected to the standard
|
||||
* error of the process. The {@link Charset} for the native encoding is used
|
||||
* to read characters, lines, or stream lines from standard error.
|
||||
*
|
||||
* <p>This method delegates to {@link #errorReader(Charset)} using the
|
||||
* {@link Charset} named by the {@code native.encoding} system property.
|
||||
* If the {@code native.encoding} is not a valid charset name or not supported
|
||||
* the {@link Charset#defaultCharset()} is used.
|
||||
*
|
||||
* @return a {@link BufferedReader BufferedReader} using the
|
||||
* {@code native.encoding} if supported, otherwise, the
|
||||
* {@link Charset#defaultCharset()}
|
||||
* @since 17
|
||||
*/
|
||||
public final BufferedReader errorReader() {
|
||||
return errorReader(CharsetHolder.nativeCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@link BufferedReader BufferedReader} connected to the
|
||||
* standard error of this process using a Charset.
|
||||
* The {@code BufferedReader} can be used to read characters, lines,
|
||||
* or stream lines of the standard error.
|
||||
*
|
||||
* <p>Characters are read by an InputStreamReader that reads and decodes bytes
|
||||
* from this process {@link #getErrorStream()}. Bytes are decoded to characters
|
||||
* using the {@code charset}; malformed-input and unmappable-character
|
||||
* sequences are replaced with the charset's default replacement.
|
||||
* The {@code BufferedReader} reads and buffers characters from the InputStreamReader.
|
||||
*
|
||||
* <p>The first call to this method creates the {@link BufferedReader BufferedReader},
|
||||
* if called again with the same {@code charset} the same {@code BufferedReader} is returned.
|
||||
* It is an error to call this method again with a different {@code charset}.
|
||||
*
|
||||
* <p>If the standard error of the process has been redirected using
|
||||
* {@link ProcessBuilder#redirectError(Redirect) ProcessBuilder.redirectError} or
|
||||
* {@link ProcessBuilder#redirectErrorStream(boolean) ProcessBuilder.redirectErrorStream}
|
||||
* then the {@code InputStreamReader} will be reading from a
|
||||
* <a href="ProcessBuilder.html#redirect-output">null input stream</a>.
|
||||
*
|
||||
* @apiNote
|
||||
* Using both {@link #getErrorStream} and {@link #errorReader(Charset)} has
|
||||
* unpredictable behavior since the buffered reader reads ahead from the
|
||||
* error stream.
|
||||
*
|
||||
* <p>When the process has terminated, and the standard error has not been redirected,
|
||||
* reading of the bytes available from the underlying stream is on a best effort basis and
|
||||
* may be unpredictable.
|
||||
*
|
||||
* @param charset the {@code Charset} used to decode bytes to characters
|
||||
* @return a {@code BufferedReader} for the standard error of the process using the {@code charset}
|
||||
* @throws NullPointerException if the {@code charset} is {@code null}
|
||||
* @throws IllegalStateException if called more than once with different charset arguments
|
||||
* @since 17
|
||||
*/
|
||||
public final BufferedReader errorReader(Charset charset) {
|
||||
Objects.requireNonNull(charset, "charset");
|
||||
synchronized (this) {
|
||||
if (errorReader == null) {
|
||||
errorCharset = charset;
|
||||
errorReader = new BufferedReader(new InputStreamReader(getErrorStream(), charset));
|
||||
} else {
|
||||
if (!errorCharset.equals(charset))
|
||||
throw new IllegalStateException("BufferedReader was created with charset: " + errorCharset);
|
||||
}
|
||||
return errorReader;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@code BufferedWriter} connected to the normal input of the process
|
||||
* using the native encoding.
|
||||
* Writes text to a character-output stream, buffering characters so as to provide
|
||||
* for the efficient writing of single characters, arrays, and strings.
|
||||
*
|
||||
* <p>This method delegates to {@link #outputWriter(Charset)} using the
|
||||
* {@link Charset} named by the {@code native.encoding} system property.
|
||||
* If the {@code native.encoding} is not a valid charset name or not supported
|
||||
* the {@link Charset#defaultCharset()} is used.
|
||||
*
|
||||
* @return a {@code BufferedWriter} to the standard input of the process using the charset
|
||||
* for the {@code native.encoding} system property
|
||||
* @since 17
|
||||
*/
|
||||
public final BufferedWriter outputWriter() {
|
||||
return outputWriter(CharsetHolder.nativeCharset());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a {@code BufferedWriter} connected to the normal input of the process
|
||||
* using a Charset.
|
||||
* Writes text to a character-output stream, buffering characters so as to provide
|
||||
* for the efficient writing of single characters, arrays, and strings.
|
||||
*
|
||||
* <p>Characters written by the writer are encoded to bytes using {@link OutputStreamWriter}
|
||||
* and the {@link Charset} are written to the standard input of the process represented
|
||||
* by this {@code Process}.
|
||||
* Malformed-input and unmappable-character sequences are replaced with the charset's
|
||||
* default replacement.
|
||||
*
|
||||
* <p>The first call to this method creates the {@link BufferedWriter BufferedWriter},
|
||||
* if called again with the same {@code charset} the same {@code BufferedWriter} is returned.
|
||||
* It is an error to call this method again with a different {@code charset}.
|
||||
*
|
||||
* <p>If the standard input of the process has been redirected using
|
||||
* {@link ProcessBuilder#redirectInput(Redirect)
|
||||
* ProcessBuilder.redirectInput} then the {@code OutputStreamWriter} writes to a
|
||||
* <a href="ProcessBuilder.html#redirect-input">null output stream</a>.
|
||||
*
|
||||
* @apiNote
|
||||
* A {@linkplain BufferedWriter} writes characters, arrays of characters, and strings.
|
||||
* Wrapping the {@link BufferedWriter} with a {@link PrintWriter} provides
|
||||
* efficient buffering and formatting of primitives and objects as well as support
|
||||
* for auto-flush on line endings.
|
||||
* Call the {@link BufferedWriter#flush()} method to flush buffered output to the process.
|
||||
* <p>
|
||||
* When writing to both {@link #getOutputStream()} and either {@link #outputWriter()}
|
||||
* or {@link #outputWriter(Charset)}, {@linkplain BufferedWriter#flush BufferedWriter.flush}
|
||||
* should be called before writes to the {@code OutputStream}.
|
||||
*
|
||||
* @param charset the {@code Charset} to encode characters to bytes
|
||||
* @return a {@code BufferedWriter} to the standard input of the process using the {@code charset}
|
||||
* @throws NullPointerException if the {@code charset} is {@code null}
|
||||
* @throws IllegalStateException if called more than once with different charset arguments
|
||||
* @since 17
|
||||
*/
|
||||
public final BufferedWriter outputWriter(Charset charset) {
|
||||
Objects.requireNonNull(charset, "charset");
|
||||
synchronized (this) {
|
||||
if (outputWriter == null) {
|
||||
outputCharset = charset;
|
||||
outputWriter = new BufferedWriter(new OutputStreamWriter(getOutputStream(), charset));
|
||||
} else {
|
||||
if (!outputCharset.equals(charset))
|
||||
throw new IllegalStateException("BufferedWriter was created with charset: " + outputCharset);
|
||||
}
|
||||
return outputWriter;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Causes the current thread to wait, if necessary, until the
|
||||
* process represented by this {@code Process} object has
|
||||
@ -261,7 +512,7 @@ public abstract class Process {
|
||||
* when the process has terminated.
|
||||
* <p>
|
||||
* Invoking this method on {@code Process} objects returned by
|
||||
* {@link ProcessBuilder#start} and {@link Runtime#exec} forcibly terminate
|
||||
* {@link ProcessBuilder#start()} and {@link Runtime#exec} forcibly terminate
|
||||
* the process.
|
||||
*
|
||||
* @implSpec
|
||||
@ -292,7 +543,7 @@ public abstract class Process {
|
||||
* forcibly and immediately terminates the process.
|
||||
* <p>
|
||||
* Invoking this method on {@code Process} objects returned by
|
||||
* {@link ProcessBuilder#start} and {@link Runtime#exec} return
|
||||
* {@link ProcessBuilder#start()} and {@link Runtime#exec} return
|
||||
* {@code true} or {@code false} depending on the platform implementation.
|
||||
*
|
||||
* @implSpec
|
||||
@ -371,7 +622,7 @@ public abstract class Process {
|
||||
* {@linkplain java.util.concurrent.CompletableFuture#cancel(boolean) Cancelling}
|
||||
* the CompletableFuture does not affect the Process.
|
||||
* <p>
|
||||
* Processes returned from {@link ProcessBuilder#start} override the
|
||||
* Processes returned from {@link ProcessBuilder#start()} override the
|
||||
* default implementation to provide an efficient mechanism to wait
|
||||
* for process exit.
|
||||
*
|
||||
@ -463,7 +714,7 @@ public abstract class Process {
|
||||
/**
|
||||
* Returns a ProcessHandle for the Process.
|
||||
*
|
||||
* {@code Process} objects returned by {@link ProcessBuilder#start} and
|
||||
* {@code Process} objects returned by {@link ProcessBuilder#start()} and
|
||||
* {@link Runtime#exec} implement {@code toHandle} as the equivalent of
|
||||
* {@link ProcessHandle#of(long) ProcessHandle.of(pid)} including the
|
||||
* check for a SecurityManager and {@code RuntimePermission("manageProcess")}.
|
||||
@ -589,4 +840,27 @@ public abstract class Process {
|
||||
return n - remaining;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A nested class to delay looking up the Charset for the native encoding.
|
||||
*/
|
||||
private static class CharsetHolder {
|
||||
private final static Charset nativeCharset;
|
||||
static {
|
||||
Charset cs;
|
||||
try {
|
||||
cs = Charset.forName(StaticProperty.nativeEncoding());
|
||||
} catch (UnsupportedCharsetException uce) {
|
||||
cs = Charset.defaultCharset();
|
||||
}
|
||||
nativeCharset = cs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Charset for the native encoding or {@link Charset#defaultCharset().
|
||||
*/
|
||||
static Charset nativeCharset() {
|
||||
return nativeCharset;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
394
test/jdk/java/lang/ProcessBuilder/ReaderWriterTest.java
Normal file
394
test/jdk/java/lang/ProcessBuilder/ReaderWriterTest.java
Normal file
@ -0,0 +1,394 @@
|
||||
/*
|
||||
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
import static org.testng.Assert.*;
|
||||
|
||||
import org.testng.Assert;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import jdk.test.lib.process.ProcessTools;
|
||||
|
||||
import jdk.test.lib.hexdump.HexPrinter;
|
||||
import jdk.test.lib.hexdump.HexPrinter.Formatters;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.Writer;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.charset.UnsupportedCharsetException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import jtreg.SkippedException;
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @library /test/lib
|
||||
* @build jdk.test.lib.process.ProcessTools jdk.test.lib.hexdump.HexPrinter
|
||||
* @run testng ReaderWriterTest
|
||||
*/
|
||||
|
||||
@Test
|
||||
public class ReaderWriterTest {
|
||||
|
||||
static final String ASCII = "ASCII: \u0000_A-Z_a-Z_\u007C_\u007D_\u007E_\u007F_;";
|
||||
static final String ISO_8859_1 = " Symbols: \u00AB_\u00BB_\u00fc_\u00fd_\u00fe_\u00ff;";
|
||||
static final String FRACTIONS = " Fractions: \u00bc_\u00bd_\u00be_\u00bf;";
|
||||
|
||||
public static final String TESTCHARS = "OneWay: " + ASCII + ISO_8859_1 + FRACTIONS;
|
||||
public static final String ROUND_TRIP_TESTCHARS = "RoundTrip: " + ASCII + ISO_8859_1 + FRACTIONS;
|
||||
|
||||
@DataProvider(name="CharsetCases")
|
||||
static Object[][] charsetCases() {
|
||||
return new Object[][] {
|
||||
{"UTF-8"},
|
||||
{"ISO8859-1"},
|
||||
{"US-ASCII"},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the defaults case of native.encoding. No extra command line flags or switches.
|
||||
*/
|
||||
@Test
|
||||
void testCaseNativeEncoding() throws IOException {
|
||||
String nativeEncoding = System.getProperty("native.encoding");
|
||||
Charset cs = Charset.forName(nativeEncoding);
|
||||
System.out.println("Native.encoding Charset: " + cs);
|
||||
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("ReaderWriterTest$ChildWithCharset");
|
||||
Process p = pb.start();
|
||||
writeTestChars(p.outputWriter());
|
||||
checkReader(p.inputReader(), cs, "Out");
|
||||
checkReader(p.errorReader(), cs, "Err");
|
||||
try {
|
||||
int exitValue = p.waitFor();
|
||||
if (exitValue != 0)
|
||||
System.out.println("exitValue: " + exitValue);
|
||||
} catch (InterruptedException ie) {
|
||||
Assert.fail("waitFor interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that redirects of input and error streams result in Readers that are empty.
|
||||
* Test that when the output to a process is redirected, the writer acts as
|
||||
* a null stream and throws an exception as expected for a null output stream
|
||||
* as specified by ProcessBuilder.
|
||||
*/
|
||||
@Test
|
||||
void testRedirects() throws IOException {
|
||||
String nativeEncoding = System.getProperty("native.encoding");
|
||||
Charset cs = Charset.forName(nativeEncoding);
|
||||
System.out.println("Native.encoding Charset: " + cs);
|
||||
|
||||
Path inPath = Path.of("InFile.tmp");
|
||||
BufferedWriter inWriter = Files.newBufferedWriter(inPath);
|
||||
inWriter.close();
|
||||
|
||||
Path outPath = Path.of("OutFile.tmp");
|
||||
Path errorPath = Path.of("ErrFile.tmp");
|
||||
|
||||
for (int errType = 1; errType < 4; errType++) {
|
||||
// Three cases to test for which the error stream is empty
|
||||
// 1: redirectErrorStream(false); redirect of errorOutput to a file
|
||||
// 2: redirectErrorStream(true); no redirect of errorOutput
|
||||
// 3: redirectErrorStream(true); redirect of errorOutput to a file
|
||||
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("ReaderWriterTest$ChildWithCharset");
|
||||
pb.redirectInput(inPath.toFile());
|
||||
pb.redirectOutput(outPath.toFile());
|
||||
if (errType == 1 || errType == 3) {
|
||||
pb.redirectError(errorPath.toFile());
|
||||
}
|
||||
if (errType == 2 || errType == 3) {
|
||||
pb.redirectErrorStream(true);
|
||||
}
|
||||
Process p = pb.start();
|
||||
// Output has been redirected to a null stream; success is IOException on the write
|
||||
try {
|
||||
BufferedWriter wr = p.outputWriter();
|
||||
wr.write("X");
|
||||
wr.flush();
|
||||
Assert.fail("writing to null stream should throw IOException");
|
||||
} catch (IOException ioe) {
|
||||
// Normal, A Null output stream is closed when created.
|
||||
}
|
||||
|
||||
// InputReader should be empty; and at EOF
|
||||
BufferedReader inputReader = p.inputReader();
|
||||
int ch = inputReader.read();
|
||||
Assert.assertEquals(ch, -1, "inputReader not at EOF: ch: " + (char)ch);
|
||||
|
||||
// InputReader should be empty; and at EOF
|
||||
BufferedReader errorReader = p.errorReader();
|
||||
ch = errorReader.read();
|
||||
Assert.assertEquals(ch, -1, "errorReader not at EOF: ch: " + (char)ch);
|
||||
|
||||
try {
|
||||
int exitValue = p.waitFor();
|
||||
if (exitValue != 0) System.out.println("exitValue: " + exitValue);
|
||||
} catch (InterruptedException ie) {
|
||||
Assert.fail("waitFor interrupted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the test characters to the child using the Process.outputWriter.
|
||||
* @param writer the Writer
|
||||
* @throws IOException if an I/O error occurs
|
||||
*/
|
||||
private static void writeTestChars(Writer writer) throws IOException {
|
||||
// Write the test data to the child
|
||||
try (writer) {
|
||||
writer.append(ROUND_TRIP_TESTCHARS);
|
||||
writer.append(System.lineSeparator());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test a child with a character set.
|
||||
* A Process is spawned; characters are written to and read from the child
|
||||
* using the character set and compared.
|
||||
*
|
||||
* @param encoding a charset name
|
||||
*/
|
||||
@Test(dataProvider = "CharsetCases", enabled = true)
|
||||
void testCase(String encoding) throws IOException {
|
||||
Charset cs = null;
|
||||
try {
|
||||
cs = Charset.forName(encoding);
|
||||
System.out.println("Charset: " + cs);
|
||||
} catch (UnsupportedCharsetException use) {
|
||||
throw new SkippedException("Charset not supported: " + encoding);
|
||||
}
|
||||
String cleanCSName = cleanCharsetName(cs);
|
||||
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
|
||||
"-Dsun.stdout.encoding=" + cleanCSName, // Encode in the child using the charset
|
||||
"-Dsun.stderr.encoding=" + cleanCSName,
|
||||
"ReaderWriterTest$ChildWithCharset");
|
||||
|
||||
Process p = pb.start();
|
||||
// Write the test data to the child
|
||||
writeTestChars(p.outputWriter(cs));
|
||||
checkReader(p.inputReader(cs), cs, "Out");
|
||||
checkReader(p.errorReader(cs), cs, "Err");
|
||||
try {
|
||||
int exitValue = p.waitFor();
|
||||
if (exitValue != 0)
|
||||
System.out.println("exitValue: " + exitValue);
|
||||
} catch (InterruptedException ie) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test passing null when a charset is expected
|
||||
* @throws IOException if an I/O error occurs; not expected
|
||||
*/
|
||||
@Test
|
||||
void testNullCharsets() throws IOException {
|
||||
// Launch a child; its behavior is not interesting and is ignored
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
|
||||
"ReaderWriterTest$ChildWithCharset");
|
||||
|
||||
Process p = pb.start();
|
||||
try {
|
||||
writeTestChars(p.outputWriter(null));
|
||||
Assert.fail("Process.outputWriter(null) did not throw NPE");
|
||||
} catch (NullPointerException npe) {
|
||||
// expected, ignore
|
||||
}
|
||||
try {
|
||||
checkReader(p.inputReader(null), null, "Out");
|
||||
Assert.fail("Process.inputReader(null) did not throw NPE");
|
||||
} catch (NullPointerException npe) {
|
||||
// expected, ignore
|
||||
}
|
||||
try {
|
||||
checkReader(p.errorReader(null), null, "Err");
|
||||
Assert.fail("Process.errorReader(null) did not throw NPE");
|
||||
} catch (NullPointerException npe) {
|
||||
// expected, ignore
|
||||
}
|
||||
|
||||
p.destroyForcibly();
|
||||
try {
|
||||
// Collect the exit status to cleanup after the process; but ignore it
|
||||
p.waitFor();
|
||||
} catch (InterruptedException ie) {
|
||||
// Ignored
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test passing different charset on multiple calls when the same charset is expected.
|
||||
* @throws IOException if an I/O error occurs; not expected
|
||||
*/
|
||||
@Test
|
||||
void testIllegalArgCharsets() throws IOException {
|
||||
String nativeEncoding = System.getProperty("native.encoding");
|
||||
Charset cs = Charset.forName(nativeEncoding);
|
||||
System.out.println("Native.encoding Charset: " + cs);
|
||||
Charset otherCharset = cs.equals(StandardCharsets.UTF_8)
|
||||
? StandardCharsets.ISO_8859_1
|
||||
: StandardCharsets.UTF_8;
|
||||
|
||||
// Launch a child; its behavior is not interesting and is ignored
|
||||
ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
|
||||
"ReaderWriterTest$ChildWithCharset");
|
||||
|
||||
Process p = pb.start();
|
||||
try {
|
||||
var writer = p.outputWriter(cs);
|
||||
writer = p.outputWriter(cs); // try again with same
|
||||
writer = p.outputWriter(otherCharset); // this should throw
|
||||
Assert.fail("Process.outputWriter(otherCharset) did not throw IllegalStateException");
|
||||
} catch (IllegalStateException ile) {
|
||||
// expected, ignore
|
||||
System.out.println(ile);
|
||||
}
|
||||
try {
|
||||
var reader = p.inputReader(cs);
|
||||
reader = p.inputReader(cs); // try again with same
|
||||
reader = p.inputReader(otherCharset); // this should throw
|
||||
Assert.fail("Process.inputReader(otherCharset) did not throw IllegalStateException");
|
||||
} catch (IllegalStateException ile) {
|
||||
// expected, ignore
|
||||
System.out.println(ile);
|
||||
}
|
||||
try {
|
||||
var reader = p.errorReader(cs);
|
||||
reader = p.errorReader(cs); // try again with same
|
||||
reader = p.errorReader(otherCharset); // this should throw
|
||||
Assert.fail("Process.errorReader(otherCharset) did not throw IllegalStateException");
|
||||
} catch (IllegalStateException ile) {
|
||||
// expected, ignore
|
||||
System.out.println(ile);
|
||||
}
|
||||
|
||||
p.destroyForcibly();
|
||||
try {
|
||||
// Collect the exit status to cleanup after the process; but ignore it
|
||||
p.waitFor();
|
||||
} catch (InterruptedException ie) {
|
||||
// Ignored
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkReader(BufferedReader reader, Charset cs, String label) throws IOException {
|
||||
try (BufferedReader in = reader) {
|
||||
String prefix = " " + label + ": ";
|
||||
String firstline = in.readLine();
|
||||
System.out.append(prefix).println(firstline);
|
||||
String secondline = in.readLine();
|
||||
System.out.append(prefix).println(secondline);
|
||||
for (String line = in.readLine(); line != null; line = in.readLine()) {
|
||||
System.out.append(prefix).append(line);
|
||||
System.out.println();
|
||||
}
|
||||
ByteBuffer bb = cs.encode(TESTCHARS);
|
||||
String reencoded = cs.decode(bb).toString();
|
||||
if (!firstline.equals(reencoded))
|
||||
diffStrings(firstline, reencoded);
|
||||
assertEquals(firstline, reencoded, label + " Test Chars");
|
||||
|
||||
bb = cs.encode(ROUND_TRIP_TESTCHARS);
|
||||
reencoded = cs.decode(bb).toString();
|
||||
if (!secondline.equals(reencoded))
|
||||
diffStrings(secondline, reencoded);
|
||||
assertEquals(secondline, reencoded, label + " Round Trip Test Chars");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A cleaned up Charset name that is suitable for Linux LANG environment variable.
|
||||
* If there are two '-'s the first one is removed.
|
||||
* @param cs a Charset
|
||||
* @return the cleanedup Charset name
|
||||
*/
|
||||
private static String cleanCharsetName(Charset cs) {
|
||||
String name = cs.name();
|
||||
int ndx = name.indexOf('-');
|
||||
if (ndx >= 0 && name.indexOf('-', ndx + 1) >= 0) {
|
||||
name = name.substring(0, ndx) + name.substring(ndx + 1);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
private static void diffStrings(String actual, String expected) {
|
||||
if (actual.equals(expected))
|
||||
return;
|
||||
int lenDiff = expected.length() - actual.length();
|
||||
if (lenDiff != 0)
|
||||
System.out.println("String lengths: " + actual.length() + " != " + expected.length());
|
||||
int first; // find first mismatched character
|
||||
for (first = 0; first < Math.min(actual.length(), expected.length()); first++) {
|
||||
if (actual.charAt(first) != expected.charAt(first))
|
||||
break;
|
||||
}
|
||||
int last;
|
||||
for (last = actual.length() - 1; last >= 0 && (last + lenDiff) >= 0; last--) {
|
||||
if (actual.charAt(last) != expected.charAt(last + lenDiff))
|
||||
break; // last mismatched character
|
||||
}
|
||||
System.out.printf("actual vs expected[%3d]: 0x%04x != 0x%04x%n", first, (int)actual.charAt(first), (int)expected.charAt(first));
|
||||
System.out.printf("actual vs expected[%3d]: 0x%04x != 0x%04x%n", last, (int)actual.charAt(last), (int)expected.charAt(last));
|
||||
System.out.printf("actual [%3d-%3d]: %s%n", first, last, actual.substring(first, last+1));
|
||||
System.out.printf("expected[%3d-%3d]: %s%n", first, last, expected.substring(first, last + lenDiff + 1));
|
||||
}
|
||||
|
||||
static class ChildWithCharset {
|
||||
public static void main(String[] args) {
|
||||
String nativeEncoding = System.getProperty("native.encoding");
|
||||
System.out.println(TESTCHARS);
|
||||
byte[] bytes = null;
|
||||
try {
|
||||
bytes = System.in.readAllBytes();
|
||||
System.out.write(bytes); // echo bytes back to parent on stdout
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace(); // Seen by the parent
|
||||
}
|
||||
System.out.println("native.encoding: " + nativeEncoding);
|
||||
System.out.println("sun.stdout.encoding: " + System.getProperty("sun.stdout.encoding"));
|
||||
System.out.println("LANG: " + System.getenv().get("LANG"));
|
||||
|
||||
System.err.println(TESTCHARS);
|
||||
try {
|
||||
System.err.write(bytes); // echo bytes back to parent on stderr
|
||||
} catch (IOException ioe) {
|
||||
ioe.printStackTrace(); // Seen by the parent
|
||||
}
|
||||
System.err.println("native.encoding: " + nativeEncoding);
|
||||
System.err.println("sun.stderr.encoding: " + System.getProperty("sun.stderr.encoding"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user