Java Code Examples for java.nio.channels.FileChannel#position()

The following examples show how to use java.nio.channels.FileChannel#position() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MetaDataInsert.java    From mp4parser with Apache License 2.0 6 votes vote down vote up
public FileChannel splitFileAndInsert(File f, long pos, long length) throws IOException {
    FileChannel read = new RandomAccessFile(f, "r").getChannel();
    File tmp = File.createTempFile("ChangeMetaData", "splitFileAndInsert");
    FileChannel tmpWrite = new RandomAccessFile(tmp, "rw").getChannel();
    read.position(pos);
    tmpWrite.transferFrom(read, 0, read.size() - pos);
    read.close();
    FileChannel write = new RandomAccessFile(f, "rw").getChannel();
    write.position(pos + length);
    tmpWrite.position(0);
    long transferred = 0;
    while ((transferred += tmpWrite.transferTo(0, tmpWrite.size() - transferred, write)) != tmpWrite.size()) {
        System.out.println(transferred);
    }
    System.out.println(transferred);
    tmpWrite.close();
    tmp.delete();
    return write;
}
 
Example 2
Source File: JimfsFileChannelTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testTruncate() throws IOException {
  RegularFile file = regularFile(10);
  FileChannel channel = channel(file, WRITE);

  channel.truncate(10); // no resize, >= size
  assertEquals(10, file.size());
  channel.truncate(11); // no resize, > size
  assertEquals(10, file.size());
  channel.truncate(5); // resize down to 5
  assertEquals(5, file.size());

  channel.position(20);
  channel.truncate(10);
  assertEquals(10, channel.position());
  channel.truncate(2);
  assertEquals(2, channel.position());
}
 
Example 3
Source File: BufferedWriteChannel.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
static BufferedWriteChannel open(File file, boolean append, ByteBuffer buffer) throws IOException {
  final RandomAccessFile raf = new RandomAccessFile(file, "rw");
  final FileChannel fc = raf.getChannel();
  if (append) {
    fc.position(fc.size());
  } else {
    fc.truncate(0);
  }
  Preconditions.assertSame(fc.size(), fc.position(), "fc.position");
  return new BufferedWriteChannel(fc, buffer);
}
 
Example 4
Source File: PEResourceDirectory.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public ResourceEntry(FileChannel chan) throws IOException {
  // System.out.println("Resource Entry Offset: " + chan.position());
  ByteBuffer buf = ByteBuffer.allocate(8);
  buf.order(ByteOrder.LITTLE_ENDIAN);
  chan.read(buf);
  buf.position(0);
  long orgchanpos = chan.position();
  int val = buf.getInt();
  long offsetToData = buf.getInt();
  // System.out.println("Entry: Val=" + val);
  // System.out.println("       Off=" + offsetToData);

  if (val < 0) {
    val &= 0x7FFFFFFF;
    Name = extractStringAt(chan, val);
    Id = -1;
    // System.out.println("    String at " + val + " = " + Name);
  } else {
    Id = val;
  }

  if (offsetToData < 0) {
    offsetToData &= 0x7FFFFFFF;
    long orgpos = chan.position();
    chan.position(PEResourceDirectory.this.m_offsetBase + offsetToData);
    Directory = new PEResourceDirectory.ImageResourceDirectory(chan);
    chan.position(orgpos);
  } else {
    Data = new DataEntry(chan, offsetToData);
  }
}
 
Example 5
Source File: ContentDataSource.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long open(DataSpec dataSpec) throws ContentDataSourceException {
  try {
    uri = dataSpec.uri;
    transferInitializing(dataSpec);
    assetFileDescriptor = resolver.openAssetFileDescriptor(uri, "r");
    if (assetFileDescriptor == null) {
      throw new FileNotFoundException("Could not open file descriptor for: " + uri);
    }
    inputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());
    long assetStartOffset = assetFileDescriptor.getStartOffset();
    long skipped = inputStream.skip(assetStartOffset + dataSpec.position) - assetStartOffset;
    if (skipped != dataSpec.position) {
      // We expect the skip to be satisfied in full. If it isn't then we're probably trying to
      // skip beyond the end of the data.
      throw new EOFException();
    }
    if (dataSpec.length != C.LENGTH_UNSET) {
      bytesRemaining = dataSpec.length;
    } else {
      long assetFileDescriptorLength = assetFileDescriptor.getLength();
      if (assetFileDescriptorLength == AssetFileDescriptor.UNKNOWN_LENGTH) {
        // The asset must extend to the end of the file. If FileInputStream.getChannel().size()
        // returns 0 then the remaining length cannot be determined.
        FileChannel channel = inputStream.getChannel();
        long channelSize = channel.size();
        bytesRemaining = channelSize == 0 ? C.LENGTH_UNSET : channelSize - channel.position();
      } else {
        bytesRemaining = assetFileDescriptorLength - skipped;
      }
    }
  } catch (IOException e) {
    throw new ContentDataSourceException(e);
  }

  opened = true;
  transferStarted(dataSpec);

  return bytesRemaining;
}
 
