Example usage for java.io InputStream InputStream

List of usage examples for java.io InputStream InputStream

Introduction

In this page you can find the example usage for java.io InputStream InputStream.

Prototype

InputStream

Source Link

Usage

From source file:com.adaptris.core.MarshallingBaseCase.java

public void testUnmarshalFromInputStream_WithException() throws Exception {
    AdaptrisMarshaller marshaller = createMarshaller();
    Adapter adapter = createMarshallingObject();
    String s = marshaller.marshal(adapter);
    InputStream fail = new InputStream() {
        @Override//w w w .j  a v  a  2s  . c  om
        public int read() throws IOException {
            throw new IOException("testUnmarshalFromInputStream_WithException");
        }
    };
    try (InputStream in = fail) {
        Adapter adapter2 = (Adapter) marshaller.unmarshal(in);
        fail();
    } catch (CoreException e) {
        assertNotNull(e.getCause());
        assertRootCause("testUnmarshalFromInputStream_WithException", e);
    }
}

From source file:com.proofpoint.jaxrs.AbstractMapperTest.java

@Test
public void testJsonProcessingExceptionThrowsJsonMapperParsingException() throws IOException {
    try {/*  w  w  w . j  a va2  s.c  o  m*/
        mapper.readFrom(Object.class, Object.class, null, null, null, new InputStream() {
            @Override
            public int read() throws IOException {
                throw new TestingJsonProcessingException("forced JsonProcessingException");
            }

            @Override
            public int read(byte[] b) throws IOException {
                throw new TestingJsonProcessingException("forced JsonProcessingException");
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                throw new TestingJsonProcessingException("forced JsonProcessingException");
            }
        });
        fail("Should have thrown a JsonMapperParsingException");
    } catch (JsonMapperParsingException e) {
        Assert.assertTrue((e.getMessage()).startsWith("Invalid json for Java type"));
    }
}

From source file:org.apache.ant.compress.resources.SevenZResource.java

/**
 * Return an InputStream for reading the contents of this Resource.
 * @return an InputStream object.//from  ww  w  . java2  s.  c  om
 * @throws IOException if the sevenz file cannot be opened,
 *         or the entry cannot be read.
 */
public InputStream getInputStream() throws IOException {
    if (isReference()) {
        return ((Resource) getCheckedRef()).getInputStream();
    }
    File f = getSevenZFile();
    if (f == null) {
        return super.getInputStream();
    }

    final SevenZFile z = new SevenZFile(f);
    SevenZArchiveEntry ze = z.getNextEntry();
    while (ze != null) {
        if (ze.getName().equals(getName())) {
            return new InputStream() {
                public int read() throws IOException {
                    return z.read();
                }

                public int read(byte[] b) throws IOException {
                    return z.read(b);
                }

                public void close() throws IOException {
                    z.close();
                }

                protected void finalize() throws Throwable {
                    try {
                        close();
                    } finally {
                        super.finalize();
                    }
                }
            };
        }
        ze = z.getNextEntry();
    }
    z.close();
    throw new BuildException("no entry " + getName() + " in " + getArchive());
}

From source file:org.commoncrawl.service.queryserver.index.PositionBasedSequenceFileIndex.java

private static InputStream newInputStream(final ByteBuffer buf) {
    return new InputStream() {
        public synchronized int read() throws IOException {
            if (!buf.hasRemaining()) {
                LOG.error("EOF REACHED in Wrapper Stream!");
                return -1;
            }//w  ww .j  av a2  s .c o m
            return buf.get() & 0xff;
        }

        public synchronized int read(byte[] bytes, int off, int len) throws IOException {
            // Read only what's left
            len = Math.min(len, buf.remaining());
            buf.get(bytes, off, len);
            return len;
        }
    };
}

From source file:io.airlift.jaxrs.TestJsonMapper.java

@Test
public void testJsonProcessingExceptionThrowsJsonMapperParsingException() throws IOException {
    try {//from   w  ww.  j  av  a2 s.  c  o  m
        JsonMapper jsonMapper = new JsonMapper(new ObjectMapper());
        jsonMapper.readFrom(Object.class, Object.class, null, null, null, new InputStream() {
            @Override
            public int read() throws IOException {
                throw new TestingJsonProcessingException("forced JsonProcessingException");
            }

            @Override
            public int read(byte[] b) throws IOException {
                throw new TestingJsonProcessingException("forced JsonProcessingException");
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                throw new TestingJsonProcessingException("forced JsonProcessingException");
            }
        });
        Assert.fail("Should have thrown a JsonMapperParsingException");
    } catch (JsonMapperParsingException e) {
        Assert.assertTrue((e.getMessage()).startsWith("Invalid json for Java type"));
    }
}

From source file:com.nextcloud.android.sso.InputStreamBinder.java

