下面列出了org.apache.http.nio.IOControl#java.io.PipedOutputStream 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static void redirectSystemIn() throws Exception {
// This starts the MvsConsole listener if it's not already started (by the JZOS Batch Launcher)
if (!MvsConsole.isListening()) {
MvsConsole.startMvsCommandListener();
}
PipedOutputStream pos = new PipedOutputStream();
final Writer writer = new OutputStreamWriter(pos); // use default file.encoding
MvsConsole.registerMvsCommandCallback(
new MvsCommandCallback() {
public void handleStart(String parms) {};
public void handleModify(String cmd) {
try {
writer.write(cmd + "\n");
writer.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public boolean handleStop() { return true; } // System.exit()
});
PipedInputStream pis = new PipedInputStream(pos);
System.setIn(pis);
}
/**
* Update out - test failed
*/
public void updateOut() {
// outPipe = new PipedOutputStream();
// try {
// in = new PipedInputStream((PipedOutputStream) outPipe);
// } catch (IOException e) {
// print("Console internal error (1)...", Color.red);
// }
PipedOutputStream pout = new PipedOutputStream();
out = new UnclosableOutputStream(pout);
try {
inPipe = new BlockingPipedInputStream(pout);
} catch (IOException e) {
print("Console internal error: " + e);
}
}
private static void testJarExtract(String jarFile) throws IOException {
List<String> argList = new ArrayList<String>();
argList.add("-xvf");
argList.add(jarFile);
argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);
String jarArgs[] = new String[argList.size()];
jarArgs = argList.toArray(jarArgs);
PipedOutputStream pipedOutput = new PipedOutputStream();
PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
PrintStream out = new PrintStream(pipedOutput);
Main jarTool = new Main(out, System.err, "jar");
if (!jarTool.run(jarArgs)) {
fail("Could not list jar file.");
}
out.flush();
check(pipedInput.available() > 0);
}
/**
* Instantiates a new microphone input stream.
*
* @param opusEncoded the opus encoded
*/
public MicrophoneInputStream(boolean opusEncoded) {
captureThread = new MicrophoneCaptureThread(this, opusEncoded);
if (opusEncoded == true) {
CONTENT_TYPE = ContentType.OPUS;
} else {
CONTENT_TYPE = ContentType.RAW;
}
os = new PipedOutputStream();
is = new PipedInputStream();
try {
is.connect(os);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
captureThread.start();
}
private static void testJarExtract(String jarFile) throws IOException {
List<String> argList = new ArrayList<String>();
argList.add("-xvf");
argList.add(jarFile);
argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);
String jarArgs[] = new String[argList.size()];
jarArgs = argList.toArray(jarArgs);
PipedOutputStream pipedOutput = new PipedOutputStream();
PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
PrintStream out = new PrintStream(pipedOutput);
Main jarTool = new Main(out, System.err, "jar");
if (!jarTool.run(jarArgs)) {
fail("Could not list jar file.");
}
out.flush();
check(pipedInput.available() > 0);
}
@Before
public void setup() throws IOException {
PipedInputStream inClient = new PipedInputStream();
PipedOutputStream outClient = new PipedOutputStream();
PipedInputStream inServer = new PipedInputStream();
PipedOutputStream outServer = new PipedOutputStream();
inClient.connect(outServer);
outClient.connect(inServer);
server = new AssertingEndpoint();
serverLauncher = DSPLauncher.createServerLauncher(
ServiceEndpoints.toServiceObject(server, IDebugProtocolServer.class), inServer, outServer);
serverListening = serverLauncher.startListening();
client = new AssertingEndpoint();
clientLauncher = DSPLauncher.createClientLauncher(
ServiceEndpoints.toServiceObject(client, IDebugProtocolClient.class), inClient, outClient);
clientListening = clientLauncher.startListening();
Logger logger = Logger.getLogger(StreamMessageProducer.class.getName());
logLevel = logger.getLevel();
logger.setLevel(Level.SEVERE);
}
@Test
public void testTestCommand() throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession("admin", "localhost", properties.getShell().getPort());
jsch.addIdentity("src/test/resources/id_rsa");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
ChannelShell channel = (ChannelShell) session.openChannel("shell");
try (PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream()) {
channel.setInputStream(new PipedInputStream(pos));
channel.setOutputStream(new PipedOutputStream(pis));
channel.connect();
pos.write("test run bob\r".getBytes(StandardCharsets.UTF_8));
pos.flush();
verifyResponseContains(pis, "test run bob");
}
channel.disconnect();
session.disconnect();
}
@Test public void shouldKnowIfPumperExpired() throws Exception {
PipedOutputStream output = new PipedOutputStream();
InputStream inputStream = new PipedInputStream(output);
try {
TestingClock clock = new TestingClock();
StreamPumper pumper = new StreamPumper(inputStream, new TestConsumer(), "", "utf-8", clock);
new Thread(pumper).start();
output.write("line1\n".getBytes());
output.flush();
long timeoutDuration = 2L;
assertThat(pumper.didTimeout(timeoutDuration, TimeUnit.SECONDS), is(false));
clock.addSeconds(5);
assertThat(pumper.didTimeout(timeoutDuration, TimeUnit.SECONDS), is(true));
} finally {
output.close();
}
}
@Test
public void canHandleDataNotAlreadyPresentSeparatedByComma()
throws Exception {
List<String> expected = Arrays.asList("a", "b", "c");
PipedOutputStream os = new PipedOutputStream();
PipedInputStream is = new PipedInputStream(os);
StreamReader reader = process(is, ",", expected);
TimeUnit.SECONDS.sleep(2);
os.write("a,b,c,".getBytes());
waitUntil(expected.size());
assertThat(received, is(expected));
reader.close();
}
private static void testJarExtract(String jarFile) throws IOException {
List<String> argList = new ArrayList<String>();
argList.add("-xvf");
argList.add(jarFile);
argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);
String jarArgs[] = new String[argList.size()];
jarArgs = argList.toArray(jarArgs);
PipedOutputStream pipedOutput = new PipedOutputStream();
PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
PrintStream out = new PrintStream(pipedOutput);
Main jarTool = new Main(out, System.err, "jar");
if (!jarTool.run(jarArgs)) {
fail("Could not list jar file.");
}
out.flush();
check(pipedInput.available() > 0);
}
public LineDisciplineTerminal(String name,
String type,
OutputStream masterOutput) throws IOException {
super(name, type);
PipedInputStream input = new LinePipedInputStream(PIPE_SIZE);
this.slaveInputPipe = new PipedOutputStream(input);
// This is a hack to fix a problem in gogo where closure closes
// streams for commands if they are instances of PipedInputStream.
// So we need to get around and make sure it's not an instance of
// that class by using a dumb FilterInputStream class to wrap it.
this.slaveInput = new FilterInputStream(input) {};
this.slaveOutput = new FilteringOutputStream();
this.masterOutput = masterOutput;
this.attributes = new Attributes();
this.size = new Size(160, 50);
}
/**
* creates a proxy, delegating to a remote endpoint, forwarding to another remote endpoint, that delegates to an actual implementation.
* @param intf
* @param impl
* @return
* @throws IOException
*/
public <T> T wrap(Class<T> intf, T impl) {
PipedInputStream in1 = new PipedInputStream();
PipedOutputStream out1 = new PipedOutputStream();
Launcher<T> launcher1 = Launcher.createLauncher(impl, intf, in1, out1);
PipedInputStream in2 = new PipedInputStream();
PipedOutputStream out2 = new PipedOutputStream();
Launcher<T> launcher2 = Launcher.createLauncher(new Object(), intf, in2, out2);
try {
in1.connect(out2);
in2.connect(out1);
} catch (IOException e) {
throw new IllegalStateException(e);
}
launcher1.startListening();
launcher2.startListening();
return launcher2.getRemoteProxy();
}
@Test
public void pipe_test() throws Exception {
ByteArrayOutputStream collected = new ByteArrayOutputStream();
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread() {
@Override
public void run() {
try {
for (int i = 1; i <= 5; i++) {
out.write(("put-" + i + "\n").getBytes());
ThreadUtil.minimumSleep(500);
}
out.close();
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}.start();
Pipe pipe = new Pipe("name", in, collected);
pipe.waitFor();
assertEquals("put-1\nput-2\nput-3\nput-4\nput-5\n", new String(collected.toByteArray()));
}
public Worker(InputStream in, int pipeBufferSize) {
setDaemon(true);
setName("Compression thread");
this.in = in;
this.pipeBufferSize = pipeBufferSize;
this.source = new PipedInputStream(pipeBufferSize);
this.sink = new PipedOutputStream();
try {
sink.connect(source);
} catch(IOException e) {
// this can only happen if the sink is already connected. Since we just
// created it, we know it's not.
}
}
protected static InputStream httpsAwareConfigurationStream(InputStream input) throws IOException {
if (!AUTH_SERVER_SSL_REQUIRED) {
return input;
}
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
try (PrintWriter pw = new PrintWriter(out)) {
try (Scanner s = new Scanner(input)) {
while (s.hasNextLine()) {
String lineWithReplaces = s.nextLine().replace("http://localhost:8180/auth", AUTH_SERVER_SCHEME + "://localhost:" + AUTH_SERVER_PORT + "/auth");
pw.println(lineWithReplaces);
}
}
}
return in;
}
private static void testJarExtract(String jarFile) throws IOException {
List<String> argList = new ArrayList<String>();
argList.add("-xvf");
argList.add(jarFile);
argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);
String jarArgs[] = new String[argList.size()];
jarArgs = argList.toArray(jarArgs);
PipedOutputStream pipedOutput = new PipedOutputStream();
PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
PrintStream out = new PrintStream(pipedOutput);
Main jarTool = new Main(out, System.err, "jar");
if (!jarTool.run(jarArgs)) {
fail("Could not list jar file.");
}
out.flush();
check(pipedInput.available() > 0);
}
protected void verifyJobPriority(String jobId, String priority,
Configuration conf, CLI jc) throws Exception {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream(pis);
int exitCode = runTool(conf, jc, new String[] { "-list", "all" }, pos);
assertEquals("Exit code", 0, exitCode);
BufferedReader br = new BufferedReader(new InputStreamReader(pis));
String line;
while ((line = br.readLine()) != null) {
LOG.info("line = " + line);
if (!line.contains(jobId)) {
continue;
}
assertTrue(line.contains(priority));
break;
}
pis.close();
}
@Test
public void testRead() throws IOException, InterruptedException {
PipedOutputStream outputStream = new PipedOutputStream();
PipedInputStream pipedInputStream = new PipedInputStream(outputStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
TerminalConnection connection = new TerminalConnection(Charset.defaultCharset(), pipedInputStream, byteArrayOutputStream);
final ArrayList<int[]> result = new ArrayList<>();
connection.setStdinHandler(result::add);
outputStream.write(("FOO").getBytes());
outputStream.flush();
outputStream.close();
Thread.sleep(150);
connection.openBlocking();
assertArrayEquals(result.get(0), new int[] {70,79,79});
}
private static void testJarList(String jarFile) throws IOException {
List<String> argList = new ArrayList<String>();
argList.add("-tvf");
argList.add(jarFile);
argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);
String jarArgs[] = new String[argList.size()];
jarArgs = argList.toArray(jarArgs);
PipedOutputStream pipedOutput = new PipedOutputStream();
PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
PrintStream out = new PrintStream(pipedOutput);
Main jarTool = new Main(out, System.err, "jar");
if (!jarTool.run(jarArgs)) {
fail("Could not list jar file.");
}
out.flush();
check(pipedInput.available() > 0);
}
private static void testJarExtract(String jarFile) throws IOException {
List<String> argList = new ArrayList<String>();
argList.add("-xvf");
argList.add(jarFile);
argList.add(JARBACKSLASH + File.separatorChar + DIR + File.separatorChar + FILENAME);
String jarArgs[] = new String[argList.size()];
jarArgs = argList.toArray(jarArgs);
PipedOutputStream pipedOutput = new PipedOutputStream();
PipedInputStream pipedInput = new PipedInputStream(pipedOutput);
PrintStream out = new PrintStream(pipedOutput);
Main jarTool = new Main(out, System.err, "jar");
if (!jarTool.run(jarArgs)) {
fail("Could not list jar file.");
}
out.flush();
check(pipedInput.available() > 0);
}
@Before
public void setUp() throws Exception {
PipedInputStream pipeIn = new PipedInputStream(1024*1024);
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
this.in = new DataInputViewStreamWrapper(pipeIn);
this.out = new DataOutputViewStreamWrapper(pipeOut);
}
@Before
public void setup() throws Exception {
in = new PipedInputStream(1000);
out = new PipedOutputStream(in);
mIn = new DataInputViewStreamWrapper(in);
mOut = new DataOutputViewStreamWrapper(out);
}
/**
* Test that an adopter making use of these APIs is able to
* identify which client is making any given request.
*/
@Test
public void testIdentifyClientRequest() throws Exception {
// create client side
PipedInputStream in = new PipedInputStream();
PipedOutputStream out = new PipedOutputStream();
PipedInputStream in2 = new PipedInputStream();
PipedOutputStream out2 = new PipedOutputStream();
in.connect(out2);
out.connect(in2);
MyClient client = new MyClientImpl();
Launcher<MyServer> clientSideLauncher = Launcher.createLauncher(client, MyServer.class, in, out);
// create server side
MyServer server = new MyServerImpl();
MessageContextStore<MyClient> contextStore = new MessageContextStore<>();
Launcher<MyClient> serverSideLauncher = createLauncher(createBuilder(contextStore), server, MyClient.class, in2, out2);
TestContextWrapper.setMap(contextStore);
clientSideLauncher.startListening();
serverSideLauncher.startListening();
CompletableFuture<MyParam> fooFuture = clientSideLauncher.getRemoteProxy().askServer(new MyParam("FOO"));
CompletableFuture<MyParam> barFuture = serverSideLauncher.getRemoteProxy().askClient(new MyParam("BAR"));
Assert.assertEquals("FOO", fooFuture.get(TIMEOUT, TimeUnit.MILLISECONDS).value);
Assert.assertEquals("BAR", barFuture.get(TIMEOUT, TimeUnit.MILLISECONDS).value);
Assert.assertFalse(TestContextWrapper.error);
}
/**
* Creates a SshConnection mock and starts a GerritConnection with that connection-mock.
*
* @throws Exception if so.
*/
@BeforeClass
public static void setUp() throws Exception {
sshConnectionMock = mock(SshConnection.class);
when(sshConnectionMock.isAuthenticated()).thenReturn(true);
when(sshConnectionMock.isConnected()).thenReturn(true);
pipedOutStream = new PipedOutputStream();
PipedInputStream pipedInStream = new PipedInputStream(pipedOutStream);
pipedReader = new InputStreamReader(pipedInStream);
when(sshConnectionMock.executeCommand(eq("gerrit version"))).thenReturn("gerrit version 2.5.2");
when(sshConnectionMock.executeCommandReader(eq("gerrit stream-events"))).thenReturn(pipedReader);
ChannelExec channelExecMock = mock(ChannelExec.class);
when(channelExecMock.isConnected()).thenReturn(true);
when(sshConnectionMock.executeCommandChannel(eq("gerrit stream-events"))).thenReturn(channelExecMock);
when(sshConnectionMock.executeCommandChannel(eq("gerrit stream-events"), anyBoolean()))
.thenReturn(channelExecMock);
when(channelExecMock.getInputStream()).thenReturn(pipedInStream);
PowerMockito.mockStatic(SshConnectionFactory.class);
PowerMockito.doReturn(sshConnectionMock).when(SshConnectionFactory.class, "getConnection",
isA(String.class), isA(Integer.class), isA(String.class), isA(Authentication.class), any());
connection = new GerritConnection("", "localhost", 29418, new Authentication(null, ""));
connection.setSshRxBufferSize(13);
handlerMock = mock(HandlerMock.class);
connection.setHandler(handlerMock);
connection.addListener(new ListenerMock());
connection.start();
try {
establishedLatch.await();
} catch (InterruptedException e) {
System.out.println("Interrupted while sleeping.");
}
assertTrue(connection.isConnected());
assertFalse(connection.isShutdownInProgress());
}
public OutputScanner() {
PipedInputStream is = new PipedInputStream();
try {
os = new PipedOutputStream(is);
} catch (IOException e) { e.printStackTrace(); }
scanner = new Scanner(is);
}
public S3ObjectWriter(S3Client s3Client, String bucketName, String key, ObjectMetadata metadata) throws IOException {
this.s3Client = s3Client;
this.bucketName = bucketName;
this.key = key;
this.metadata = metadata;
pipedOutput = new PipedOutputStream() ;
pipedInput = new PipedInputStream(pipedOutput);
writeThread = new WriteThread() ;
writeThread.start();
}
@Test public void shouldNotHaveExpiredTimeoutWhenCompleted() throws Exception {
PipedOutputStream output = new PipedOutputStream();
InputStream inputStream = new PipedInputStream(output);
TestingClock clock = new TestingClock();
StreamPumper pumper = new StreamPumper(inputStream, new TestConsumer(), "", "utf-8", clock);
new Thread(pumper).start();
output.write("line1\n".getBytes());
output.flush();
output.close();
pumper.readToEnd();
clock.addSeconds(2);
assertThat(pumper.didTimeout(1L, TimeUnit.SECONDS), is(false));
}
@Before
public void setup() throws Exception {
readThreadActive = new AtomicBoolean(true);
threads = new ArrayList<>();
queue = new ArrayBlockingQueue<>(1);
consoleInput = new PipedInputStream(bufferSize);
consoleWriter = new PrintWriter(new PipedOutputStream(consoleInput));
consoleOutput = new PipedOutputStream();
consoleInputStream = new PipedInputStream(consoleOutput, bufferSize);
consoleReader = new InputStreamReader(consoleInputStream);
sb = new StringBuilder();
// tests can manipulate with jboss.cli.config system property thus we need keep have original value so
// it can be restored in @After phase
originalCliConfig = WildFlySecurityManager.getPropertyPrivileged("jboss.cli.config", "");
}
@Test
public void testRedirectPipedInputStream() throws Exception {
// Setup InputStream that will block on a read()
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ProcessExecutor exec = new ProcessExecutor("java", "-cp", "target/test-classes", PrintArguments.class.getName());
exec.redirectInput(pis);
StartedProcess startedProcess = exec.start();
// Assert that we don't get a TimeoutException
startedProcess.getFuture().get(5, TimeUnit.SECONDS);
}
private static Socket[] setUpLoppbackSockets() throws IOException {
Socket[] sockets = new Socket[2];
PipedInputStream in1 = new PipedInputStream();
PipedOutputStream out1 = new PipedOutputStream(in1);
PipedInputStream in2 = new PipedInputStream();
PipedOutputStream out2 = new PipedOutputStream(in2);
sockets[0] = new LoopbackSocket(out1, in2);
sockets[1] = new LoopbackSocket(out2, in1);
return sockets;
}