Search in sources :

Example 56 with IntByReference

use of com.sun.jna.ptr.IntByReference in project jna by java-native-access.

the class Kernel32NamedPipeTest method testMultiThreadedNamedPipe.

@Test
public void testMultiThreadedNamedPipe() {
    final String pipeName = "\\\\.\\pipe\\" + getCurrentTestName();
    final Logger logger = Logger.getLogger(getClass().getName());
    final int MAX_BUFFER_SIZE = 1024;
    ExecutorService executors = Executors.newFixedThreadPool(2);
    try {
        Future<?> server = executors.submit(new Runnable() {

            @Override
            public void run() {
                // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365588(v=vs.85).aspx
                HANDLE hNamedPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateNamedPipe(pipeName, // dwOpenMode
                WinBase.PIPE_ACCESS_DUPLEX, // dwPipeMode
                WinBase.PIPE_TYPE_MESSAGE | WinBase.PIPE_READMODE_MESSAGE | WinBase.PIPE_WAIT, // nMaxInstances,
                1, // nOutBufferSize,
                MAX_BUFFER_SIZE, // nInBufferSize,
                MAX_BUFFER_SIZE, // nDefaultTimeOut,
                (int) TimeUnit.SECONDS.toMillis(30L), // lpSecurityAttributes
                null));
                try {
                    logger.info("Await client connection");
                    assertCallSucceeded("ConnectNamedPipe", Kernel32.INSTANCE.ConnectNamedPipe(hNamedPipe, null));
                    logger.info("Client connected");
                    byte[] readBuffer = new byte[MAX_BUFFER_SIZE];
                    IntByReference lpNumberOfBytesRead = new IntByReference(0);
                    assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hNamedPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null));
                    int readSize = lpNumberOfBytesRead.getValue();
                    logger.info("Received client data - length=" + readSize);
                    assertTrue("No data receieved from client", readSize > 0);
                    IntByReference lpNumberOfBytesWritten = new IntByReference(0);
                    assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hNamedPipe, readBuffer, readSize, lpNumberOfBytesWritten, null));
                    logger.info("Echoed client data - length=" + lpNumberOfBytesWritten.getValue());
                    assertEquals("Mismatched write buffer size", readSize, lpNumberOfBytesWritten.getValue());
                    // Flush the pipe to allow the client to read the pipe's contents before disconnecting
                    assertCallSucceeded("FlushFileBuffers", Kernel32.INSTANCE.FlushFileBuffers(hNamedPipe));
                    logger.info("Disconnecting");
                    assertCallSucceeded("DisconnectNamedPipe", Kernel32.INSTANCE.DisconnectNamedPipe(hNamedPipe));
                    logger.info("Disconnected");
                } finally {
                    // clean up
                    assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hNamedPipe));
                }
            }
        });
        logger.info("Started server - handle=" + server);
        Future<?> client = executors.submit(new Runnable() {

            @Override
            public void run() {
                // based on https://msdn.microsoft.com/en-us/library/windows/desktop/aa365592(v=vs.85).aspx
                assertCallSucceeded("WaitNamedPipe", Kernel32.INSTANCE.WaitNamedPipe(pipeName, (int) TimeUnit.SECONDS.toMillis(15L)));
                logger.info("Connected to server");
                HANDLE hPipe = assertValidHandle("CreateNamedPipe", Kernel32.INSTANCE.CreateFile(pipeName, WinNT.GENERIC_READ | WinNT.GENERIC_WRITE, // no sharing
                0, // default security attributes
                null, // opens existing pipe
                WinNT.OPEN_EXISTING, // default attributes
                0, // no template file
                null));
                try {
                    IntByReference lpMode = new IntByReference(WinBase.PIPE_READMODE_MESSAGE);
                    assertCallSucceeded("SetNamedPipeHandleState", Kernel32.INSTANCE.SetNamedPipeHandleState(hPipe, lpMode, null, null));
                    String expMessage = Thread.currentThread().getName() + " says hello";
                    byte[] expData = expMessage.getBytes();
                    IntByReference lpNumberOfBytesWritten = new IntByReference(0);
                    assertCallSucceeded("WriteFile", Kernel32.INSTANCE.WriteFile(hPipe, expData, expData.length, lpNumberOfBytesWritten, null));
                    logger.info("Sent hello message");
                    assertEquals("Mismatched write buffer size", expData.length, lpNumberOfBytesWritten.getValue());
                    byte[] readBuffer = new byte[MAX_BUFFER_SIZE];
                    IntByReference lpNumberOfBytesRead = new IntByReference(0);
                    assertCallSucceeded("ReadFile", Kernel32.INSTANCE.ReadFile(hPipe, readBuffer, readBuffer.length, lpNumberOfBytesRead, null));
                    int readSize = lpNumberOfBytesRead.getValue();
                    logger.info("Received server data - length=" + readSize);
                    assertTrue("No data receieved from server", readSize > 0);
                    String actMessage = new String(readBuffer, 0, readSize);
                    assertEquals("Mismatched server data", expMessage, actMessage);
                } finally {
                    // clean up
                    assertCallSucceeded("Named pipe handle close", Kernel32.INSTANCE.CloseHandle(hPipe));
                }
            }
        });
        logger.info("Started client - handle=" + client);
        for (Future<?> f : Arrays.asList(client, server)) {
            try {
                f.get(30L, TimeUnit.SECONDS);
                logger.info("Finished " + f);
            } catch (Exception e) {
                logger.warning(e.getClass().getSimpleName() + " while await completion of " + f + ": " + e.getMessage());
            }
        }
    } finally {
        executors.shutdownNow();
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) ExecutorService(java.util.concurrent.ExecutorService) Logger(java.util.logging.Logger) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) Test(org.junit.Test)