Example 6
Source File: GeoTiff.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeIFDEntry(FileChannel channel, IFDEntry ifd, int start) throws IOException {
  channel.position(start);
  ByteBuffer buffer = ByteBuffer.allocate(12);

  buffer.putShort((short) ifd.tag.getCode());
  buffer.putShort((short) ifd.type.code);
  buffer.putInt(ifd.count);

  int size = ifd.count * ifd.type.size;
  if (size <= 4) {
    int done = writeValues(buffer, ifd);
    for (int k = 0; k < 4 - done; k++) // fill out to 4 bytes
      buffer.put((byte) 0);
    buffer.flip();
    channel.write(buffer);

  } else { // write offset
    buffer.putInt(nextOverflowData);
    buffer.flip();
    channel.write(buffer);
    // write data
    channel.position(nextOverflowData);
    ByteBuffer vbuffer = ByteBuffer.allocate(size);
    writeValues(vbuffer, ifd);
    vbuffer.flip();
    channel.write(vbuffer);
    nextOverflowData += size;
  }
}
 
Example 7
Source File: FileUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Randomly generates a sequence of bytes and overwrites the contents of the file a number of times. The file is then deleted.
 *
 * @param file File to be overwritten a number of times and, ultimately, deleted
 * @param passes Number of times file should be overwritten
 * @throws IOException if something makes shredding or deleting a problem
 */
public static void shredFile(final File file, final int passes)
        throws IOException {
    final Random generator = new Random();
    final long fileLength = file.length();
    final int byteArraySize = (int) Math.min(fileLength, 1048576); // 1MB
    final byte[] b = new byte[byteArraySize];
    final long numOfRandomWrites = (fileLength / b.length) + 1;
    final FileOutputStream fos = new FileOutputStream(file);
    try {
        // Over write file contents (passes) times
        final FileChannel channel = fos.getChannel();
        for (int i = 0; i < passes; i++) {
            generator.nextBytes(b);
            for (int j = 0; j <= numOfRandomWrites; j++) {
                fos.write(b);
            }
            fos.flush();
            channel.position(0);
        }
        // Write out "0" for each byte in the file
        Arrays.fill(b, (byte) 0);
        for (int j = 0; j < numOfRandomWrites; j++) {
            fos.write(b);
        }
        fos.flush();
        fos.close();
        // Try to delete the file a few times
        if (!FileUtils.deleteFile(file, null, 5)) {
            throw new IOException("Failed to delete file after shredding");
        }

    } finally {
        FileUtils.closeQuietly(fos);
    }
}
 
Example 8
Source File: TestFSEditLogLoader.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Return the length of bytes in the given file after subtracting
 * the trailer of 0xFF (OP_INVALID)s.
 * This seeks to the end of the file and reads chunks backwards until
 * it finds a non-0xFF byte.
 * @throws IOException if the file cannot be read
 */
private static long getNonTrailerLength(File f) throws IOException {
  final int chunkSizeToRead = 256*1024;
  FileInputStream fis = new FileInputStream(f);
  try {
    
    byte buf[] = new byte[chunkSizeToRead];

    FileChannel fc = fis.getChannel();
    long size = fc.size();
    long pos = size - (size % chunkSizeToRead);
    
    while (pos >= 0) {
      fc.position(pos);

      int readLen = (int) Math.min(size - pos, chunkSizeToRead);
      IOUtils.readFully(fis, buf, 0, readLen);
      for (int i = readLen - 1; i >= 0; i--) {
        if (buf[i] != FSEditLogOpCodes.OP_INVALID.getOpCode()) {
          return pos + i + 1; // + 1 since we count this byte!
        }
      }
      
      pos -= chunkSizeToRead;
    }
    return 0;
  } finally {
    fis.close();
  }
}
 
