Java Code Examples for java.io.RandomAccessFile#writeInt()

The following examples show how to use java.io.RandomAccessFile#writeInt() . 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: TeeAudioProcessor.java    From MediaSDK with Apache License 2.0 6 votes vote down vote up
private void writeFileHeader(RandomAccessFile randomAccessFile) throws IOException {
  // Write the start of the header as big endian data.
  randomAccessFile.writeInt(WavUtil.RIFF_FOURCC);
  randomAccessFile.writeInt(-1);
  randomAccessFile.writeInt(WavUtil.WAVE_FOURCC);
  randomAccessFile.writeInt(WavUtil.FMT_FOURCC);

  // Write the rest of the header as little endian data.
  scratchByteBuffer.clear();
  scratchByteBuffer.putInt(16);
  scratchByteBuffer.putShort((short) WavUtil.getTypeForEncoding(encoding));
  scratchByteBuffer.putShort((short) channelCount);
  scratchByteBuffer.putInt(sampleRateHz);
  int bytesPerSample = Util.getPcmFrameSize(encoding, channelCount);
  scratchByteBuffer.putInt(bytesPerSample * sampleRateHz);
  scratchByteBuffer.putShort((short) bytesPerSample);
  scratchByteBuffer.putShort((short) (8 * bytesPerSample / channelCount));
  randomAccessFile.write(scratchBuffer, 0, scratchByteBuffer.position());

  // Write the start of the data chunk as big endian data.
  randomAccessFile.writeInt(WavUtil.DATA_FOURCC);
  randomAccessFile.writeInt(-1);
}
 
Example 2
Source File: AbstractID3v2FrameBody.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
protected void writeHeader(final RandomAccessFile file, final int size) throws IOException {
    final byte[] buffer = new byte[3];
    if (has6ByteHeader()) {
        // write the 3 byte size;
        buffer[0] = (byte) ((size & 0x00FF0000) >> 16);
        buffer[1] = (byte) ((size & 0x0000FF00) >> 8);
        buffer[2] = (byte) (size & 0x000000FF);
        file.write(buffer);
    } else {
        // write the 4 byte size;
        file.writeInt(size);

        // need to skip 2 flag bytes
        file.skipBytes(2);
    }
}
 
Example 3
Source File: RegionLoader.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void createBlank() throws IOException {
    RandomAccessFile raf = this.getRandomAccessFile();

    raf.seek(0);
    raf.setLength(0);
    this.lastSector = 1;
    int time = (int) (System.currentTimeMillis() / 1000d);
    for (int i = 0; i < 1024; ++i) {
        this.locationTable.put(i, new Integer[]{0, 0, time});
        raf.writeInt(0);
    }
    for (int i = 0; i < 1024; ++i) {
        raf.writeInt(time);
    }
}
 
Example 4
Source File: FileDeltaCollection.java    From swellrt with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that a file has a valid deltas header, adding the header if the
 * file is shorter than the header.
 */
private static void setOrCheckFileHeader(RandomAccessFile file) throws IOException {
  Preconditions.checkNotNull(file);
  file.seek(0);

  if (file.length() < FILE_HEADER_LENGTH) {
    // The file is new. Insert a header.
    file.write(FILE_MAGIC_BYTES);
    file.writeInt(FILE_PROTOCOL_VERSION);
  } else {
    byte[] magic = new byte[4];
    file.readFully(magic);
    if (!Arrays.equals(FILE_MAGIC_BYTES, magic)) {
      throw new IOException("Delta file magic bytes are incorrect");
    }

    int version = file.readInt();
    if (version != FILE_PROTOCOL_VERSION) {
      throw new IOException(String.format("File protocol version mismatch - expected %d got %d",
          FILE_PROTOCOL_VERSION, version));
    }
  }
}
 
Example 5
Source File: Storage.java    From RDFS with Apache License 2.0 5 votes vote down vote up
protected void writeCorruptedData(RandomAccessFile file) throws IOException {
  final String messageForPreUpgradeVersion =
    "\nThis file is INTENTIONALLY CORRUPTED so that versions\n"
    + "of Hadoop prior to 0.13 (which are incompatible\n"
    + "with this directory layout) will fail to start.\n";

  file.seek(0);
  file.writeInt(FSConstants.LAYOUT_VERSION);
  org.apache.hadoop.io.UTF8.writeString(file, "");
  file.writeBytes(messageForPreUpgradeVersion);
  file.getFD().sync();
}
 
Example 6
Source File: AuFileWriter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAuFile(stream, auFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            if (raf.length()<=0x7FFFFFFFl) {
                // skip AU magic and data offset field
                raf.skipBytes(8);
                raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
                // that's all
            }
            raf.close();
        }

        return bytesWritten;
    }
 