Example 57 with IntByReference

use of com.sun.jna.ptr.IntByReference in project jna by java-native-access.

the class MprTest method getLocalComputerName.

/**
     * Get local NETBIOS machine name
     * 
     * @return String with machine name
     * @throws Exception
     */
private String getLocalComputerName() throws Exception {
    IntByReference lpnSize = new IntByReference(0);
    // Get size of char array
    Kernel32.INSTANCE.GetComputerName(null, lpnSize);
    assertEquals(WinError.ERROR_BUFFER_OVERFLOW, Kernel32.INSTANCE.GetLastError());
    // Allocate character array
    char[] buffer = new char[WinBase.MAX_COMPUTERNAME_LENGTH + 1];
    lpnSize.setValue(buffer.length);
    assertTrue(Kernel32.INSTANCE.GetComputerName(buffer, lpnSize));
    // Return string with computer name
    String computerName = new String(buffer);
    computerName = computerName.trim();
    return computerName;
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference)

Example 58 with IntByReference

use of com.sun.jna.ptr.IntByReference in project jna by java-native-access.

the class MprTest method testWNetEnumConnection.

public void testWNetEnumConnection() throws Exception {
    // MSDN recommends this as a reasonable size
    int bufferSize = 16 * 1024;
    HANDLEByReference lphEnum = new HANDLEByReference();
    // Create a local share and connect to it. This ensures the enum will
    // find at least one entry.
    File fileShareFolder = createTempFolder();
    String share = createLocalShare(fileShareFolder);
    // Connect to local share
    connectToLocalShare(share, null);
    try {
        // Open an enumeration
        assertEquals(WinError.ERROR_SUCCESS, Mpr.INSTANCE.WNetOpenEnum(RESOURCESCOPE.RESOURCE_CONNECTED, RESOURCETYPE.RESOURCETYPE_DISK, RESOURCEUSAGE.RESOURCEUSAGE_ALL, null, lphEnum));
        int winError = WinError.ERROR_SUCCESS;
        while (true) {
            Memory memory = new Memory(bufferSize);
            IntByReference lpBufferSize = new IntByReference(bufferSize);
            IntByReference lpcCount = new IntByReference(1);
            // Get next value
            winError = Mpr.INSTANCE.WNetEnumResource(lphEnum.getValue(), lpcCount, memory, lpBufferSize);
            // Reached end of enumeration
            if (winError == WinError.ERROR_NO_MORE_ITEMS)
                break;
            // Unlikely, but means our buffer size isn't large enough.
            if (winError == WinError.ERROR_MORE_DATA) {
                bufferSize = bufferSize * 2;
                continue;
            }
            // If we get here, it means it has to be a success or our
            // programming logic was wrong.
            assertEquals(winError, WinError.ERROR_SUCCESS);
            // Asked for one, should only get one.
            assertEquals(1, lpcCount.getValue());
            // Create a NETRESOURCE based on the memory
            NETRESOURCE resource = new NETRESOURCE(memory);
            // Assert things we know for sure.
            assertNotNull(resource.lpRemoteName);
        }
        // Expect ERROR_NO_MORE_ITEMS here.
        assertEquals(winError, WinError.ERROR_NO_MORE_ITEMS);
    } finally {
        // Clean up resources
        Mpr.INSTANCE.WNetCloseEnum(lphEnum.getValue());
        disconnectFromLocalShare("\\\\" + getLocalComputerName() + "\\" + share);
        deleteLocalShare(share);
        fileShareFolder.delete();
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) Memory(com.sun.jna.Memory) HANDLEByReference(com.sun.jna.platform.win32.WinNT.HANDLEByReference) NETRESOURCE(com.sun.jna.platform.win32.Winnetwk.NETRESOURCE) File(java.io.File)

Example 59 with IntByReference

use of com.sun.jna.ptr.IntByReference in project jna by java-native-access.

the class MprTest method testWNetGetUniversalName.

public void testWNetGetUniversalName() throws Exception {
    // MSDN recommends this as a reasonable size
    int bufferSize = 1024;
    Memory memory = new Memory(bufferSize);
    IntByReference lpBufferSize = new IntByReference(bufferSize);
    File file = null;
    String share = null;
    String driveLetter = new String("x:");
    File fileShareFolder = createTempFolder();
    try {
        // Create a local share and connect to it.
        share = createLocalShare(fileShareFolder);
        // Connect to share using a drive letter.
        connectToLocalShare(share, driveLetter);
        // Create a path on local device redirected to the share.
        String filePath = new String(driveLetter + "\\testfile.txt");
        file = new File(filePath);
        file.createNewFile();
        // Test WNetGetUniversalName using UNIVERSAL_NAME_INFO_LEVEL
        assertEquals(WinError.ERROR_SUCCESS, Mpr.INSTANCE.WNetGetUniversalName(filePath, Winnetwk.UNIVERSAL_NAME_INFO_LEVEL, memory, lpBufferSize));
        UNIVERSAL_NAME_INFO uinfo = new UNIVERSAL_NAME_INFO(memory);
        assertNotNull(uinfo.lpUniversalName);
        // Test WNetGetUniversalName using REMOTE_NAME_INFO_LEVEL
        assertEquals(WinError.ERROR_SUCCESS, Mpr.INSTANCE.WNetGetUniversalName(filePath, Winnetwk.REMOTE_NAME_INFO_LEVEL, memory, lpBufferSize));
        REMOTE_NAME_INFO rinfo = new REMOTE_NAME_INFO(memory);
        assertNotNull(rinfo.lpUniversalName);
        assertNotNull(rinfo.lpConnectionName);
        assertNotNull(rinfo.lpRemainingPath);
    } finally {
        // Clean up resources
        if (file != null)
            file.delete();
        if (share != null) {
            disconnectFromLocalShare(driveLetter);
            deleteLocalShare(share);
            fileShareFolder.delete();
        }
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) Memory(com.sun.jna.Memory) REMOTE_NAME_INFO(com.sun.jna.platform.win32.Winnetwk.REMOTE_NAME_INFO) UNIVERSAL_NAME_INFO(com.sun.jna.platform.win32.Winnetwk.UNIVERSAL_NAME_INFO) File(java.io.File)

Example 60 with IntByReference

use of com.sun.jna.ptr.IntByReference in project jna by java-native-access.

the class Kernel32Test method testDeviceIoControlFsctlCompression.

public void testDeviceIoControlFsctlCompression() throws IOException {
    File tmp = File.createTempFile("testDeviceIoControlFsctlCompression", "jna");
    tmp.deleteOnExit();
    HANDLE hFile = Kernel32.INSTANCE.CreateFile(tmp.getAbsolutePath(), WinNT.GENERIC_ALL, WinNT.FILE_SHARE_READ, new WinBase.SECURITY_ATTRIBUTES(), WinNT.OPEN_EXISTING, WinNT.FILE_ATTRIBUTE_NORMAL, null);
    assertFalse(WinBase.INVALID_HANDLE_VALUE.equals(hFile));
    try {
        ShortByReference lpBuffer = new ShortByReference();
        IntByReference lpBytes = new IntByReference();
        if (false == Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_GET_COMPRESSION, null, 0, lpBuffer.getPointer(), USHORT.SIZE, lpBytes, null)) {
            fail("DeviceIoControl failed with " + Kernel32.INSTANCE.GetLastError());
        }
        assertEquals(WinNT.COMPRESSION_FORMAT_NONE, lpBuffer.getValue());
        assertEquals(USHORT.SIZE, lpBytes.getValue());
        lpBuffer = new ShortByReference((short) WinNT.COMPRESSION_FORMAT_LZNT1);
        if (false == Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_SET_COMPRESSION, lpBuffer.getPointer(), USHORT.SIZE, null, 0, lpBytes, null)) {
            fail("DeviceIoControl failed with " + Kernel32.INSTANCE.GetLastError());
        }
        if (false == Kernel32.INSTANCE.DeviceIoControl(hFile, FSCTL_GET_COMPRESSION, null, 0, lpBuffer.getPointer(), USHORT.SIZE, lpBytes, null)) {
            fail("DeviceIoControl failed with " + Kernel32.INSTANCE.GetLastError());
        }
        assertEquals(WinNT.COMPRESSION_FORMAT_LZNT1, lpBuffer.getValue());
        assertEquals(USHORT.SIZE, lpBytes.getValue());
    } finally {
        Kernel32Util.closeHandle(hFile);
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) ShortByReference(com.sun.jna.ptr.ShortByReference) File(java.io.File) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE)

