Example usage for org.apache.commons.io.input NullInputStream NullInputStream

List of usage examples for org.apache.commons.io.input NullInputStream NullInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input NullInputStream NullInputStream.

Prototype

public NullInputStream(long size) 

Source Link

Document

Create an InputStream that emulates a specified size which supports marking and does not throw EOFException.

Usage

From source file:ch.cyberduck.core.io.FileBuffer.java

@Override
public synchronized int read(final byte[] chunk, final Long offset) throws IOException {
    final RandomAccessFile file = random();
    if (offset < file.length()) {
        file.seek(offset);/*from w  ww  .ja  va  2 s  .c om*/
        if (chunk.length + offset > file.length()) {
            return file.read(chunk, 0, (int) (file.length() - offset));
        } else {
            return file.read(chunk, 0, chunk.length);
        }
    } else {
        final NullInputStream nullStream = new NullInputStream(length);
        if (nullStream.available() > 0) {
            nullStream.skip(offset);
            return nullStream.read(chunk, 0, chunk.length);
        } else {
            return IOUtils.EOF;
        }
    }
}

From source file:com.talis.storage.SubmittedItemTest.java

@Test(expected = UnsupportedOperationException.class)
public void getMetadataReturnsImmutableCopy() {
    SubmittedItem submittedItem = new SubmittedItem(MediaType.TEXT_XML_TYPE, new NullInputStream(1024));
    submittedItem.getMetadata().put("KEY", "VALUE");
}

From source file:ch.cyberduck.core.s3.S3DirectoryFeature.java

@Override
public Path mkdir(final Path folder, final String region, final TransferStatus status)
        throws BackgroundException {
    if (containerService.isContainer(folder)) {
        final S3BucketCreateService service = new S3BucketCreateService(session);
        service.create(folder,//w  w  w .j  av  a  2  s  .  c  om
                StringUtils.isBlank(region) ? PreferencesFactory.get().getProperty("s3.location") : region);
        return folder;
    } else {
        if (Checksum.NONE == status.getChecksum()) {
            status.setChecksum(writer.checksum(folder).compute(new NullInputStream(0L), status));
        }
        // Add placeholder object
        status.setMime(MIMETYPE);
        final EnumSet<AbstractPath.Type> type = EnumSet.copyOf(folder.getType());
        type.add(Path.Type.placeholder);
        final Path placeholder = new Path(folder.getParent(), folder.getName(), type,
                new PathAttributes(folder.attributes()));
        new DefaultStreamCloser().close(writer.write(placeholder, status, new DisabledConnectionCallback()));
        return placeholder;
    }
}

From source file:com.nesscomputing.tinyhttp.HttpContentResponseHandler.java

/**
 * Processes the client response.//from w ww. j a  va2  s. co m
 */
public T handle(final HttpRequest request, final HttpResponse response) throws IOException {
    // Find the response stream - the error stream may be valid in cases
    // where the input stream is not.
    InputStream is = null;
    try {
        final HttpEntity httpEntity = response.getEntity();
        if (httpEntity != null) {
            is = httpEntity.getContent();
        }
    } catch (IOException e) {
        log.warn("Could not locate response body stream", e);
        // normal for 401, 403 and 404 responses, for example...
    }

    if (is == null) {
        // Fall back to zero length response.
        is = new NullInputStream(0);
    }

    final Header header = response.getFirstHeader("Content-Encoding");
    if (header != null) {
        final String encoding = StringUtils.trimToEmpty(header.getValue());

        if (StringUtils.equalsIgnoreCase(encoding, "gzip")
                || StringUtils.equalsIgnoreCase(encoding, "x-gzip")) {
            log.debug("Found GZIP stream");
            is = new GZIPInputStream(is);
        } else if (StringUtils.equalsIgnoreCase(encoding, "deflate")) {
            log.debug("Found deflate stream");
            final Inflater inflater = new Inflater(true);
            is = new InflaterInputStream(is, inflater);
        }
    }
    return contentConverter.convert(request, response, is);
}

From source file:com.norconex.committer.AbstractMappedCommitterTest.java

/**
 * Test no commit if not enough document
 * @throws IOException could not create temporary file 
 *///from   www .  ja  v  a2 s  .co m
@Test
public void testNoCommit() throws IOException {
    // Default batch size is 1000, so no commit should occur
    committer.add(defaultReference, new NullInputStream(0), metadata);
    assertFalse(committed);
}

From source file:ch.cyberduck.core.cryptomator.features.CryptoChecksumCompute.java

@Override
public Checksum compute(final InputStream in, final TransferStatus status) throws ChecksumException {
    if (Checksum.NONE == delegate.compute(new NullInputStream(0L), status)) {
        return Checksum.NONE;
    }/* w w w  .  ja v  a  2 s.  co m*/
    if (null == status.getHeader()) {
        // Write header to be reused in writer
        final Cryptor cryptor = cryptomator.getCryptor();
        final FileHeader header = cryptor.fileHeaderCryptor().create();
        status.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header));
    }
    // Make nonces reusable in case we need to compute a checksum
    status.setNonces(new RotatingNonceGenerator(cryptomator.numberOfChunks(status.getLength())));
    return this.compute(in, status.getOffset(), status.getHeader(), status.getNonces());
}