Example 9
Source File: DavidAppend.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {

        List<Movie> movies = new LinkedList<Movie>();
        movies.add(MovieCreator.build(DavidAppend.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/davidappend/v1.mp4"));
        movies.add(MovieCreator.build(DavidAppend.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/davidappend/v2.mp4"));
        movies.add(MovieCreator.build(DavidAppend.class.getProtectionDomain().getCodeSource().getLocation().getFile() + "/davidappend/v2.mp4"));


        List<Track> videoTracks = new LinkedList<Track>();
        List<Track> audioTracks = new LinkedList<Track>();


        for (Movie m : movies) {
            for (Track track : m.getTracks()) {
                if (track.getHandler().equals("vide")) {
                    videoTracks.add(track);
                }
                if (track.getHandler().equals("soun")) {
                    audioTracks.add(track);
                }
            }
        }

        Movie concatMovie = new Movie();

        concatMovie.addTrack(new AppendTrack(videoTracks.toArray(new Track[videoTracks.size()])));
        concatMovie.addTrack(new AppendTrack(audioTracks.toArray(new Track[audioTracks.size()])));


        Container out2 = new DefaultMp4Builder().build(concatMovie);
        FileChannel fc = new RandomAccessFile(String.format("output.mp4"), "rw").getChannel();
        fc.position(0);
        out2.writeContainer(fc);
        fc.close();


    }
 
Example 10
Source File: IoUtil.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Fill a region of a file with a given byte value.
 *
 * @param fileChannel to fill.
 * @param position    at which to start writing.
 * @param length      of the region to write.
 * @param value       to fill the region with.
 */
public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value)
{
    try
    {
        final byte[] filler;
        if (0 != value)
        {
            filler = new byte[BLOCK_SIZE];
            Arrays.fill(filler, value);
        }
        else
        {
            filler = FILLER;
        }

        final ByteBuffer byteBuffer = ByteBuffer.wrap(filler);
        fileChannel.position(position);

        final int blocks = (int)(length / BLOCK_SIZE);
        final int blockRemainder = (int)(length % BLOCK_SIZE);

        for (int i = 0; i < blocks; i++)
        {
            byteBuffer.position(0);
            fileChannel.write(byteBuffer);
        }

        if (blockRemainder > 0)
        {
            byteBuffer.position(0);
            byteBuffer.limit(blockRemainder);
            fileChannel.write(byteBuffer);
        }
    }
    catch (final IOException ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}
 
Example 11
Source File: TextSecurePreKeyStore.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void storeSerializedRecord(File file, byte[] serialized) throws IOException {
    RandomAccessFile recordFile = new RandomAccessFile(file, "rw");
    FileChannel out = recordFile.getChannel();

    out.position(0);
    writeInteger(CURRENT_VERSION_MARKER, out);
    writeBlob(serialized, out);
    out.truncate(out.position());
    recordFile.close();
}
 
Example 12
Source File: JimfsFileChannelTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testPositionNegative() throws IOException {
  FileChannel channel = channel(regularFile(0), READ, WRITE);

  try {
    channel.position(-1);
    fail();
  } catch (IllegalArgumentException expected) {
  }
}
 
Example 13
Source File: MemFileChannelTest.java    From jackcess with Apache License 2.0 5 votes vote down vote up
private static void copy(FileChannel src, FileChannel dst, ByteBuffer bb)
  throws IOException
{
  src.position(0L);
  while(true) {
    bb.clear();
    if(src.read(bb) < 0) {
      break;
    }
    bb.flip();
    dst.write(bb);
  }
}
 
Example 14
Source File: Pread.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    File blah = File.createTempFile("blah3", null);
    blah.deleteOnExit();
    initTestFile(blah);

    FileInputStream fis = new FileInputStream(blah);
    FileChannel c = fis.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        long expectedResult = offset / CHARS_PER_LINE;
        offset = expectedResult * CHARS_PER_LINE;
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        long originalPosition = c.position();

        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }

        long newPosition = c.position();

        for (int i=0; i<4; i++) {
            byte aByte = bleck.get(i);
            sb.setCharAt(i, (char)aByte);
        }
        int result = Integer.parseInt(sb.toString());
        if (result != expectedResult) {
            err.println("I expected "+ expectedResult);
            err.println("I got "+ result);
            throw new Exception("Read test failed");
        }

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");
    }

    c.close();
    fis.close();
    blah.delete();
}
 
Example 15
Source File: Pwrite.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    blah = File.createTempFile("blah", null);
    blah.deleteOnExit();
    initTestFile(blah);

    RandomAccessFile raf = new RandomAccessFile(blah, "rw");
    FileChannel c = raf.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        // Write known sequence out
        for (byte i=0; i<4; i++) {
            bleck.put(i);
        }
        bleck.flip();
        long originalPosition = c.position();
        int totalWritten = 0;
        while (totalWritten < 4) {
            int written = c.write(bleck, offset);
            if (written < 0)
                throw new Exception("Read failed");
            totalWritten += written;
        }

        long newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        // Attempt to read sequence back in
        bleck = ByteBuffer.allocateDirect(4);
        originalPosition = c.position();
        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }
        newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        for (byte i=0; i<4; i++) {
            if (bleck.get(i) != i)
                throw new Exception("Write test failed");
        }
    }
    c.close();
    raf.close();
    blah.delete();
}
 
