use of com.sun.jna.platform.win32.WinUser.SIZE in project jna by java-native-access.
the class Advapi32Test method testCreateWellKnownSid.
public void testCreateWellKnownSid() {
PSID pSid = new PSID(WinNT.SECURITY_MAX_SID_SIZE);
IntByReference cbSid = new IntByReference(WinNT.SECURITY_MAX_SID_SIZE);
assertTrue("Failed to create well-known SID", Advapi32.INSTANCE.CreateWellKnownSid(WELL_KNOWN_SID_TYPE.WinWorldSid, null, pSid, cbSid));
assertTrue("Not recognized as well-known SID", Advapi32.INSTANCE.IsWellKnownSid(pSid, WELL_KNOWN_SID_TYPE.WinWorldSid));
assertTrue("Invalid SID size", cbSid.getValue() <= WinNT.SECURITY_MAX_SID_SIZE);
PointerByReference convertedSidStringPtr = new PointerByReference();
assertTrue("Failed to convert SID", Advapi32.INSTANCE.ConvertSidToStringSid(pSid, convertedSidStringPtr));
Pointer conv = convertedSidStringPtr.getValue();
try {
String convertedSidString = conv.getWideString(0);
assertEquals("Mismatched SID string", EVERYONE, convertedSidString);
} finally {
Kernel32Util.freeLocalMemory(conv);
}
}
use of com.sun.jna.platform.win32.WinUser.SIZE in project jna by java-native-access.
the class SAFEARRAYTest method testADODB.
/**
* Test assumption: The windows search provider is present and holds at least
* five entries. If this assumption is not met, this test fails.
*/
@Test
public void testADODB() {
ObjectFactory fact = new ObjectFactory();
// Open a record set with a sample search (basicly get the first five
// entries from the search index
Connection conn = fact.createObject(Connection.class);
conn.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';", "", "", -1);
Recordset recordset = fact.createObject(Recordset.class);
recordset.Open("SELECT TOP 5 System.ItemPathDisplay, System.ItemName, System.ItemUrl, System.DateCreated FROM SYSTEMINDEX ORDER BY System.ItemUrl", conn, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, -1);
// Save complete list for comparison with subscript list
List<String> urls = new ArrayList<String>(5);
List<String> names = new ArrayList<String>(5);
while (!recordset.getEOF()) {
WinNT.HRESULT hr;
// Fetch (all) five rows and extract SAFEARRAY
SAFEARRAY sa = recordset.GetRows(5);
assertThat(sa.getDimensionCount(), is(2));
// Test getting bounds via automation functions SafeArrayGetLBound
// and SafeArrayGetUBound
// 5 rows (dimension 1) and 4 (dimension 2) columns should be
// returned, the indices are zero-based, the lower bounds are
// always zero
//
// Dimensions are inverted between SafeArray and java, so
// in this case row dimension 2 retrieves row count,
// dimension 1 retrieves column count
WinDef.LONGByReference res = new WinDef.LONGByReference();
hr = OleAuto.INSTANCE.SafeArrayGetLBound(sa, new UINT(2), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(0));
hr = OleAuto.INSTANCE.SafeArrayGetUBound(sa, new UINT(2), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(4));
hr = OleAuto.INSTANCE.SafeArrayGetLBound(sa, new UINT(1), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(0));
hr = OleAuto.INSTANCE.SafeArrayGetUBound(sa, new UINT(1), res);
assert COMUtils.SUCCEEDED(hr);
assertThat(res.getValue().intValue(), is(3));
// Get dimensions directly from structure
// lLbound contains lowerBound (first index)
// cElements contains count of elements
int row_lower = sa.rgsabound[0].lLbound.intValue();
int row_count = sa.rgsabound[0].cElements.intValue();
int column_lower = sa.rgsabound[1].lLbound.intValue();
int column_count = sa.rgsabound[1].cElements.intValue();
assertThat(row_lower, is(0));
assertThat(row_count, is(5));
assertThat(column_lower, is(0));
assertThat(column_count, is(4));
// Use Wrapper methods
assertThat(sa.getLBound(0), is(0));
assertThat(sa.getUBound(0), is(4));
assertThat(sa.getLBound(1), is(0));
assertThat(sa.getUBound(1), is(3));
// Columns 1 - 3 return Strings, Column 4 returns a date
for (int rowIdx = row_lower; rowIdx < row_lower + row_count; rowIdx++) {
for (int colIdx = column_lower; colIdx < column_lower + column_count; colIdx++) {
VARIANT result = (VARIANT) sa.getElement(rowIdx, colIdx);
Pointer pv = sa.ptrOfIndex(rowIdx, colIdx);
VARIANT result2 = new VARIANT(pv);
COMUtils.checkRC(hr);
if (colIdx == 3) {
assert (result.getVarType().intValue() & Variant.VT_DATE) > 0;
assert (result2.getVarType().intValue() & Variant.VT_DATE) > 0;
} else {
assert (result.getVarType().intValue() & Variant.VT_BSTR) > 0;
assert (result2.getVarType().intValue() & Variant.VT_BSTR) > 0;
}
// Only clear result, as SafeArrayGetElement creates a copy
// result2 is a view into the SafeArray
OleAuto.INSTANCE.VariantClear(result);
}
}
// Access SafeArray directly
sa.lock();
try {
// Map the returned array to java
VARIANT[] variantArray = (VARIANT[]) (new VARIANT(sa.pvData.getPointer()).toArray(row_count * column_count));
for (int rowIdx = 0; rowIdx < row_count; rowIdx++) {
for (int colIdx = 0; colIdx < column_count; colIdx++) {
int index = rowIdx * column_count + colIdx;
VARIANT result = variantArray[index];
if (colIdx == 3) {
assert (result.getVarType().intValue() & Variant.VT_DATE) > 0;
} else {
assert (result.getVarType().intValue() & Variant.VT_BSTR) > 0;
}
// see comment for urls
if (colIdx == 2) {
urls.add(result.stringValue());
} else if (colIdx == 1) {
names.add(result.stringValue());
}
}
}
} finally {
sa.unlock();
}
// Access SafeArray directly - Variant 2
Pointer data = sa.accessData();
try {
// Map the returned array to java
VARIANT[] variantArray = (VARIANT[]) (new VARIANT(data).toArray(row_count * column_count));
for (int rowIdx = 0; rowIdx < row_count; rowIdx++) {
for (int colIdx = 0; colIdx < column_count; colIdx++) {
int index = rowIdx * column_count + colIdx;
VARIANT result = variantArray[index];
if (colIdx == 3) {
assert (result.getVarType().intValue() & Variant.VT_DATE) > 0;
} else {
assert (result.getVarType().intValue() & Variant.VT_BSTR) > 0;
}
// see comment for urls
if (colIdx == 2) {
urls.add(result.stringValue());
} else if (colIdx == 1) {
names.add(result.stringValue());
}
}
}
} finally {
sa.unaccessData();
}
sa.destroy();
}
recordset.Close();
// Requery and fetch only columns "System.ItemUrl", "System.ItemName" and "System.ItemUrl"
recordset = fact.createObject(Recordset.class);
recordset.Open("SELECT TOP 5 System.ItemPathDisplay, System.ItemName, System.ItemUrl FROM SYSTEMINDEX ORDER BY System.ItemUrl", conn, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, -1);
// Create SAFEARRAY and wrap it into a VARIANT
// Array is initialized to one element and then redimmed. This is done
// to test SafeArrayRedim, in normal usage it is more efficient to
// intitialize directly to the correct size
SAFEARRAY arr = SAFEARRAY.createSafeArray(1);
arr.putElement(new VARIANT("System.ItemUrl"), 0);
boolean exceptionCaught = false;
try {
arr.putElement(new VARIANT("System.ItemName"), 1);
} catch (COMException ex) {
exceptionCaught = true;
}
assertTrue("Array is initialized to a size of one - it can't hold a second item.", exceptionCaught);
arr.redim(2, 0);
arr.putElement(new VARIANT("System.ItemName"), 1);
assertThat(arr.getDimensionCount(), is(1));
VARIANT columnList = new VARIANT();
columnList.setValue(Variant.VT_ARRAY | Variant.VT_VARIANT, arr);
assert !(recordset.getEOF());
while (!recordset.getEOF()) {
SAFEARRAY sa = recordset.GetRows(5, VARIANT.VARIANT_MISSING, columnList);
assertThat(sa.getDimensionCount(), is(2));
assertThat(sa.getVarType().intValue(), is(Variant.VT_VARIANT));
LONGByReference longRef = new LONGByReference();
OleAuto.INSTANCE.SafeArrayGetLBound(sa, new UINT(2), longRef);
int lowerBound = longRef.getValue().intValue();
assertThat(sa.getLBound(0), equalTo(lowerBound));
OleAuto.INSTANCE.SafeArrayGetUBound(sa, new UINT(2), longRef);
int upperBound = longRef.getValue().intValue();
assertThat(sa.getUBound(0), equalTo(upperBound));
// 5 rows are expected
assertThat(upperBound - lowerBound + 1, is(5));
for (int rowIdx = lowerBound; rowIdx <= upperBound; rowIdx++) {
VARIANT variantItemUrl = (VARIANT) sa.getElement(rowIdx, 0);
VARIANT variantItemName = (VARIANT) sa.getElement(rowIdx, 1);
assertThat(variantItemUrl.stringValue(), is(urls.get(rowIdx)));
assertThat(variantItemName.stringValue(), is(names.get(rowIdx)));
OleAuto.INSTANCE.VariantClear(variantItemUrl);
OleAuto.INSTANCE.VariantClear(variantItemName);
}
sa.destroy();
}
recordset.Close();
// Requery and fetch only columns "System.ItemUrl", "System.ItemName" and "System.ItemUrl"
recordset = fact.createObject(Recordset.class);
recordset.Open("SELECT TOP 5 System.ItemPathDisplay, System.ItemName, System.ItemUrl FROM SYSTEMINDEX ORDER BY System.ItemUrl", conn, CursorTypeEnum.adOpenUnspecified, LockTypeEnum.adLockUnspecified, -1);
assert !(recordset.getEOF());
while (!recordset.getEOF()) {
Object[][] data = (Object[][]) OaIdlUtil.toPrimitiveArray(recordset.GetRows(5, VARIANT.VARIANT_MISSING, columnList), true);
assertThat(data.length, is(5));
assertThat(data[0].length, is(2));
for (int rowIdx = 0; rowIdx < data.length; rowIdx++) {
assertThat((String) data[rowIdx][0], is(urls.get(rowIdx)));
assertThat((String) data[rowIdx][1], is(names.get(rowIdx)));
}
}
recordset.Close();
conn.Close();
fact.disposeAll();
}
use of com.sun.jna.platform.win32.WinUser.SIZE in project jna by java-native-access.
the class User32WindowMessagesTest method testWindowMesssages.
/**
* Instantiates 2 windows and make them communicate through windows messages, even complex ones throught
* WM_COPYDATA.
*/
@Test
public void testWindowMesssages() {
// note : check the asserts that are present in the callback implementations here after.
// Create window 1 named "ping"
createWindow("ping");
// let windows create the window before searching its handle.
sleepCurrThread(4000);
// Retrieves the created window's handle.
HWND hwndPing = determineHWNDFromWindowClass("ping");
assertNotNull(hwndPing);
HHOOK hook = null;
try {
// DEMO 1 : sends a simple message to ping window with code MSG_CODE and value 123456.
LRESULT result = User32.INSTANCE.SendMessage(hwndPing, WinUser.WM_USER, new WPARAM(MSG_SIMPLE_CODE), new LPARAM(MSG_SIMPLE_VAL));
log("User Message sent to " + hwndPing + ", result = " + result);
assertEquals(0, result.doubleValue(), 0);
// DEMO 2 : send of structured message.
// copyDataStruct must be held strongly on the java side.
// cf : https://github.com/java-native-access/jna/pull/774 comments.
COPYDATASTRUCT copyDataStruct = createStructuredMessage();
result = User32.INSTANCE.SendMessage(hwndPing, WinUser.WM_COPYDATA, null, /* No current hwnd for this demo */
new LPARAM(Pointer.nativeValue(copyDataStruct.getPointer())));
log("COPYDATASTRUCT sent message to " + hwndPing + "(size=" + copyDataStruct.size() + ") code =" + copyDataStruct.dwData);
assertEquals(0, result.intValue());
assertEquals(DATA_STRUCT_CODE, copyDataStruct.dwData.doubleValue(), 0);
// DEMO 3 : hook winproc then send a message to the hooked proc.
hook = hookwinProc(hwndPing);
result = User32.INSTANCE.SendMessage(hwndPing, WinUser.WM_USER, new WPARAM(MSG_HOOKED_CODE), new LPARAM(MSG_HOOKED_VAL));
log("User Message sent to hooked proc " + hwndPing + ", result = " + result);
assertEquals(0, result.intValue());
// Waits e few moment before shutdown message.
sleepCurrThread(3000);
} finally {
try {
// checks that there has been no exception in the created thread for windows messages receival.
assertNull("Unexpected exception in created Thread : " + exceptionInCreatedThread, exceptionInCreatedThread);
//assert done in a try block in order not to block the WM_CLOSE message sending.
} finally {
User32.INSTANCE.PostMessage(hwndPing, WinUser.WM_CLOSE, null, null);
log("WM_CLOSE posted to " + hwndPing);
// Remember to unhook the win proc.
if (hook != null) {
User32.INSTANCE.UnhookWindowsHookEx(hook);
}
log("Unhook done correctly");
}
}
}
use of com.sun.jna.platform.win32.WinUser.SIZE 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.platform.win32.WinUser.SIZE 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();
}
}
Aggregations