Search in sources :

Example 6 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class WevtapiTest method testReadEvents.

public void testReadEvents() throws Exception {
    EVT_HANDLE queryHandle = null;
    EVT_HANDLE contextHandle = null;
    File testEvtx = new File(getClass().getResource("/res/WevtapiTest.sample1.evtx").toURI());
    StringBuilder sb = new StringBuilder();
    try {
        // test EvtQuery
        queryHandle = Wevtapi.INSTANCE.EvtQuery(null, testEvtx.getPath(), null, Winevt.EVT_QUERY_FLAGS.EvtQueryFilePath);
        // test EvtCreateRenderContext
        String[] targets = { "Event/System/Provider/@Name", "Event/System/EventRecordID", "Event/System/EventID", "Event/EventData/Data", "Event/System/TimeCreated/@SystemTime" };
        contextHandle = Wevtapi.INSTANCE.EvtCreateRenderContext(targets.length, targets, Winevt.EVT_RENDER_CONTEXT_FLAGS.EvtRenderContextValues);
        // test EvtNext
        int eventArraySize = 10;
        int evtNextTimeout = 1000;
        int arrayIndex = 0;
        EVT_HANDLE[] eventArray = new EVT_HANDLE[eventArraySize];
        IntByReference returned = new IntByReference();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        while (Wevtapi.INSTANCE.EvtNext(queryHandle, eventArraySize, eventArray, evtNextTimeout, 0, returned)) {
            // test EvtRender
            Memory buff;
            IntByReference propertyCount = new IntByReference();
            Winevt.EVT_VARIANT evtVariant = new Winevt.EVT_VARIANT();
            for (int i = 0; i < returned.getValue(); i++) {
                buff = WevtapiUtil.EvtRender(contextHandle, eventArray[i], Winevt.EVT_RENDER_FLAGS.EvtRenderEventValues, propertyCount);
                assertThat("PropertyCount", propertyCount.getValue(), is(5));
                useMemory(evtVariant, buff, 0);
                assertThat("Provider Name", (String) evtVariant.getValue(), is("testSource"));
                sb.append((String) evtVariant.getValue());
                useMemory(evtVariant, buff, 1);
                assertThat("EventRecordID", (Long) evtVariant.getValue(), is((long) arrayIndex * eventArraySize + i + 1));
                useMemory(evtVariant, buff, 2);
                assertThat("EventID", (Short) evtVariant.getValue(), is((short) (5000 + (arrayIndex * eventArraySize + i + 1))));
                useMemory(evtVariant, buff, 3);
                String[] args = (String[]) evtVariant.getValue();
                assertThat("Data#length", args.length, is(1));
                assertThat("Data#value", args[0], is("testMessage" + (arrayIndex * eventArraySize + i + 1)));
                useMemory(evtVariant, buff, 4);
                Date systemtime = ((WinBase.FILETIME) evtVariant.getValue()).toDate();
                assertThat("TimeCreated", dateFormat.format(systemtime), is("2016-08-17"));
            }
            arrayIndex++;
        }
        if (Kernel32.INSTANCE.GetLastError() != WinError.ERROR_SUCCESS && Kernel32.INSTANCE.GetLastError() != WinError.ERROR_NO_MORE_ITEMS) {
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        }
        assertThat(sb.length() > 0, is(true));
    } finally {
        // test EvtClose
        if (queryHandle != null) {
            Wevtapi.INSTANCE.EvtClose(queryHandle);
        }
        if (contextHandle != null) {
            Wevtapi.INSTANCE.EvtClose(contextHandle);
        }
    }
    // =========== Test accessing binary data and empty value ================
    queryHandle = null;
    contextHandle = null;
    testEvtx = new File(getClass().getResource("/res/WevtapiTest.sample2.evtx").toURI());
    try {
        queryHandle = Wevtapi.INSTANCE.EvtQuery(null, testEvtx.getPath(), null, Winevt.EVT_QUERY_FLAGS.EvtQueryFilePath);
        String[] targets = { "Event/EventData/Binary", "Event/System/Correlation" };
        contextHandle = Wevtapi.INSTANCE.EvtCreateRenderContext(targets.length, targets, Winevt.EVT_RENDER_CONTEXT_FLAGS.EvtRenderContextValues);
        int read = 0;
        int eventArraySize = 1;
        int evtNextTimeout = 1000;
        EVT_HANDLE[] eventArray = new EVT_HANDLE[eventArraySize];
        IntByReference returned = new IntByReference();
        while (Wevtapi.INSTANCE.EvtNext(queryHandle, eventArraySize, eventArray, evtNextTimeout, 0, returned)) {
            Memory buff;
            IntByReference propertyCount = new IntByReference();
            Winevt.EVT_VARIANT evtVariant = new Winevt.EVT_VARIANT();
            for (int i = 0; i < returned.getValue(); i++) {
                read++;
                buff = WevtapiUtil.EvtRender(contextHandle, eventArray[i], Winevt.EVT_RENDER_FLAGS.EvtRenderEventValues, propertyCount);
                assertThat("PropertyCount", propertyCount.getValue(), is(2));
                useMemory(evtVariant, buff, 0);
                assertThat("Binary", (byte[]) evtVariant.getValue(), is(new byte[] { (byte) 0xD9, (byte) 0x06, 0, 0 }));
                useMemory(evtVariant, buff, 1);
                assertThat("Correlation", evtVariant.getValue(), nullValue());
            }
        }
        assertThat(read, is(1));
    } finally {
        // test EvtClose
        if (queryHandle != null) {
            Wevtapi.INSTANCE.EvtClose(queryHandle);
        }
        if (contextHandle != null) {
            Wevtapi.INSTANCE.EvtClose(contextHandle);
        }
    }
    // =========== Test accessing GUID + SID data ================
    queryHandle = null;
    contextHandle = null;
    testEvtx = new File(getClass().getResource("/res/WevtapiTest.sample3.evtx").toURI());
    try {
        queryHandle = Wevtapi.INSTANCE.EvtQuery(null, testEvtx.getPath(), null, Winevt.EVT_QUERY_FLAGS.EvtQueryFilePath);
        String[] targets = { "Event/System/Security/@UserID", "Event/System/Provider/@Guid" };
        contextHandle = Wevtapi.INSTANCE.EvtCreateRenderContext(targets.length, targets, Winevt.EVT_RENDER_CONTEXT_FLAGS.EvtRenderContextValues);
        int read = 0;
        int eventArraySize = 1;
        int evtNextTimeout = 1000;
        EVT_HANDLE[] eventArray = new EVT_HANDLE[eventArraySize];
        IntByReference returned = new IntByReference();
        while (Wevtapi.INSTANCE.EvtNext(queryHandle, eventArraySize, eventArray, evtNextTimeout, 0, returned)) {
            Memory buff;
            IntByReference propertyCount = new IntByReference();
            Winevt.EVT_VARIANT evtVariant = new Winevt.EVT_VARIANT();
            for (int i = 0; i < returned.getValue(); i++) {
                read++;
                buff = WevtapiUtil.EvtRender(contextHandle, eventArray[i], Winevt.EVT_RENDER_FLAGS.EvtRenderEventValues, propertyCount);
                assertThat("PropertyCount", propertyCount.getValue(), is(2));
                useMemory(evtVariant, buff, 0);
                assertThat("Security#UserID", ((WinNT.PSID) evtVariant.getValue()).getSidString(), is("S-1-5-21-3178902164-3053647283-518304804-1001"));
                useMemory(evtVariant, buff, 1);
                assertThat("Provider#GUID", ((Guid.GUID) evtVariant.getValue()).toGuidString(), is("{B0AA8734-56F7-41CC-B2F4-DE228E98B946}"));
            }
        }
        assertThat(read, is(1));
    } finally {
        // test EvtClose
        if (queryHandle != null) {
            Wevtapi.INSTANCE.EvtClose(queryHandle);
        }
        if (contextHandle != null) {
            Wevtapi.INSTANCE.EvtClose(contextHandle);
        }
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) Memory(com.sun.jna.Memory) Date(java.util.Date) EVT_HANDLE(com.sun.jna.platform.win32.Winevt.EVT_HANDLE) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 7 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class WevtapiTest method testEvtGetQueryInfo.

public void testEvtGetQueryInfo() throws Exception {
    EVT_HANDLE queryHandle = null;
    try {
        queryHandle = Wevtapi.INSTANCE.EvtQuery(null, "Application", null, Winevt.EVT_QUERY_FLAGS.EvtQueryChannelPath);
        Memory buff = new Memory(1024);
        IntByReference bufferUsed = new IntByReference();
        if (!Wevtapi.INSTANCE.EvtGetQueryInfo(queryHandle, Winevt.EVT_QUERY_PROPERTY_ID.EvtQueryNames, (int) buff.size(), buff, bufferUsed)) {
            if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_INSUFFICIENT_BUFFER) {
                buff = new Memory(bufferUsed.getValue());
                if (!Wevtapi.INSTANCE.EvtGetQueryInfo(queryHandle, Winevt.EVT_QUERY_PROPERTY_ID.EvtQueryNames, (int) buff.size(), buff, bufferUsed)) {
                    throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
                }
            }
        }
        Winevt.EVT_VARIANT evtVariant = new Winevt.EVT_VARIANT(buff.share(0));
        evtVariant.readField("Type");
        StringBuilder sb = new StringBuilder();
        evtVariant.readField("Count");
        int count = evtVariant.Count;
        useMemory(evtVariant, buff, 0);
        String[] queryNames = (String[]) evtVariant.getValue();
        for (int i = 0; i < count; i++) {
            sb.append(queryNames[i]);
        }
        assertThat(sb.toString(), is("Application"));
    } finally {
        if (queryHandle != null) {
            Wevtapi.INSTANCE.EvtClose(queryHandle);
        }
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) EVT_HANDLE(com.sun.jna.platform.win32.Winevt.EVT_HANDLE) Memory(com.sun.jna.Memory)

Example 8 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class PsapiTest method testGetProcessImageFileName.

@Test
public void testGetProcessImageFileName() {
    HANDLE me = null;
    Win32Exception we = null;
    try {
        me = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_ALL_ACCESS, false, Kernel32.INSTANCE.GetCurrentProcessId());
        assertTrue("Handle to my process should not be null", me != null);
        char[] buffer = new char[256];
        Psapi.INSTANCE.GetProcessImageFileName(me, buffer, 256);
        String path = new String(buffer);
        assertTrue("Image path should contain 'java' and '.exe'", path.contains("java") && path.contains(".exe"));
    } catch (Win32Exception e) {
        we = e;
        // re-throw to invoke finally block
        throw we;
    } finally {
        try {
            Kernel32Util.closeHandle(me);
        } catch (Win32Exception e) {
            if (we == null) {
                we = e;
            } else {
                we.addSuppressed(e);
            }
        }
        if (we != null) {
            throw we;
        }
    }
}
Also used : HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) Test(org.junit.Test)

