@Test public void buildACommand() throws IOException { PipedInputStream pis = new PipedInputStream(); BufferedInputStream bis = new BufferedInputStream(pis); PipedOutputStream pos = new PipedOutputStream(pis); RedisOutputStream ros = new RedisOutputStream(pos); Protocol.sendCommand(ros, Protocol.Command.GET, "SOMEKEY".getBytes(Protocol.CHARSET)); ros.flush(); pos.close(); String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; int b; StringBuilder sb = new StringBuilder(); while ((b = bis.read()) != -1) { sb.append((char) b); } assertEquals(expectedCommand, sb.toString()); }
public InputStream getInputStream() throws IOException { int max_input_buffer_size = 32*1024; try { max_input_buffer_size = Integer.parseInt(getSession().getConfig("max_input_buffer_size")); } catch(Exception e){} PipedInputStream in = new MyPipedInputStream( 32*1024, // this value should be customizable. max_input_buffer_size ); boolean resizable = 32*1024<max_input_buffer_size; io.setOutputStream(new PassiveOutputStream(in, resizable), false); return in; }
public InputStream getExtInputStream() throws IOException { int max_input_buffer_size = 32*1024; try { max_input_buffer_size = Integer.parseInt(getSession().getConfig("max_input_buffer_size")); } catch(Exception e){} PipedInputStream in = new MyPipedInputStream( 32*1024, // this value should be customizable. max_input_buffer_size ); boolean resizable = 32*1024<max_input_buffer_size; io.setExtOutputStream(new PassiveOutputStream(in, resizable), false); return in; }
@Test public void testEntityMarshallingWithGZIP() throws Exception { for (int numDataPoints = 1; numDataPoints <= 10; numDataPoints++) { ArrayList<DataPoint> dataPoints = createDataPoints(numDataPoints); DatapointsHttpEntity entity = new DatapointsHttpEntity(dataPoints, globalTags, true); PipedInputStream pis = new PipedInputStream(); entity.writeTo(new PipedOutputStream(pis)); String jsonText = streamToString(pis); DataPoint[] unmarshalledDPs = Util.jsonToDataPoints(jsonText); assertEquals(numDataPoints, unmarshalledDPs.length); for (int i = 0; i < numDataPoints; i++) { assertEquals(getExpectedDataPoint(dataPoints.get(i), globalTags), unmarshalledDPs[i]); } } }
@Test public void getHelloFromServerTest() throws IOException{ //preparing remote connection Socket First parameter for ArticlePuller //and pipeline fot testing PipedInputStream inForOut = new PipedInputStream(); PipedOutputStream outForIn = new PipedOutputStream(); BufferedReader rIn = new BufferedReader(new InputStreamReader(inForOut, "UTF-8")); PrintWriter rOut = new PrintWriter(new OutputStreamWriter(outForIn, "UTF-8")); when(rSocket.getOutputStream()).thenReturn(new PipedOutputStream(inForOut)); when(rSocket.getInputStream()).thenReturn(new PipedInputStream(outForIn)); rOut.println("200 hello"); rOut.flush(); Socket socket = FeedManager.getHelloFromServer(rSocket, false, "testhost", Charset.forName("UTF-8")); assertTrue (socket != null); }
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(); }
private static boolean checkPrintAllValues(JMXGet jmx) throws Exception { int size = 0; byte[] bytes = null; String pattern = "List of all the available keys:"; PipedOutputStream pipeOut = new PipedOutputStream(); PipedInputStream pipeIn = new PipedInputStream(pipeOut); System.setErr(new PrintStream(pipeOut)); jmx.printAllValues(); if ((size = pipeIn.available()) != 0) { bytes = new byte[size]; pipeIn.read(bytes, 0, bytes.length); } pipeOut.close(); pipeIn.close(); return bytes != null ? new String(bytes).contains(pattern) : false; }
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); }
public static void main(String[] args) { /** * 流程 * 1 建立输入输出流 * 2 绑定输入输出流 * 3 向缓冲区写数据 * 4 读取缓冲区数据 */ PipedOutputStream out = new PipedOutputStream(); PipedInputStream in = new PipedInputStream(); Producer producer = new Producer(out); Consumer consumer = new Consumer(in); try { out.connect(in); producer.start(); consumer.start(); } catch (IOException e) { e.printStackTrace(); } }
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); int rc = JAR_TOOL.run(out, System.err, jarArgs); if (rc != 0) { 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); int rc = JAR_TOOL.run(out, System.err, jarArgs); if (rc != 0) { fail("Could not list jar file."); } out.flush(); check(pipedInput.available() > 0); }
@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"); 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(); verifyResponse(pis, "test run bob"); pis.close(); pos.close(); channel.disconnect(); session.disconnect(); }
protected void sshCall(String username, String password, SshExecutor executor, String channelType) { try { JSch jsch = new JSch(); Session session = jsch.getSession(username, props.getShell().getHost(), props.getShell().getPort()); session.setPassword(password); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel(channelType); PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); channel.setInputStream(new PipedInputStream(pos)); channel.setOutputStream(new PipedOutputStream(pis)); channel.connect(); try { executor.execute(pis, pos); } finally { pis.close(); pos.close(); channel.disconnect(); session.disconnect(); } } catch(JSchException | IOException ex) { fail(ex.toString()); } }
public void setup(AbstractCliArgs args, Mic m, MixingOutput player, int frameSamples) throws IOException { bufferSize=frameSamples*2; int pipeSize=(Math.abs(nLate)+100)*bufferSize; play=new PipedInputStream(pipeSize); play.connect(playSink); rec=new PipedInputStream(pipeSize); rec.connect(recSink); Process p=new ProcessBuilder(args.program_speexcmd, "cancelecho", ""+frameSamples, ""+(int)StreamSourceAudio.getFormat().getFrameRate()).start(); speexInputMic=p.getOutputStream(); speexInputMonitor=p.getOutputStream(); speexOutput=p.getInputStream(); SpeexResampler.checkSpeexCmdVersion(p, speexOutput); if(log) { speexInputMic=new TeeOutputStream(new OutputStream[]{speexInputMic, new FileOutputStream("/tmp/mic.sw")}); speexInputMonitor=new TeeOutputStream(new OutputStream[]{speexInputMonitor, new FileOutputStream("/tmp/monitor.sw")}); } ConnectStreams.startStreamThread(p.getErrorStream(), System.err); player.setSpeexCopy(playSink); m.setSpeexCopy(recSink); System.out.println("Speex buffer size: "+bufferSize); }
public void setup(Mic m, Play player, int frameSamples) throws IOException { bufferSize=frameSamples*2; int pipeSize=(Math.abs(nLate)+100)*bufferSize; play=new PipedInputStream(pipeSize); play.connect(playSink); rec=new PipedInputStream(pipeSize); rec.connect(recSink); Process p; p=Runtime.getRuntime().exec("/home/rizsi/github/rcom/speexexample/a.out"); speexInputMic=p.getOutputStream(); speexInputMonitor=p.getOutputStream(); speexOutput=p.getInputStream(); if(log) { speexInputMic=new TeeOutputStream(new OutputStream[]{speexInputMic, new FileOutputStream("/tmp/mic.sw")}); speexInputMonitor=new TeeOutputStream(new OutputStream[]{speexInputMonitor, new FileOutputStream("/tmp/monitor.sw")}); } ConnectStreams.startStreamThread(p.getErrorStream(), System.err); player.setSpeexCopy(playSink); m.setSpeexCopy(recSink); System.out.println("Speex buffer size: "+bufferSize); }
public static DataNetSocketPair createDataNetSocketPair() throws IOException { final DataNetSocketPair result = new DataNetSocketPair(); // create stream from higher layer final PipedInputStream fromHigherLayerIS = new PipedInputStream(); final PipedOutputStream fromHigherLayerOS = new PipedOutputStream( fromHigherLayerIS); // stream to higher layer final PipedInputStream toHigherLayerIS = new PipedInputStream(); final PipedOutputStream toHigherLayerOS = new PipedOutputStream( toHigherLayerIS); // create socket provided to higher layer result.setSocket(new DataNetSocketImpl(toHigherLayerIS, fromHigherLayerOS)); result.setInvertedSocked(new DataNetSocketImpl(fromHigherLayerIS, toHigherLayerOS)); return result; }
TCPStreamOutputStream(final TCPStream stream) { this.stream = stream; buffer = new byte[CellRelay.RELAY_DATA_SIZE]; bufferFilled = 0; try { sout = new PipedOutputStream(); fromjava = new PipedInputStream(sout); } catch (final IOException e) { LOG.error("TCPStreamThreadJava2Tor: caught IOException " + e.getMessage(), e); } }
@Test public void runInteractive() throws IOException, InterruptedException { when(opts.isInteractive()).thenReturn(true); PipedOutputStream out = new PipedOutputStream(); OutputStreamWriter writter = new OutputStreamWriter(out); PipedInputStream in = new PipedInputStream(out); final AtomicInteger mutableInt = new AtomicInteger(Main.ERROR); main.setIn(in); Thread t = new Thread(() -> mutableInt.set(main.run())); t.start(); writter.write(System.lineSeparator()); writter.close(); t.join(20000); assertThat(mutableInt.get()).isEqualTo(Main.SUCCESS); verify(sonarLint, times(1)).stop(); verify(sonarLint, times(2)).runAnalysis(anyMapOf(String.class, String.class), eq(reportFactory), eq(fileFinder), any(Path.class)); }
protected void verifyJobName(String jobId, String name, 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 = null; while ((line = br.readLine()) != null) { LOG.info("line = " + line); if (!line.contains(jobId)) { continue; } assertTrue(line.contains(name)); break; } pis.close(); }
public GtpEngineConnection(GtpEngine engine) throws IOException, GtpError { PipedInputStream gtpInput = new PipedInputStream(); final OutputStream out = new PipedOutputStream(gtpInput); final PipedInputStream in = new PipedInputStream(); PipedOutputStream gtpOutput = new PipedOutputStream(in); m_engine = engine; Thread thread = new Thread() { public void run() { try { m_engine.mainLoop(in, out); } catch (IOException e) { } } }; thread.start(); m_gtp = new GtpClient(gtpInput, gtpOutput, false, null); }
/** * Проверим выходные данные метода readParam(String message) */ @Test public void testReadParamOutput() throws IOException { //assign InputStream is = System.in; PrintStream ps = System.out; PipedInputStream pin = new PipedInputStream(); PipedOutputStream pout = new PipedOutputStream(pin); InputStream bis = new ByteArrayInputStream("\n".getBytes()); System.setIn(bis); System.setOut(new PrintStream(pout)); Input input = new Input(); byte[] b = new byte[1000]; String result; //action input.readParam("print message"); pin.read(b); result = new String(b).trim(); System.setIn(is); System.setOut(ps); //assert assertArrayEquals("print message".getBytes(),result.getBytes()); }
@Override public InputStream getInputStream() throws IOException { final PipedInputStream pin = new PipedInputStream(); final PipedOutputStream pout = new PipedOutputStream(pin); new Thread() { @Override public void run() { try { BarTransformer.transform(barXmlURL, pout); } catch (Exception e) { LOGGER.warn("Bundle cannot be generated"); } finally { try { pout.close(); } catch (IOException ignore) { // if we get here something is very wrong LOGGER.error("Bundle cannot be generated", ignore); } } } }.start(); return pin; }
public EventHandle(OutputStream out, long timeoutMillis, EventListener listener) { this.out = out; this.timeoutMillis = timeoutMillis; this.listener = listener; if (out instanceof PipedOutputStream) { try { this.pin = new PipedInputStream(); this.pin.connect((PipedOutputStream) out); } catch (IOException e) { throw DockerClientException.launderThrowable(e); } } else { pin = null; } }
private static OutputStream getPipedOutputStreamStream( final OutputStream outputStream) throws IOException { final int BUFFER_SIZE = 1 * 1024 * 1024; final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream, BUFFER_SIZE); new Thread("Label Writer Output Stream") { @Override public void run() { try { IOUtils.copy(pipedInputStream, outputStream); pipedInputStream.close(); outputStream.close(); } catch (Throwable t) { logger.error("", t); } } }.start(); return pipedOutputStream; }
private static InputStream getUncompressedStream( final InputStream inputStream) throws IOException { // the decompression is a major bottleneck, make sure that it does not // have to wait for the buffer to empty final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream, BUFFER_SIZE); new Thread("Dump File Decompressor") { @Override public void run() { try { InputStream compressorInputStream = new BZip2CompressorInputStream(inputStream); IOUtils.copy(compressorInputStream, pipedOutputStream); compressorInputStream.close(); pipedOutputStream.close(); } catch (IOException e) { logger.error("", e); } } }.start(); return pipedInputStream; }
@Before public void setup() throws IOException { socket = mock(Socket.class); serverInput = new ByteArrayOutputStream(); serverOutput = new PipedOutputStream(); PipedInputStream pipedServerOutput = new PipedInputStream(serverOutput); when(socket.getOutputStream()).thenReturn(serverInput); when(socket.getInputStream()).thenReturn(pipedServerOutput); when(socket.isConnected()).thenReturn(true); client = new StratumClient("not used", 1234) { @Override protected Socket createSocket() { return CommunicationsTest.this.socket; } }; }
/** Create a StretchedAudioInputStream that distorts the incoming * audio so it matches a fixed number of frames. * * @param in the AudioInputStream to stretch. * @param frames the number of frames the input stream should be stretched to. * @throws IOException if an IO problem occurs. */ public static StretchedAudioInputStream create(AudioInputStream in,long frames) throws IOException { AudioFormat format = in.getFormat(); if(!(format.getEncoding().equals(Encoding.PCM_SIGNED) || format.getEncoding().equals(Encoding.PCM_UNSIGNED) )) throw new IllegalArgumentException("the audio input must be PCM-encoded data (found "+format.getEncoding()+")"); PipedInputStream pipedIn = new PipedInputStream(); PipedOutputStream pipedOut = new PipedOutputStream(pipedIn); /** One flaw with this model is that we always generate ALL the * transformed data: even if the entity working with pipedIn * is trying to skip large chunks of data. */ Thread thread = new StretchThread(in, format, frames, pipedOut); thread.start(); return new StretchedAudioInputStream( pipedIn, format, frames); }
/** * 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(); }
@Test public void canHandleDataNotAlreadyPresentSeparatedByNewline() throws Exception { List<String> expected = Arrays.asList("a", "b", "c"); PipedOutputStream os = new PipedOutputStream(); PipedInputStream is = new PipedInputStream(os); StreamReader reader = process(is, "\n", expected); TimeUnit.SECONDS.sleep(2); os.write("a\nb\nc\n".getBytes()); waitUntil(expected.size()); assertThat(received, is(expected)); reader.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(); }
@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 = LSPLauncher.createServerLauncher(ServiceEndpoints.toServiceObject(server, LanguageServer.class), inServer, outServer); serverListening = serverLauncher.startListening(); client = new AssertingEndpoint(); clientLauncher = LSPLauncher.createClientLauncher(ServiceEndpoints.toServiceObject(client, LanguageClient.class), inClient, outClient); clientListening = clientLauncher.startListening(); }