Search in sources :

Example 81 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project google-cloud-java by GoogleCloudPlatform.

the class ITGcsNio method testReadByteChannel.

@Test(timeout = 60_000)
public void testReadByteChannel() throws IOException {
    CloudStorageFileSystem testBucket = getTestBucket();
    Path path = testBucket.getPath(SML_FILE);
    long size = Files.size(path);
    SeekableByteChannel chan = Files.newByteChannel(path, StandardOpenOption.READ);
    assertThat(chan.size()).isEqualTo(size);
    ByteBuffer buf = ByteBuffer.allocate(SML_SIZE);
    int read = 0;
    while (chan.isOpen()) {
        int rc = chan.read(buf);
        assertThat(chan.size()).isEqualTo(size);
        if (rc < 0) {
            // EOF
            break;
        }
        assertThat(rc).isGreaterThan(0);
        read += rc;
        assertThat(chan.position()).isEqualTo(read);
    }
    assertThat(read).isEqualTo(size);
    byte[] expected = new byte[SML_SIZE];
    new Random(SML_SIZE).nextBytes(expected);
    assertThat(Arrays.equals(buf.array(), expected)).isTrue();
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel) Random(java.util.Random) CloudStorageFileSystem(com.google.cloud.storage.contrib.nio.CloudStorageFileSystem) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 82 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project google-cloud-java by GoogleCloudPlatform.

the class CloudStorageReadTest method testChannelReads.

@Test
public void testChannelReads() throws IOException, InterruptedException {
    // fill in the file
    byte[] bytes = ALONE.getBytes(UTF_8);
    try (FileSystem fs = CloudStorageFileSystem.forBucket("bucket")) {
        Path p = fillFile(fs, bytes, repeat);
        try (SeekableByteChannel chan = Files.newByteChannel(p, StandardOpenOption.READ)) {
            ByteBuffer buf = ByteBuffer.allocate(bytes.length);
            for (int i = 0; i < repeat; i++) {
                buf.clear();
                for (int off = 0; off < bytes.length; ) {
                    int read = chan.read(buf);
                    if (read < 0) {
                        // EOF
                        break;
                    }
                    off += read;
                }
                assertWithMessage("Wrong bytes from channel at repeat " + i).that(new String(buf.array(), UTF_8)).isEqualTo(ALONE);
            }
            // reading past the end
            buf.clear();
            int eof = chan.read(buf);
            assertWithMessage("EOF should return -1").that(eof).isEqualTo(-1);
        }
    }
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel) FileSystem(java.nio.file.FileSystem) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 83 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project beam by apache.

the class MinimalWordCountJava8Test method buildMockGcsUtil.

private GcsUtil buildMockGcsUtil() throws IOException {
    GcsUtil mockGcsUtil = Mockito.mock(GcsUtil.class);
    // Any request to open gets a new bogus channel
    Mockito.when(mockGcsUtil.open(Mockito.any(GcsPath.class))).then(new Answer<SeekableByteChannel>() {

        @Override
        public SeekableByteChannel answer(InvocationOnMock invocation) throws Throwable {
            return FileChannel.open(Files.createTempFile("channel-", ".tmp"), StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
        }
    });
    // Any request for expansion returns a list containing the original GcsPath
    // This is required to pass validation that occurs in TextIO during apply()
    Mockito.when(mockGcsUtil.expand(Mockito.any(GcsPath.class))).then(new Answer<List<GcsPath>>() {

        @Override
        public List<GcsPath> answer(InvocationOnMock invocation) throws Throwable {
            return ImmutableList.of((GcsPath) invocation.getArguments()[0]);
        }
    });
    return mockGcsUtil;
}
Also used : SeekableByteChannel(java.nio.channels.SeekableByteChannel) InvocationOnMock(org.mockito.invocation.InvocationOnMock) GcsPath(org.apache.beam.sdk.util.gcsfs.GcsPath) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) GcsUtil(org.apache.beam.sdk.util.GcsUtil)