Example 9 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class PsapiTest method testEnumProcessModules.

@Test
public void testEnumProcessModules() {
    HANDLE me = null;
    Win32Exception we = null;
    try {
        me = Kernel32.INSTANCE.OpenProcess(WinNT.PROCESS_ALL_ACCESS, false, Kernel32.INSTANCE.GetCurrentProcessId());
        assertTrue("Handle to my process should not be null", me != null);
        List<HMODULE> list = new LinkedList<HMODULE>();
        HMODULE[] lphModule = new HMODULE[100 * 4];
        IntByReference lpcbNeeded = new IntByReference();
        if (!Psapi.INSTANCE.EnumProcessModules(me, lphModule, lphModule.length, lpcbNeeded)) {
            throw new Win32Exception(Native.getLastError());
        }
        for (int i = 0; i < lpcbNeeded.getValue() / 4; i++) {
            list.add(lphModule[i]);
        }
        assertTrue("List should have at least 1 item in it.", list.size() > 0);
    } catch (Win32Exception e) {
        we = e;
        // re-throw to invoke finally block
        throw we;
    } finally {
        try {
            Kernel32Util.closeHandle(me);
        } catch (Win32Exception e) {
            if (we == null) {
                we = e;
            } else {
                we.addSuppressed(e);
            }
        }
        if (we != null) {
            throw we;
        }
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) HMODULE(com.sun.jna.platform.win32.WinDef.HMODULE) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 10 with Win32Exception

use of com.sun.jna.platform.win32.Win32Exception in project jna by java-native-access.

the class PsapiTest method testGetModuleFileNameEx.

@Test
public void testGetModuleFileNameEx() {
    final JFrame w = new JFrame();
    try {
        w.setVisible(true);
        final String searchSubStr = "\\bin\\java";
        final HWND hwnd = new HWND(Native.getComponentPointer(w));
        final IntByReference pid = new IntByReference();
        User32.INSTANCE.GetWindowThreadProcessId(hwnd, pid);
        final HANDLE process = Kernel32.INSTANCE.OpenProcess(0x0400 | 0x0010, false, pid.getValue());
        if (process == null)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        // check ANSI function
        final byte[] filePathAnsi = new byte[1025];
        int length = Psapi.INSTANCE.GetModuleFileNameExA(process, null, filePathAnsi, filePathAnsi.length - 1);
        if (length == 0)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        assertTrue("Path didn't contain '" + searchSubStr + "': " + Native.toString(filePathAnsi), Native.toString(filePathAnsi).toLowerCase().contains(searchSubStr));
        // check Unicode function
        final char[] filePathUnicode = new char[1025];
        length = Psapi.INSTANCE.GetModuleFileNameExW(process, null, filePathUnicode, filePathUnicode.length - 1);
        if (length == 0)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        assertTrue("Path didn't contain '" + searchSubStr + "': " + Native.toString(filePathUnicode), Native.toString(filePathUnicode).toLowerCase().contains(searchSubStr));
        // check default function
        final int memAllocSize = 1025 * Native.WCHAR_SIZE;
        final Memory filePathDefault = new Memory(memAllocSize);
        length = Psapi.INSTANCE.GetModuleFileNameEx(process, null, filePathDefault, (memAllocSize / Native.WCHAR_SIZE) - 1);
        if (length == 0)
            throw new Win32Exception(Kernel32.INSTANCE.GetLastError());
        assertTrue("Path didn't contain '" + searchSubStr + "': " + Native.toString(filePathDefault.getCharArray(0, memAllocSize / Native.WCHAR_SIZE)), Native.toString(filePathDefault.getCharArray(0, memAllocSize / Native.WCHAR_SIZE)).toLowerCase().contains(searchSubStr));
    } finally {
        w.dispose();
    }
}
Also used : IntByReference(com.sun.jna.ptr.IntByReference) JFrame(javax.swing.JFrame) Memory(com.sun.jna.Memory) HWND(com.sun.jna.platform.win32.WinDef.HWND) HANDLE(com.sun.jna.platform.win32.WinNT.HANDLE) Test(org.junit.Test)

Aggregations

IntByReference (com.sun.jna.ptr.IntByReference)35 HKEYByReference (com.sun.jna.platform.win32.WinReg.HKEYByReference)18 HANDLE (com.sun.jna.platform.win32.WinNT.HANDLE)17 Memory (com.sun.jna.Memory)15 PointerByReference (com.sun.jna.ptr.PointerByReference)11 ArrayList (java.util.ArrayList)11 EVT_HANDLE (com.sun.jna.platform.win32.Winevt.EVT_HANDLE)7 Pointer (com.sun.jna.Pointer)6 File (java.io.File)6 HANDLEByReference (com.sun.jna.platform.win32.WinNT.HANDLEByReference)5 Test (org.junit.Test)5 DWORD (com.sun.jna.platform.win32.WinDef.DWORD)4 HRESULT (com.sun.jna.platform.win32.WinNT.HRESULT)4 PSID (com.sun.jna.platform.win32.WinNT.PSID)4 Win32Exception (com.sun.jna.platform.win32.Win32Exception)3 HMODULE (com.sun.jna.platform.win32.WinDef.HMODULE)3 LOCALGROUP_INFO_1 (com.sun.jna.platform.win32.LMAccess.LOCALGROUP_INFO_1)2 LOCALGROUP_USERS_INFO_0 (com.sun.jna.platform.win32.LMAccess.LOCALGROUP_USERS_INFO_0)2 DATA_BLOB (com.sun.jna.platform.win32.WinCrypt.DATA_BLOB)2 DWORDByReference (com.sun.jna.platform.win32.WinDef.DWORDByReference)2