Aggregations

IntByReference (com.sun.jna.ptr.IntByReference)199 PointerByReference (com.sun.jna.ptr.PointerByReference)38 Memory (com.sun.jna.Memory)33 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)26 File (java.io.File)19 Pointer (com.sun.jna.Pointer)15 Test (org.junit.Test)15 ArrayList (java.util.ArrayList)14 PSID (com.sun.jna.platform.win32.WinNT.PSID)13 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)11 SC_HANDLE (com.sun.jna.platform.win32.Winsvc.SC_HANDLE)11 HKEYByReference (com.sun.jna.platform.win32.WinReg.HKEYByReference)9 ACL (com.sun.jna.platform.win32.WinNT.ACL)8 Advapi32 (com.sun.jna.platform.win32.Advapi32)7 HRESULT (com.sun.jna.platform.win32.WinNT.HRESULT)7 ACCESS_ALLOWED_ACE (com.sun.jna.platform.win32.WinNT.ACCESS_ALLOWED_ACE)6 SECURITY_DESCRIPTOR (com.sun.jna.platform.win32.WinNT.SECURITY_DESCRIPTOR)6 HKEY (com.sun.jna.platform.win32.WinReg.HKEY)6 EVT_HANDLE (com.sun.jna.platform.win32.Winevt.EVT_HANDLE)6 CredHandle (com.sun.jna.platform.win32.Sspi.CredHandle)5