@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()); }
private void tupleWriter(PipedOutputStream pipeOut, Set<String> tuples) throws BiremeException { byte[] data = null; try { Iterator<String> iterator = tuples.iterator(); while (iterator.hasNext() && !cxt.stop) { data = iterator.next().getBytes("UTF-8"); pipeOut.write(data); } pipeOut.flush(); } catch (IOException e) { throw new BiremeException("I/O error occurs while write to pipe.", e); } finally { try { pipeOut.close(); } catch (IOException ignore) { } } }
@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 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(); }
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); PrintStream oldErr = System.err; System.setErr(new PrintStream(pipeOut)); try { jmx.printAllValues(); if ((size = pipeIn.available()) != 0) { bytes = new byte[size]; pipeIn.read(bytes, 0, bytes.length); } pipeOut.close(); pipeIn.close(); } finally { System.setErr(oldErr); } return bytes != null ? new String(bytes).contains(pattern) : false; }
@Test public void readsResourceFromInputStreamTest() { InputStreamResource resource = new InputStreamResource() { @Override public InputStream resourceStream() throws IOException { PipedOutputStream outputStream = new PipedOutputStream(); PipedInputStream inputStream = new PipedInputStream(outputStream); PrintStream printer = new PrintStream(outputStream); printer.print("Lorem ipsum doler sit amet"); printer.close(); return inputStream; } }; Assert.assertEquals("Lorem ipsum doler sit amet", resource.resourceText()); }
/** * Default constructor * * @param account JOSS account object * @param url URL connection * @param targetContentType Content type * @param metadata input metadata * @param connectionManager SwiftConnectionManager */ public SwiftOutputStream( JossAccount account, URL url, final String targetContentType, Map<String, String> metadata, SwiftConnectionManager connectionManager ) { mUrl = url; mAccount = account; client = connectionManager.createHttpConnection(); contentType = targetContentType; pipOutStream = new PipedOutputStream(); bufOutStream = new BufferedOutputStream(pipOutStream, Constants.SWIFT_DATA_BUFFER); // Append the headers to the request request = new HttpPut(mUrl.toString()); request.addHeader("X-Auth-Token", account.getAuthToken()); if (metadata != null && !metadata.isEmpty()) { for (Map.Entry<String, String> entry : metadata.entrySet()) { request.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue()); } } }
/** * Проверим выходные данные метода 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 OutputHandle list() { try { StringBuilder sb = new StringBuilder(); sb.append(getOperationUrl()) .append(Q).append(FILTERS).append(EQUALS).append(JSON_MAPPER.writeValueAsString(filters)); if (Utils.isNotNullOrEmpty(since)) { sb.append(A).append(SINCE).append(EQUALS).append(since); } if (Utils.isNotNullOrEmpty(until)) { sb.append(A).append(UNTIL).append(EQUALS).append(until); } Request request = new Request.Builder().get().url(sb.toString()).build(); OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build(); EventHandle handle = new EventHandle(new PipedOutputStream(), config.getRequestTimeout(), TimeUnit.MILLISECONDS); clone.newCall(request).enqueue(handle); return handle; } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
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; } }
@Override public void onOpen(WebSocket webSocket, Response response) { try { if (out instanceof PipedOutputStream && output != null) { output.connect((PipedOutputStream) out); } if (err instanceof PipedOutputStream && error != null) { error.connect((PipedOutputStream) err); } webSocketRef.set(webSocket); started.set(true); queue.add(true); } catch (IOException e) { queue.add(e); } }
@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(); }
/** * 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(); }
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 getPipedDumpFileStream(final InputStream inputStream) throws IOException { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream, BUFFER_SIZE); new Thread("Dump File Reader") { @Override public void run() { try { IOUtils.copy(inputStream, pipedOutputStream); inputStream.close(); pipedOutputStream.close(); } catch (Throwable t) { logger.error("", t); } } }.start(); return pipedInputStream; }
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; }
/** 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); }
public StreamChunkWriter(KissVideoStreamServer server, String link, HashMap file_info, String mega_account, PipedOutputStream pipeos, String url, long start_offset, long end_offset) { _server = server; _link = link; _mega_account = mega_account; _file_info = file_info; _bytes_written = start_offset; _pipeos = pipeos; _start_offset = start_offset; _end_offset = end_offset; _next_offset_required = start_offset; _chunk_queue = new ConcurrentHashMap<>(); _notified_threads = new ConcurrentHashMap<>(); _secure_notify_lock = new Object(); _chunk_offset_lock = new Object(); _url = url; _exit = false; }
/** * 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(); }