Example 16
Source File: Pread.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    File blah = File.createTempFile("blah3", null);
    blah.deleteOnExit();
    initTestFile(blah);

    FileInputStream fis = new FileInputStream(blah);
    FileChannel c = fis.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        long expectedResult = offset / CHARS_PER_LINE;
        offset = expectedResult * CHARS_PER_LINE;
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        long originalPosition = c.position();

        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }

        long newPosition = c.position();

        for (int i=0; i<4; i++) {
            byte aByte = bleck.get(i);
            sb.setCharAt(i, (char)aByte);
        }
        int result = Integer.parseInt(sb.toString());
        if (result != expectedResult) {
            err.println("I expected "+ expectedResult);
            err.println("I got "+ result);
            throw new Exception("Read test failed");
        }

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");
    }

    c.close();
    fis.close();
    blah.delete();
}
 
Example 17
Source File: SNPLoader.java    From systemsgenetics with GNU General Public License v3.0 4 votes vote down vote up
public void loadGenotypes(SNP snp) throws IOException {
        byte[] allele1 = new byte[m_numIndividuals];
        byte[] allele2 = new byte[m_numIndividuals];

        int nrBytesToRead = m_numIndividuals * 2;
        long seekLoc = (long) snp.getId() * (long) nrBytesToRead;

//		byte[] alleles = new byte[nrBytesToRead];

        // initiate buffer if it doesn't exist, or if location we're looking for is beyond the current map
        long seekEnd = seekLoc + (m_numIndividuals * 2);
//		System.out.println("Seekloc: " + seekLoc);
//		System.out.println("SeekEnd: " + seekEnd);
        if (mappedGenotypeHandle == null || seekLoc < currentGtMapStart || seekLoc > currentGtMapEnd || seekEnd > currentGtMapEnd) {
            // 32 megabytes worth of variants; (32*1048576)/(m_numIndividuals * 2) bytes
            if (mappedGenotypeHandle == null) {

                int bytesPerVariant = (m_numIndividuals * 2);
                int nrBytesPerBuffer = bytesPerVariant * numberOfVariantsInMemoryMap; //(32 * 1048576);
                while (nrBytesPerBuffer < 0) {
                    numberOfVariantsInMemoryMap /= 2;
                    nrBytesPerBuffer = bytesPerVariant * numberOfVariantsInMemoryMap; //(32 * 1048576);

//					System.out.println("WARNING: BUFFER OVERFLOW! Setting max number of variants in memory to " + numberOfVariantsInMemoryMap);
//					System.out.println("Buffer will be " + Gpio.humanizeFileSize(nrBytesPerBuffer) + " (" + nrBytesPerBuffer + "b)");
                }
//				int remainder = nrBytesPerBuffer % bytesPerVariant;
//				nrBytesPerBuffer += remainder;
                gtmaplen = nrBytesPerBuffer;
                dsmaplen = nrBytesPerBuffer / 2;
//				System.out.println("bytes in buffer1: " + gtmaplen);
//				System.out.println("bytes in buffer2: " + dsmaplen);
            }


            // prevent overflow
            int maplentouse = gtmaplen;
            if (seekLoc + maplentouse > m_genotypehandle.length()) {
                maplentouse = (int) (m_genotypehandle.length() - seekLoc);
            }

            FileChannel gtChannel = m_genotypehandle.getChannel();
            gtChannel.position(seekLoc);
            if (mappedGenotypeHandle == null || mappedGenotypeHandle.capacity() != maplentouse) {
                mappedGenotypeHandle = ByteBuffer.allocateDirect(maplentouse);
            } else {
                ((Buffer) mappedGenotypeHandle).clear();
            }

            gtChannel.read(mappedGenotypeHandle);

//            mappedGenotypeHandle = m_genotypehandle.getChannel().map(FileChannel.MapMode.READ_ONLY, seekLoc, maplentouse);
//            mappedGenotypeHandle.load();
//            bGt = new byte[(int) maplentouse];
//            mappedGenotypeHandle.get(bGt);
//            mappedGenotypeHandle.g
            ((Buffer) mappedGenotypeHandle).flip();
            currentGtMapStart = seekLoc;
            currentGtMapEnd = currentGtMapStart + maplentouse;
//            System.out.println("Reload buffer:\t" + seekLoc + "\tstart\t" + currentGtMapStart + "\tstop\t" + currentGtMapEnd + "\tlen\t" + maplentouse);

        }

//		if (m_genotypehandle.getFilePointer() != seekLoc) {
//			m_genotypehandle.seek(seekLoc);
//		}

//		m_genotypehandle.read(alleles, 0, bytesize);
//		mappedGenotypeHandle(alleles, 0, bytesize);

        // recalculate where we should be looking for this particular snp


//		mappedGenotypeHandle.get(alleles, offset, nrBytesToRead);
//		mappedGenotypeHandle.slice();

        int offset = (int) (seekLoc - currentGtMapStart);
//        System.out.println("Seekloc: " + seekLoc);
//        System.out.println("offset: " + offset);
//        System.out.println("btr: " + nrBytesToRead);
//        System.out.println("capacity: " + mappedGenotypeHandle.capacity());
//        System.out.println("remaining: " + mappedGenotypeHandle.remaining());
//        System.out.println("limit:" + mappedGenotypeHandle.limit());
//        System.out.println("position:" + mappedGenotypeHandle.position());
//        System.out.println("req: " + m_numIndividuals);

        ((Buffer) mappedGenotypeHandle).position(offset);

        mappedGenotypeHandle.get(allele1, 0, m_numIndividuals);
        mappedGenotypeHandle.get(allele2, 0, m_numIndividuals);
//        System.arraycopy(bGt, offset, allele1, 0, m_numIndividuals);
//        System.arraycopy(bGt, offset + m_numIndividuals, allele2, 0, m_numIndividuals);
//		System.arraycopy(alleles, 0, allele1, 0, m_numIndividuals);
//		System.arraycopy(alleles, m_numIndividuals, allele2, 0, m_numIndividuals);

//		alleles = null;

        snp.setAlleles(allele1, allele2, m_isIncluded, m_isFemale);

    }
 