From source file:com.talis.storage.StoredItemTest.java

@Test
public void getMetadataFromEnclosedItem() {
    String key = UUID.randomUUID().toString();
    Multimap<String, String> meta = ArrayListMultimap.create();
    meta.put(key, UUID.randomUUID().toString());
    StoredItem stored = new StoredItem(
            new SubmittedItem(MediaType.TEXT_PLAIN_TYPE, new NullInputStream(100), meta), now(), etag);

    assertEquals(meta.get(key), stored.getMetadata().get(key));
}

From source file:ch.cyberduck.core.manta.MantaReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status,
        final ConnectionCallback connectionCallback) throws BackgroundException {
    final MantaHttpHeaders headers = new MantaHttpHeaders();
    try {//from w ww  . j a  v  a  2  s .co  m
        try {
            if (status.isAppend()) {
                final HttpRange range = HttpRange.withStatus(status);
                headers.setByteRange(range.getStart(), range.getEnd() < 0 ? null : range.getEnd());
            }
            // Requesting an empty file as an InputStream doesn't work, but we also don't want to
            // perform a HEAD request for every read so we'll opt to handle the exception instead
            // see https://github.com/joyent/java-manta/issues/248
            return session.getClient().getAsInputStream(file.getAbsolute(), headers);
        } catch (UnsupportedOperationException e) {
            final MantaObject probablyEmptyFile = session.getClient().head(file.getAbsolute());
            if (probablyEmptyFile.getContentLength() != 0) {
                throw new AccessDeniedException();
            }
            return new NullInputStream(0L);
        }
    } catch (MantaException e) {
        throw new MantaExceptionMappingService().map("Download {0} failed", e, file);
    } catch (MantaClientHttpResponseException e) {
        throw new MantaHttpExceptionMappingService().map("Download {0} failed", e, file);
    } catch (IOException e) {
        throw new DefaultIOExceptionMappingService().map("Download {0} failed", e, file);
    }
}

From source file:ch.cyberduck.core.googledrive.DriveReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {//  w  w w  .j  a  v a2s. com
        if (file.getType().contains(Path.Type.placeholder)) {
            final DescriptiveUrl link = new DriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http);
            if (DescriptiveUrl.EMPTY.equals(link)) {
                log.warn(String.format("Missing web link for file %s", file));
                return new NullInputStream(file.attributes().getSize());
            }
            // Write web link file
            return IOUtils.toInputStream(UrlFileWriterFactory.get().write(link), Charset.defaultCharset());
        } else {
            final String base = session.getClient().getRootUrl();
            final HttpUriRequest request = new HttpGet(String.format(
                    String.format("%%s/drive/v3/files/%%s?alt=media&supportsTeamDrives=%s",
                            PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")),
                    base,
                    new DriveFileidProvider(session).getFileid(file, new DisabledListProgressListener())));
            request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
            if (status.isAppend()) {
                final HttpRange range = HttpRange.withStatus(status);
                final String header;
                if (-1 == range.getEnd()) {
                    header = String.format("bytes=%d-", range.getStart());
                } else {
                    header = String.format("bytes=%d-%d", range.getStart(), range.getEnd());
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Add range header %s for file %s", header, file));
                }
                request.addHeader(new BasicHeader(HttpHeaders.RANGE, header));
                // Disable compression
                request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity"));
            }
            final HttpClient client = session.getHttpClient();
            final HttpResponse response = client.execute(request);
            switch (response.getStatusLine().getStatusCode()) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_PARTIAL_CONTENT:
                return new HttpMethodReleaseInputStream(response);
            default:
                throw new DriveExceptionMappingService().map(new HttpResponseException(
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
            }
        }
    } catch (IOException e) {
        throw new DriveExceptionMappingService().map("Download {0} failed", e, file);
    }
}

From source file:com.norconex.importer.handler.tagger.impl.DeleteTaggerTest.java

@Test
public void testDeleteField() throws IOException, ImporterHandlerException {
    ImporterMetadata meta = new ImporterMetadata();
    meta.addString("field1", "delete me");
    meta.addString("field1", "delete me too");
    meta.setString("field2", "delete also");
    meta.setString("field3", "keep this one");
    meta.setString("field4", "one last to delete");

    DeleteTagger tagger = new DeleteTagger();
    tagger.addField("field1");
    tagger.addField("field2");
    tagger.addField("field4");

    tagger.tagDocument("blah", new NullInputStream(0), meta, false);

    Assert.assertEquals("Invalid field count", 1, meta.size());
    Assert.assertEquals("Value wrongfully deleted or modified", "keep this one", meta.getString("field3"));
}