Example 7
Source File: WaveFileWriter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
            int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip RIFF magic
            raf.skipBytes(4);
            raf.writeInt(big2little( riffLength ));
            // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
            raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
            raf.writeInt(big2little( dataLength ));
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example 8
Source File: WaveFileWriter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
            int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip RIFF magic
            raf.skipBytes(4);
            raf.writeInt(big2little( riffLength ));
            // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
            raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
            raf.writeInt(big2little( dataLength ));
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example 9
Source File: AuFileWriter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAuFile(stream, auFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            if (raf.length()<=0x7FFFFFFFl) {
                // skip AU magic and data offset field
                raf.skipBytes(8);
                raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
                // that's all
            }
            raf.close();
        }

        return bytesWritten;
    }
 
Example 10
Source File: WaveFileWriter.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        WaveFileFormat waveFileFormat = (WaveFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeWaveFile(stream, waveFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( waveFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            int dataLength=bytesWritten-waveFileFormat.getHeaderSize();
            int riffLength=dataLength + waveFileFormat.getHeaderSize() - 8;

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip RIFF magic
            raf.skipBytes(4);
            raf.writeInt(big2little( riffLength ));
            // skip WAVE magic, fmt_ magic, fmt_ length, fmt_ chunk, data magic
            raf.skipBytes(4+4+4+WaveFileFormat.getFmtChunkSize(waveFileFormat.getWaveType())+4);
            raf.writeInt(big2little( dataLength ));
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example 11
Source File: TestFileJournalManager.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/** 
 * Corrupt an edit log file after the start segment transaction
 */
private void corruptAfterStartSegment(File f) throws IOException {
  RandomAccessFile raf = new RandomAccessFile(f, "rw");
  raf.seek(0x20); // skip version and first tranaction and a bit of next transaction
  for (int i = 0; i < 1000; i++) {
    raf.writeInt(0xdeadbeef);
  }
  raf.close();
}
 
Example 12
Source File: RegionLoader.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void writeLocationIndex(int index) throws IOException {
    Integer[] array = this.locationTable.get(index);
    RandomAccessFile raf = this.getRandomAccessFile();

    raf.seek(index << 2);
    raf.writeInt((array[0] << 8) | array[1]);
    raf.seek(4096 + (index << 2));
    raf.writeInt(array[2]);
}
 
Example 13
Source File: AuFileWriter.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAuFile(stream, auFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            if (raf.length()<=0x7FFFFFFFl) {
                // skip AU magic and data offset field
                raf.skipBytes(8);
                raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
                // that's all
            }
            raf.close();
        }

        return bytesWritten;
    }
 
Example 14
Source File: AuFileWriter.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AuFileFormat auFileFormat = (AuFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAuFile(stream, auFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( auFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            if (raf.length()<=0x7FFFFFFFl) {
                // skip AU magic and data offset field
                raf.skipBytes(8);
                raf.writeInt(bytesWritten-AuFileFormat.AU_HEADERSIZE);
                // that's all
            }
            raf.close();
        }

        return bytesWritten;
    }
 
Example 15
Source File: AiffFileWriter.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAiffFile(stream, aiffFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( aiffFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            int ssndBlockSize           = (aiffFileFormat.getFormat().getChannels() * aiffFileFormat.getFormat().getSampleSizeInBits());

            int aiffLength=bytesWritten;
            int ssndChunkSize=aiffLength-aiffFileFormat.getHeaderSize()+16;
            long dataSize=ssndChunkSize-16;
            int numFrames=(int) (dataSize*8/ssndBlockSize);

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip FORM magic
            raf.skipBytes(4);
            raf.writeInt(aiffLength-8);
            // skip aiff2 magic, fver chunk, comm magic, comm size, channel count,
            raf.skipBytes(4+aiffFileFormat.getFverChunkSize()+4+4+2);
            // write frame count
            raf.writeInt(numFrames);
            // skip sample size, samplerate, SSND magic
            raf.skipBytes(2+10+4);
            raf.writeInt(ssndChunkSize-8);
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example 16
Source File: AiffFileWriter.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAiffFile(stream, aiffFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( aiffFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            int ssndBlockSize           = (aiffFileFormat.getFormat().getChannels() * aiffFileFormat.getFormat().getSampleSizeInBits());

            int aiffLength=bytesWritten;
            int ssndChunkSize=aiffLength-aiffFileFormat.getHeaderSize()+16;
            long dataSize=ssndChunkSize-16;
            int numFrames=(int) (dataSize*8/ssndBlockSize);

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip FORM magic
            raf.skipBytes(4);
            raf.writeInt(aiffLength-8);
            // skip aiff2 magic, fver chunk, comm magic, comm size, channel count,
            raf.skipBytes(4+aiffFileFormat.getFverChunkSize()+4+4+2);
            // write frame count
            raf.writeInt(numFrames);
            // skip sample size, samplerate, SSND magic
            raf.skipBytes(2+10+4);
            raf.writeInt(ssndChunkSize-8);
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example 17
Source File: AiffFileWriter.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public int write(AudioInputStream stream, AudioFileFormat.Type fileType, File out) throws IOException {

        // throws IllegalArgumentException if not supported
        AiffFileFormat aiffFileFormat = (AiffFileFormat)getAudioFileFormat(fileType, stream);

        // first write the file without worrying about length fields
        FileOutputStream fos = new FileOutputStream( out );     // throws IOException
        BufferedOutputStream bos = new BufferedOutputStream( fos, bisBufferSize );
        int bytesWritten = writeAiffFile(stream, aiffFileFormat, bos );
        bos.close();

        // now, if length fields were not specified, calculate them,
        // open as a random access file, write the appropriate fields,
        // close again....
        if( aiffFileFormat.getByteLength()== AudioSystem.NOT_SPECIFIED ) {

            // $$kk: 10.22.99: jan: please either implement this or throw an exception!
            // $$fb: 2001-07-13: done. Fixes Bug 4479981
            int ssndBlockSize           = (aiffFileFormat.getFormat().getChannels() * aiffFileFormat.getFormat().getSampleSizeInBits());

            int aiffLength=bytesWritten;
            int ssndChunkSize=aiffLength-aiffFileFormat.getHeaderSize()+16;
            long dataSize=ssndChunkSize-16;
            int numFrames=(int) (dataSize*8/ssndBlockSize);

            RandomAccessFile raf=new RandomAccessFile(out, "rw");
            // skip FORM magic
            raf.skipBytes(4);
            raf.writeInt(aiffLength-8);
            // skip aiff2 magic, fver chunk, comm magic, comm size, channel count,
            raf.skipBytes(4+aiffFileFormat.getFverChunkSize()+4+4+2);
            // write frame count
            raf.writeInt(numFrames);
            // skip sample size, samplerate, SSND magic
            raf.skipBytes(2+10+4);
            raf.writeInt(ssndChunkSize-8);
            // that's all
            raf.close();
        }

        return bytesWritten;
    }
 
Example 18
Source File: ID3v2_4.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
public void write(final RandomAccessFile file) throws IOException {
    int size;
    final String str;
    final Iterator iterator;
    ID3v2_4Frame frame;
    final byte[] buffer = new byte[6];
    final MP3File mp3 = new MP3File();
    mp3.seekMP3Frame(file);
    final long mp3start = file.getFilePointer();
    file.seek(0);
    str = "ID3";
    for (int i = 0; i < str.length(); i++) {
        buffer[i] = (byte) str.charAt(i);
    }
    buffer[3] = 4;
    buffer[4] = 0;
    if (this.unsynchronization) {
        buffer[5] |= TagConstant.MASK_V24_UNSYNCHRONIZATION;
    }
    if (this.extended) {
        buffer[5] |= TagConstant.MASK_V24_EXTENDED_HEADER;
    }
    if (this.experimental) {
        buffer[5] |= TagConstant.MASK_V24_EXPERIMENTAL;
    }
    if (this.footer) {
        buffer[5] |= TagConstant.MASK_V24_FOOTER_PRESENT;
    }
    file.write(buffer);

    // write size
    file.write(sizeToByteArray((int) mp3start - 10));
    if (this.extended) {
        size = 6;
        if (this.updateTag) {
            size++;
        }
        if (this.crcDataFlag) {
            size += 5;
        }
        if (this.tagRestriction) {
            size += 2;
        }
        file.writeInt(size);
        file.writeByte(1); // always 1 byte of flags in this tag
        buffer[0] = 0;
        if (this.updateTag) {
            buffer[0] |= TagConstant.MASK_V24_TAG_UPDATE;
        }
        if (this.crcDataFlag) {
            buffer[0] |= TagConstant.MASK_V24_CRC_DATA_PRESENT;
        }
        if (this.tagRestriction) {
            buffer[0] |= TagConstant.MASK_V24_TAG_RESTRICTIONS;
        }
        file.writeByte(buffer[0]);
        if (this.updateTag) {
            file.writeByte(0);
        }

        // this can be variable length, but this is easier
        if (this.crcDataFlag) {
            file.writeByte(4);
            file.writeInt(this.crcData);
        }
        if (this.tagRestriction) {
            // todo we need to finish this
            file.writeByte(1);
            buffer[0] = (byte) 0;
            if (this.tagRestriction) {
                buffer[0] |= TagConstant.MASK_V24_TAG_SIZE_RESTRICTIONS;
            }
            file.writeByte(this.tagSizeRestriction);
            file.writeByte(this.textEncodingRestriction);
            file.writeByte(this.textFieldSizeRestriction);
            file.writeByte(this.imageEncodingRestriction);
            file.writeByte(this.imageSizeRestriction);
            file.writeByte(buffer[0]);
        }
    }

    // write all frames
    iterator = this.getFrameIterator();
    while (iterator.hasNext()) {
        frame = (ID3v2_4Frame) iterator.next();
        frame.write(file);
    }
}
 
Example 19
Source File: DirFile4.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public synchronized int getExclusiveFileLock()
   {
	boolean validExclusiveLock = false;
	int status;

	/*
	** There can be  a scenario where there is some other JVM that is before jkdk1.4
	** had booted the system and jdk1.4 trying to boot it, in this case we will get the 
	** Exclusive Lock even though some other JVM has already booted the database. But
	** the lock is not a reliable one , so we should  still throw the warning.
	** The Way we identify this case is if "dbex.lck" file size  is differen
	** for pre jdk1.4 jvms and jdk1.4 or above.
		** Zero size "dbex.lck" file  is created by a jvm i.e before jdk1.4 and
       ** File created by jdk1.4 or above writes EXCLUSIVE_FILE_LOCK value into the file.
	** If we are unable to acquire the lock means other JVM that
	** currently booted the system is also JDK1.4 or above;
	** In this case we could confidently throw a exception instead of 
	** of a warning.
	**/

	try
	{
		//create the file that us used to acquire exclusive lock if it does not exists.
		if(createNewFile())
		{
			validExclusiveLock = true;
		}	
		else
		{
			if(length() > 0)
				validExclusiveLock = true;
		}

		//If we can acquire a reliable exclusive lock , try to get it.
		if(validExclusiveLock)
		{
			lockFileOpen = new RandomAccessFile((File) this, "rw");
			lockFileChannel = lockFileOpen.getChannel();
			dbLock =lockFileChannel.tryLock();
			if(dbLock == null)
			{
				lockFileChannel.close();
				lockFileChannel=null;
				lockFileOpen.close();
				lockFileOpen = null;
				status = EXCLUSIVE_FILE_LOCK_NOT_AVAILABLE;
			}
			else
			{	
				lockFileOpen.writeInt(EXCLUSIVE_FILE_LOCK);
				lockFileChannel.force(true);
				status = EXCLUSIVE_FILE_LOCK;
			}
		}
		else
		{
			status = NO_FILE_LOCK_SUPPORT;
		}
	
	}catch(IOException ioe)
	{
		// do nothing - it may be read only medium, who knows what the
		// problem is

		//release all the possible resource we created in this functions.
		releaseExclusiveFileLock();
		status = NO_FILE_LOCK_SUPPORT;
		if (SanityManager.DEBUG)
		{
			SanityManager.THROWASSERT("Unable to Acquire Exclusive Lock on "
									  + getPath(), ioe);
		}
	}
   
	return status;
}
 
Example 20
Source File: HALogFile.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This constructor is called by the log manager to create the file. A
 * writer is created at the same time, and its presence indicates that the
 * file is open for writing.
 * 
 * @throws IOException
 */
public HALogFile(final IRootBlockView rbv,
		final IHALogManagerCallback callback) throws IOException {
	m_callback = callback;
       m_haLogFile = getHALogFileName(m_callback.getHALogDir(),
               rbv.getCommitCounter());

	if (m_haLogFile.exists())
		throw new IllegalStateException("File already exists: "
				+ m_haLogFile.getAbsolutePath());

       final File parentDir = m_haLogFile.getParentFile();

       // Make sure the parent directory(ies) exist.
       if (!parentDir.exists())
           if (!parentDir.mkdirs())
               throw new IOException("Could not create directory: "
                       + parentDir);

       m_raf = new RandomAccessFile(m_haLogFile, "rw");
	m_channel = m_raf.getChannel();
	m_storeType = rbv.getStoreType();

	m_openRootBlock = rbv;
	m_closeRootBlock = null; // file NOT closed

	m_magic = MAGIC;
	m_version = VERSION1;

	/*
	 * Write the MAGIC and version on the file.
	 */
	m_raf.seek(0);
	m_raf.writeInt(m_magic);
	m_raf.writeInt(m_version);

	// Write opening rootblock as both BLOCK0 and BLOCK1
	writeRootBlock(true, rbv); // as BLOCK0
	writeRootBlock(false, rbv); // as BLOCK1

	m_writePosition = START_DATA;

	m_writer = new HALogWriter();

	if (log.isInfoEnabled())
		log.info("Opening HALogFile: " + m_haLogFile.getAbsolutePath());

}