package net.openhft.chronicle.bytes;

import net.openhft.chronicle.bytes.ref.BinaryLongReference;
import net.openhft.chronicle.core.io.IOTools;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class LockingByteableTest {
    @Test(expected = UnsupportedOperationException.class)
    public void notLockable() throws IOException {
        BinaryLongReference blr = new BinaryLongReference();
        blr.bytesStore(Bytes.from("Hello World"), 0, 8);
        blr.lock(false);
    }

    @Test
    public void lockableShared() throws IOException {
        final String tmp = IOTools.tempName("lockableShared");
        new File(tmp).deleteOnExit();

        for (int i = 0; i < 3; i++) {
            try (MappedBytes mbs = MappedBytes.mappedBytes(tmp, 64 << 10)) {
                BinaryLongReference blr = new BinaryLongReference();
                blr.bytesStore(mbs, 0, 8);
                try (FileLock fl = blr.lock(true)) {
                    assertNotNull(fl);
                }
                try (FileLock fl = blr.lock(true)) {
                    assertNotNull(fl);
                }
            }
        }
    }

    @Test
    public void tryLockableShared() throws IOException {
        final String tmp = IOTools.tempName("lockableShared");
        new File(tmp).deleteOnExit();

        for (int i = 0; i < 3; i++) {
            try (MappedBytes mbs = MappedBytes.mappedBytes(tmp, 64 << 10)) {
                BinaryLongReference blr = new BinaryLongReference();
                blr.bytesStore(mbs, 0, 8);
                try (FileLock fl = blr.tryLock(true)) {
                    assertNotNull(fl);
                }
                try (FileLock fl = blr.tryLock(true)) {
                    assertNotNull(fl);
                }
            }
        }
    }

    @Test(expected = OverlappingFileLockException.class)
    public void doubleLockableShared() throws IOException {
        final String tmp = IOTools.tempName("doubleLockableShared");
        new File(tmp).deleteOnExit();

        try (MappedBytes mbs = MappedBytes.mappedBytes(tmp, 64 << 10)) {
            BinaryLongReference blr = new BinaryLongReference();
            blr.bytesStore(mbs, 0, 8);
            try (FileLock fl = blr.lock(true)) {
                blr.lock(false);
                fail();
            }
        }
    }
}

@@ -948,36 +948,35 @@
 s(tmp, 64 %3C%3C 10)
-) %7B%0A
+;%0A 
                 
@@ -1018,33 +1018,35 @@
 yLongReference()
-;
+) %7B
 %0A               
@@ -1596,36 +1596,35 @@
 s(tmp, 64 %3C%3C 10)
-) %7B%0A
+;%0A 
                 
@@ -1666,33 +1666,35 @@
 yLongReference()
-;
+) %7B
 %0A               
@@ -2272,20 +2272,19 @@
 4 %3C%3C 10)
-) %7B%0A
+;%0A 
         
@@ -2330,33 +2330,35 @@
 yLongReference()
-;
+) %7B
 %0A            blr

Fix clean up.