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();
}
}
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;
}
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();
}
}
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();
}
}
}
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);
}
}
Aggregations