List of usage examples for java.io InputStream InputStream
InputStream
From source file:org.mule.transport.sftp.AbstractSftpTestCase.java
/** Base method for executing tests... */ protected void executeBaseTest(String inputEndpointName, String sendUrl, String filename, final int size, String receivingTestComponentName, long timeout, String expectedFailingConnector, String serviceName) throws Exception { MuleClient client = new MuleClient(muleContext); // Do some cleaning so that the endpoint doesn't have any other files // We don't need to do this anymore since we are deleting and then creating // the directory for each test // cleanupRemoteFtpDirectory(client, inputEndpointName); final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger loopCount = new AtomicInteger(0); final AtomicInteger totalReceivedSize = new AtomicInteger(0); // Random byte that we want to send a lot of final int testByte = 42; EventCallback callback = new EventCallback() { @Override/*from w ww .jav a 2s .c o m*/ public void eventReceived(MuleEventContext context, Object component) throws Exception { if (logger.isInfoEnabled()) logger.info("called " + loopCount.incrementAndGet() + " times"); InputStream sftpInputStream = (InputStream) context.getMessage().getPayload(); BufferedInputStream bif = new BufferedInputStream(sftpInputStream); byte[] buffer = new byte[1024 * 4]; try { int n; while (-1 != (n = bif.read(buffer))) { totalReceivedSize.addAndGet(n); // Simple check to verify the data... for (byte b : buffer) { if (b != testByte) { fail("Incorrect received byte (was '" + b + "', expected '" + testByte + "'"); } } } } finally { bif.close(); } latch.countDown(); } }; getFunctionalTestComponent(receivingTestComponentName).setEventCallback(callback); final ValueHolder<Exception> exceptionHolder = new ValueHolder<Exception>(); if (expectedFailingConnector != null) { // Register an exception-listener on the connector that expects to fail // and count down the latch after saving the thrown exception muleContext.setExceptionListener(new SystemExceptionHandler() { @Override public void handleException(Exception e, RollbackSourceCallback rollbackMethod) { if (logger.isInfoEnabled()) logger.info("expected exception occurred: " + e, e); exceptionHolder.value = e; latch.countDown(); } @Override public void handleException(Exception exception) { handleException(exception, null); } }); if (serviceName != null && !(serviceName.length() == 0)) { muleContext.getRegistry().lookupService(serviceName) .setExceptionListener(new MessagingExceptionHandler() { @Override public MuleEvent handleException(Exception e, MuleEvent event) { if (logger.isInfoEnabled()) logger.info("expected exception occurred: " + e, e); exceptionHolder.value = e; latch.countDown(); return event; } }); } } // InputStream that generates the data without using a file InputStream os = new InputStream() { int totSize = 0; @Override public int read() throws IOException { totSize++; if (totSize <= size) { return testByte; } else { return -1; } } }; HashMap<String, String> props = new HashMap<String, String>(1); props.put(SftpConnector.PROPERTY_FILENAME, filename); props.put(SftpConnector.PROPERTY_ORIGINAL_FILENAME, filename); if (logger.isInfoEnabled()) logger.info(StringMessageUtils.getBoilerPlate( "Note! If this test fails due to timeout please add '-Dmule.test.timeoutSecs=XX' to the mvn command!")); executeBaseAssertionsBeforeCall(); // Send the content using stream client.dispatch(sendUrl, os, props); boolean workDone = latch.await(timeout, TimeUnit.MILLISECONDS); assertTrue("Test timed out. It took more than " + timeout + " milliseconds. If this error occurs the test probably needs a longer time out (on your computer/network)", workDone); // Rethrow any exception that we have caught in an exception-listener if (exceptionHolder.value != null) { throw exceptionHolder.value; } executeBaseAssertionsAfterCall(size, totalReceivedSize.intValue()); }
From source file:com.socialize.test.unit.DefaultSocializeProviderTest.java
public void testGet() throws Exception { final String id = "foo"; final String endpoint = "foobar/"; final String host = "host"; final String url = "http://" + host + "/" + endpoint; final SocializeObject object = new SocializeObject(); final InputStream in = new InputStream() { @Override/*w w w . j av a 2s .c o m*/ public int read() throws IOException { return -1; } }; AndroidMock.expect(clientFactory.isDestroyed()).andReturn(false); AndroidMock.expect(clientFactory.getClient()).andReturn(client); AndroidMock.expect(requestFactory.getGetRequest(session, url, id)).andReturn(request); AndroidMock.expect(client.execute(request)).andReturn(response); AndroidMock.expect(response.getEntity()).andReturn(entity); AndroidMock.expect(entity.getContent()).andReturn(in); AndroidMock.expect(ioUtils.readSafe(in)).andReturn(null); AndroidMock.expect(jsonParser.parseObject((String) null)).andReturn(json); AndroidMock.expect(objectFactory.fromJSON(json)).andReturn(object); AndroidMock.expect(httpUtils.isHttpError(response)).andReturn(false); AndroidMock.expect(session.getHost()).andReturn(host); entity.consumeContent(); AndroidMock.replay(session); AndroidMock.replay(sessionFactory); AndroidMock.replay(clientFactory); AndroidMock.replay(objectFactory); AndroidMock.replay(requestFactory); AndroidMock.replay(jsonParser); AndroidMock.replay(client); AndroidMock.replay(json); AndroidMock.replay(userFactory); AndroidMock.replay(entity); AndroidMock.replay(response); AndroidMock.replay(httpUtils); DefaultSocializeProvider<SocializeObject> provider = getNewProvider(); SocializeObject gotten = provider.get(session, endpoint, id); AndroidMock.verify(session); AndroidMock.verify(sessionFactory); AndroidMock.verify(clientFactory); AndroidMock.verify(requestFactory); AndroidMock.verify(jsonParser); AndroidMock.verify(client); AndroidMock.verify(json); AndroidMock.verify(userFactory); AndroidMock.verify(entity); AndroidMock.verify(response); AndroidMock.verify(objectFactory); AndroidMock.verify(httpUtils); assertSame(object, gotten); }
From source file:com.twitter.common.thrift.text.TTextProtocol.java
/** * Set up the stream parser to read from the trans_ TTransport * buffer./* w w w. j a va2 s . c o m*/ */ private JsonStreamParser createParser() throws IOException { return new JsonStreamParser(new String(ByteStreams.toByteArray(new InputStream() { private int index; private int max; private final byte[] buffer = new byte[READ_BUFFER_SIZE]; @Override public int read() throws IOException { if (max == -1) { return -1; } if (max > 0 && index < max) { return buffer[index++]; } try { max = trans_.read(buffer, 0, READ_BUFFER_SIZE); index = 0; } catch (TTransportException e) { if (TTransportException.END_OF_FILE != e.getType()) { throw new IOException(e); } max = -1; } return read(); } }), Charsets.UTF_8)); }
From source file:org.apache.solr.common.util.TestJavaBinCodec.java
public static int doDecode(byte[][] buffers, long iter, JavaBinCodec.StringCache stringCache) throws IOException { int ret = 0;/*w ww. j a va 2 s . c o m*/ int bufnum = -1; InputStream empty = new InputStream() { @Override public int read() throws IOException { return -1; } }; while (--iter >= 0) { if (++bufnum >= buffers.length) bufnum = 0; byte[] buf = buffers[bufnum]; JavaBinCodec javabin = new JavaBinCodec(null, stringCache); FastInputStream in = new FastInputStream(empty, buf, 0, buf.length); Object o = javabin.unmarshal(in); if (o instanceof SolrDocument) { ret += ((SolrDocument) o).size(); } } return ret; }
From source file:eu.stratosphere.nephele.fs.s3.S3FileSystem.java
private void createEmptyObject(final String bucketName, final String objectName) { final InputStream im = new InputStream() { @Override// w w w .j a va 2 s .c o m public int read() throws IOException { return -1; } }; final ObjectMetadata om = new ObjectMetadata(); om.setContentLength(0L); this.s3Client.putObject(bucketName, objectName, im, om); }
From source file:org.orbeon.oxf.util.NetUtils.java
public static String createTemporaryFile(int scope) { return inputStreamToAnyURI(new InputStream() { @Override// w w w . j a v a2 s. c o m public int read() { return -1; } }, scope, null); }
From source file:com.couchbase.lite.DatabaseAttachmentTest.java
public void testAttachmentThrowIoException() { InputStream in = new InputStream() { @Override// ww w. ja v a2 s.c om public int read() throws IOException { throw new IOException(); } }; Document doc = database.createDocument(); UnsavedRevision rev = doc.createRevision(); rev.setAttachment("ioe_attach", "text/plain", in); try { rev.save(); fail("Saved revision with corrupt attachment"); } catch (CouchbaseLiteException expected) { assertEquals(Status.ATTACHMENT_ERROR, expected.getCBLStatus().getCode()); } }
From source file:org.esigate.DriverTest.java
/** * 0000141: Socket read timeout causes a stacktrace and may leak connection * http://www.esigate.org/mantisbt/view.php?id=141 * //from w ww .j av a 2 s . co m * The warning will not be fixed in HttpClient but the leak is fixed. * * @throws Exception */ public void testSocketReadTimeoutWithCacheAndGzipDoesNotLeak() throws Exception { Properties properties = new Properties(); properties.put(Parameters.REMOTE_URL_BASE, "http://localhost/"); properties.put(Parameters.USE_CACHE, "true"); BasicHttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "Ok"); response.addHeader("Date", DateUtils.formatDate(new Date())); response.addHeader("Cache-control", "public, max-age=1000"); response.addHeader("Content-Encoding", "gzip"); response.setEntity(new InputStreamEntity(new InputStream() { @Override public int read() throws IOException { throw new SocketTimeoutException("Read timed out"); } }, 1000)); mockConnectionManager.setResponse(response); Driver driver = createMockDriver(properties, mockConnectionManager); request = TestUtils.createIncomingRequest("http://test.mydomain.fr/"); request.addHeader("Accept-Encoding", "gzip, deflate"); try { driver.proxy("/", request.build()); fail("We should have had a SocketTimeoutException"); } catch (HttpErrorPage e) { // That is what we expect assertEquals(HttpStatus.SC_GATEWAY_TIMEOUT, e.getHttpResponse().getStatusLine().getStatusCode()); } assertFalse("All the connections should have been closed", mockConnectionManager.isOpen()); }
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
public boolean openConnectionForReceive(final String transactionUrl, final Peer peer) throws IOException { final HttpGet get = createGet(transactionUrl + "/flow-files"); // Set uri so that it'll be used as transit uri. ((HttpCommunicationsSession) peer.getCommunicationsSession()).setDataTransferUrl(get.getURI().toString()); get.setHeader(HttpHeaders.PROTOCOL_VERSION, String.valueOf(transportProtocolVersionNegotiator.getVersion())); setHandshakeProperties(get);/*from w ww . j av a 2 s . c o m*/ final CloseableHttpResponse response = getHttpClient().execute(get); final int responseCode = response.getStatusLine().getStatusCode(); logger.debug("responseCode={}", responseCode); boolean keepItOpen = false; try { switch (responseCode) { case RESPONSE_CODE_OK: logger.debug("Server returned RESPONSE_CODE_OK, indicating there was no data."); EntityUtils.consume(response.getEntity()); return false; case RESPONSE_CODE_ACCEPTED: final InputStream httpIn = response.getEntity().getContent(); final InputStream streamCapture = new InputStream() { boolean closed = false; @Override public int read() throws IOException { if (closed) { return -1; } final int r = httpIn.read(); if (r < 0) { closed = true; logger.debug("Reached to end of input stream. Closing resources..."); stopExtendingTtl(); closeSilently(httpIn); closeSilently(response); } return r; } }; ((HttpInput) peer.getCommunicationsSession().getInput()).setInputStream(streamCapture); startExtendingTtl(transactionUrl, httpIn, response); keepItOpen = true; return true; default: try (InputStream content = response.getEntity().getContent()) { throw handleErrResponse(responseCode, content); } } } finally { if (!keepItOpen) { response.close(); } } }
From source file:org.lnicholls.galleon.util.Tools.java
public static InputStream getInputStream(File file) { try {/* www . j a v a2 s .com*/ FileChannel roChannel = new RandomAccessFile(file, "r").getChannel(); final ByteBuffer buf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel.size()); return new InputStream() { public synchronized int read() throws IOException { if (!buf.hasRemaining()) { return -1; } return buf.get(); } public synchronized int read(byte[] bytes, int off, int len) throws IOException { if (!buf.hasRemaining()) { return -1; } len = Math.min(len, buf.remaining()); buf.get(bytes, off, len); return len; } }; } catch (Exception ex) { Tools.logException(Tools.class, ex, file.getAbsolutePath()); } return null; }