Example 18
Source File: DiskRegionJUnitTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
   * If IOException occurs while initializing a region 
   * ,then the bridge servers should not be stopped 
   * 
   * @throws Exception
   */
  public void testBridgeServerRunningInSynchPersistOnlyForIOExceptionCase()
      throws Exception {    
      DiskRegionProperties props = new DiskRegionProperties();
      props.setRegionName("IGNORE_EXCEPTION_testBridgeServerStoppingInSynchPersistOnlyForIOExceptionCase");
      props.setOverflow(true);
      props.setRolling(true);
      props.setDiskDirs(dirs);
      props.setPersistBackup(true);
      props.setMaxOplogSize(100000); // just needs to be bigger than 65550

      region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, props, Scope.LOCAL);
      BridgeServer bs1 = cache.addBridgeServer();
      bs1.setPort(5555);
      bs1.start();      
      try {        
        region.create("key1", new byte[16]);
        region.create("key2", new byte[16]);
        //Get the oplog file path
        FileChannel oplogFileChnl = ((LocalRegion)region).getDiskRegion()
        .testHook_getChild().getFileChannel();
        //corrupt the opfile
        oplogFileChnl.position(2);
        ByteBuffer bf = ByteBuffer.allocate(416);
        for(int i = 0; i <5;++i) {
          bf.putInt(i);
        }
        bf.flip();
//      Corrupt the oplogFile
        oplogFileChnl.write(bf);
        //Close the region
        region.close();        
        assertTrue(region.isDestroyed());        
        try {
          region = DiskRegionHelperFactory.getSyncPersistOnlyRegion(cache, props, Scope.LOCAL);
          fail("expected DiskAccessException");
        }catch(DiskAccessException dae) {
          //OK expected          
        }
        assertTrue(region.isDestroyed());        
        region = null;
        List bsRunning = cache.getBridgeServers();
        assertTrue(!bsRunning.isEmpty());
      }
      finally {
        if (region != null) {
          region.destroyRegion();
        }        
      }
  }
 