Example 84 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project lucene-solr by apache.

the class SimpleFSDirectory method openInput.

/** Creates an IndexInput for the file with the given name. */
@Override
public IndexInput openInput(String name, IOContext context) throws IOException {
    ensureOpen();
    ensureCanRead(name);
    Path path = directory.resolve(name);
    SeekableByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ);
    return new SimpleFSIndexInput("SimpleFSIndexInput(path=\"" + path + "\")", channel, context);
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel)

Example 85 with SeekableByteChannel

use of java.nio.channels.SeekableByteChannel in project lucene-solr by apache.

the class LineFileDocs method open.

private synchronized void open(Random random) throws IOException {
    InputStream is = getClass().getResourceAsStream(path);
    boolean needSkip = true;
    long size = 0L, seekTo = 0L;
    if (is == null) {
        // if it's not in classpath, we load it as absolute filesystem path (e.g. Hudson's home dir)
        Path file = Paths.get(path);
        size = Files.size(file);
        if (path.endsWith(".gz")) {
            // if it is a gzip file, we need to use InputStream and slowly skipTo:
            is = Files.newInputStream(file);
        } else {
            // optimized seek using SeekableByteChannel
            seekTo = randomSeekPos(random, size);
            final SeekableByteChannel channel = Files.newByteChannel(file);
            if (LuceneTestCase.VERBOSE) {
                System.out.println("TEST: LineFileDocs: file seek to fp=" + seekTo + " on open");
            }
            channel.position(seekTo);
            is = Channels.newInputStream(channel);
            needSkip = false;
        }
    } else {
        // if the file comes from Classpath:
        size = is.available();
    }
    if (path.endsWith(".gz")) {
        is = new GZIPInputStream(is);
        // guestimate:
        size *= 2.8;
    }
    // but this seek is a scan, so very inefficient!!!
    if (needSkip) {
        seekTo = randomSeekPos(random, size);
        if (LuceneTestCase.VERBOSE) {
            System.out.println("TEST: LineFileDocs: stream skip to fp=" + seekTo + " on open");
        }
        is.skip(seekTo);
    }
    // if we seeked somewhere, read until newline char
    if (seekTo > 0L) {
        int b;
        do {
            b = is.read();
        } while (b >= 0 && b != 13 && b != 10);
    }
    CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
    reader = new BufferedReader(new InputStreamReader(is, decoder), BUFFER_SIZE);
    if (seekTo > 0L) {
        // read one more line, to make sure we are not inside a Windows linebreak (\r\n):
        reader.readLine();
    }
}
Also used : Path(java.nio.file.Path) SeekableByteChannel(java.nio.channels.SeekableByteChannel) GZIPInputStream(java.util.zip.GZIPInputStream) CharsetDecoder(java.nio.charset.CharsetDecoder) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IntPoint(org.apache.lucene.document.IntPoint)

Aggregations

SeekableByteChannel (java.nio.channels.SeekableByteChannel)151 ByteBuffer (java.nio.ByteBuffer)72 Path (java.nio.file.Path)56 IOException (java.io.IOException)52 Test (org.junit.Test)41 InputStream (java.io.InputStream)17 ReadableByteChannel (java.nio.channels.ReadableByteChannel)13 NoSuchFileException (java.nio.file.NoSuchFileException)13 FileSystem (java.nio.file.FileSystem)12 StandardOpenOption (java.nio.file.StandardOpenOption)11 Test (org.testng.annotations.Test)9 WritableByteChannel (java.nio.channels.WritableByteChannel)8 OpenOption (java.nio.file.OpenOption)8 HashSet (java.util.HashSet)8 OutputStream (java.io.OutputStream)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 File (java.io.File)6 CloudStorageFileSystem (com.google.cloud.storage.contrib.nio.CloudStorageFileSystem)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 URI (java.net.URI)5