public ParcelFileDescriptor performNextcloudRequest(ParcelFileDescriptor input) {
    // read the input
    final InputStream is = new ParcelFileDescriptor.AutoCloseInputStream(input);

    Exception exception = null;//from  ww w . j av  a  2  s  . c  om
    InputStream httpStream = new InputStream() {
        @Override
        public int read() {
            return 0;
        }
    };
    try {
        // Start request and catch exceptions
        NextcloudRequest request = deserializeObjectAndCloseStream(is);
        httpStream = processRequest(request);
    } catch (Exception e) {
        Log_OC.e(TAG, e.getMessage());
        exception = e;
    }

    try {
        // Write exception to the stream followed by the actual network stream
        InputStream exceptionStream = serializeObjectToInputStream(exception);
        InputStream resultStream = new java.io.SequenceInputStream(exceptionStream, httpStream);
        return ParcelFileDescriptorUtil.pipeFrom(resultStream, thread -> Log.d(TAG, "Done sending result"));
    } catch (IOException e) {
        Log_OC.e(TAG, e.getMessage());
    }
    return null;
}

From source file:org.talend.mdm.bulkload.client.BulkloadClientTest.java

public void testInterruptedBulkLoad() throws Exception {
    String serverURL = "http://localhost:8180/talendmdm/services/bulkload";
    boolean isServerRunning = isServerRunning(serverURL);
    if (isServerRunning) {
        final InterruptedTestResult result = new InterruptedTestResult();
        BulkloadClient client = new BulkloadClient(serverURL, "administrator", "administrator", null, "Product",
                "Product", "Product");
        client.setOptions(new BulkloadOptions());

        int count = 10;
        InputStream bin = new InputStream() {

            @Override/*w  w w.  jav a 2s .com*/
            public synchronized int read() throws IOException {
                try {
                    Thread.sleep(RandomUtils.nextInt(5000));
                    synchronized (result) {
                        result.setSuccess(true);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return -1;
            }
        };
        for (int i = 0; i < count; i++) {
            InputStreamMerger manager = client.load();
            manager.push(bin);
            manager.close();
        }

        // client.waitForEndOfQueue();
        synchronized (result) {
            assertEquals(count, result.getSuccessCount());
            assertTrue(result.isSuccess());
        }
    }
}

From source file:netinf.node.transferdispatcher.streamprovider.HTTPStreamProvider.java

@Override
public InputStream getStream(Chunk chunk, String chunkUrl) throws IOException {
    // determine range
    int chunkSizeInBytes = 256 * 1024;
    int from = chunkSizeInBytes * chunk.getNumber();
    int to = (chunkSizeInBytes * (chunk.getNumber() + 1)) - 1;

    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(chunkUrl);
    httpGet.setHeader("Range", "bytes=" + from + "-" + to);
    try {/*w w  w  .  j  ava2 s.  c  o  m*/
        HttpResponse response = client.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_PARTIAL_CONTENT) {

            InputStream inStream = response.getEntity().getContent();
            // check integrity
            String destination = Utils.getTmpFolder("chunkproviding") + File.separator + chunk.getHash()
                    + ".tmp";
            boolean success = Utils.saveTemp(inStream, destination);

            if (success) {
                if (Utils.isValidHash(chunk.getHash(), destination)) {
                    return new FileInputStream(destination);
                } else {
                    throw new IOException("Hash of chunk no. " + chunk.getNumber() + " is NOT valid...");
                }
            }

        } else {
            throw new IOException("Error at ranges request... status: " + status);
        }
    } catch (ClientProtocolException e) {
        throw new IOException("Error at ranges request...");
    } catch (IOException e) {
        throw new IOException("Error at ranges request...: ");
    }

    return new InputStream() {
        @Override
        public int read() throws IOException {
            LOG.warn("(HTTPStreamProvider ) returning an error stream (-1)");
            return -1;
        }
    };
}

From source file:org.apache.myfaces.custom.fileupload.HtmlFileUploadRendererTest.java

public void testUploadedFileDefaultMemoryImplSerializable() throws Exception {
    String fieldName = "inputFile";
    String contentType = "someType";

    MockControl control = MockControl.createControl(FileItem.class);
    FileItem item = (FileItem) control.getMock();

    item.getName();// w w  w  .  j av  a  2 s  .c  o  m
    control.setReturnValue(fieldName, 1);
    item.getContentType();
    control.setReturnValue(contentType, 1);
    item.getSize();
    control.setReturnValue(0, 1);
    item.getInputStream();
    control.setReturnValue(new InputStream() {
        public int read() throws IOException {
            return -1;
        }
    }, 1);

    item.delete();
    control.setVoidCallable(1);

    control.replay();

    UploadedFileDefaultMemoryImpl original = new UploadedFileDefaultMemoryImpl(item);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(original);
    oos.close();

    byte[] serializedArray = out.toByteArray();
    InputStream in = new ByteArrayInputStream(serializedArray);
    ObjectInputStream ois = new ObjectInputStream(in);
    UploadedFileDefaultMemoryImpl copy = (UploadedFileDefaultMemoryImpl) ois.readObject();

    assertEquals(original.getName(), copy.getName());
    assertEquals(original.getContentType(), copy.getContentType());
    assertEquals(copy.getSize(), 0);

    copy.getStorageStrategy().deleteFileContents();
}

From source file:org.apache.jackrabbit.oak.spi.blob.AbstractBlobStoreTest.java

@Test
public void testCloseStream() throws Exception {
    final AtomicBoolean closed = new AtomicBoolean();
    InputStream in = new InputStream() {
        @Override/*from  w w  w  .  j a  va  2 s . c om*/
        public void close() {
            closed.set(true);
        }

        @Override
        public int read() throws IOException {
            return -1;
        }
    };
    store.writeBlob(in);
    assertTrue(closed.get());
}