Example 19
Source File: Pwrite.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private static void genericTest() throws Exception {
    StringBuffer sb = new StringBuffer();
    sb.setLength(4);

    blah = File.createTempFile("blah", null);
    blah.deleteOnExit();
    initTestFile(blah);

    RandomAccessFile raf = new RandomAccessFile(blah, "rw");
    FileChannel c = raf.getChannel();

    for (int x=0; x<100; x++) {
        long offset = generator.nextInt(1000);
        ByteBuffer bleck = ByteBuffer.allocateDirect(4);

        // Write known sequence out
        for (byte i=0; i<4; i++) {
            bleck.put(i);
        }
        bleck.flip();
        long originalPosition = c.position();
        int totalWritten = 0;
        while (totalWritten < 4) {
            int written = c.write(bleck, offset);
            if (written < 0)
                throw new Exception("Read failed");
            totalWritten += written;
        }

        long newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        // Attempt to read sequence back in
        bleck = ByteBuffer.allocateDirect(4);
        originalPosition = c.position();
        int totalRead = 0;
        while (totalRead < 4) {
            int read = c.read(bleck, offset);
            if (read < 0)
                throw new Exception("Read failed");
            totalRead += read;
        }
        newPosition = c.position();

        // Ensure that file pointer position has not changed
        if (originalPosition != newPosition)
            throw new Exception("File position modified");

        for (byte i=0; i<4; i++) {
            if (bleck.get(i) != i)
                throw new Exception("Write test failed");
        }
    }
    c.close();
    raf.close();
    blah.delete();
}
 
Example 20
Source File: ContentDataSource.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
@Override
public long open(DataSpec dataSpec) throws ContentDataSourceException {
  try {
    Uri uri = dataSpec.uri;
    this.uri = uri;

    transferInitializing(dataSpec);
    AssetFileDescriptor assetFileDescriptor = resolver.openAssetFileDescriptor(uri, "r");
    this.assetFileDescriptor = assetFileDescriptor;
    if (assetFileDescriptor == null) {
      throw new FileNotFoundException("Could not open file descriptor for: " + uri);
    }
    FileInputStream inputStream = new FileInputStream(assetFileDescriptor.getFileDescriptor());
    this.inputStream = inputStream;

    long assetStartOffset = assetFileDescriptor.getStartOffset();
    long skipped = inputStream.skip(assetStartOffset + dataSpec.position) - assetStartOffset;
    if (skipped != dataSpec.position) {
      // We expect the skip to be satisfied in full. If it isn't then we're probably trying to
      // skip beyond the end of the data.
      throw new EOFException();
    }
    if (dataSpec.length != C.LENGTH_UNSET) {
      bytesRemaining = dataSpec.length;
    } else {
      long assetFileDescriptorLength = assetFileDescriptor.getLength();
      if (assetFileDescriptorLength == AssetFileDescriptor.UNKNOWN_LENGTH) {
        // The asset must extend to the end of the file. If FileInputStream.getChannel().size()
        // returns 0 then the remaining length cannot be determined.
        FileChannel channel = inputStream.getChannel();
        long channelSize = channel.size();
        bytesRemaining = channelSize == 0 ? C.LENGTH_UNSET : channelSize - channel.position();
      } else {
        bytesRemaining = assetFileDescriptorLength - skipped;
      }
    }
  } catch (IOException e) {
    throw new ContentDataSourceException(e);
  }

  opened = true;
  transferStarted(dataSpec);

  return bytesRemaining;
}