Java Code Examples for com.sun.jna.platform.win32.WinNT#HANDLE

The following examples show how to use com.sun.jna.platform.win32.WinNT#HANDLE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static List<WinNT.HANDLE> mockEventHandles(WEvtApi wEvtApi, Kernel32 kernel32, List<String> eventXmls) {
    List<WinNT.HANDLE> eventHandles = new ArrayList<>();
    for (String eventXml : eventXmls) {
        WinNT.HANDLE eventHandle = mock(WinNT.HANDLE.class);
        when(wEvtApi.EvtRender(isNull(), eq(eventHandle), eq(WEvtApi.EvtRenderFlags.EVENT_XML),
                anyInt(), any(Pointer.class), any(Pointer.class), any(Pointer.class))).thenAnswer(invocation -> {
            Object[] arguments = invocation.getArguments();
            Pointer bufferUsed = (Pointer) arguments[5];
            byte[] array = StandardCharsets.UTF_16LE.encode(eventXml).array();
            if (array.length > (int) arguments[3]) {
                when(kernel32.GetLastError()).thenReturn(W32Errors.ERROR_INSUFFICIENT_BUFFER).thenReturn(W32Errors.ERROR_SUCCESS);
            } else {
                ((Pointer) arguments[4]).write(0, array, 0, array.length);
            }
            bufferUsed.setInt(0, array.length);
            return false;
        });
        eventHandles.add(eventHandle);
    }
    return eventHandles;
}
 
Example 2
Source File: WindowsProcessExecutor.java    From Java-Auto-Update with Apache License 2.0 6 votes vote down vote up
@Override
public String findProcessId(Process process) throws NoSuchFieldException, IllegalAccessException {
    if (process.getClass().getName().equals("java.lang.Win32Process")
            || process.getClass().getName().equals("java.lang.ProcessImpl")) {
            Field f = process.getClass().getDeclaredField("handle");
            f.setAccessible(true);
            long handleNumber = f.getLong(process);

            Kernel32 kernel = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(handleNumber));
            int pid = kernel.GetProcessId(handle);
            log.debug("Found pid for managed process: {}", pid);
            return pid + "";
    }
    return null;
}
 
Example 3
Source File: SpringBootManagedContainer.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected static Integer windowsProcessId(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    /* determine the pid on windows plattforms */
    try {
      Field f = process.getClass().getDeclaredField("handle");
      f.setAccessible(true);
      long handl = f.getLong(process);

      Kernel32 kernel = Kernel32.INSTANCE;
      WinNT.HANDLE handle = new WinNT.HANDLE();
      handle.setPointer(Pointer.createConstant(handl));
      int ret = kernel.GetProcessId(handle);
      log.debug("Detected pid: {}", ret);
      return ret;
    } catch (Throwable ex) {
      throw new RuntimeException("Cannot fetch windows pid!", ex);
    }
  }
  return null;
}
 
Example 4
Source File: OSUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * @param process NiFi Process Reference
 * @param logger  Logger Reference for Debug
 * @return        Returns pid or null in-case pid could not be determined
 * This method takes {@link Process} and {@link Logger} and returns
 * the platform specific Handle for Win32 Systems, a.k.a <b>pid</b>
 * In-case it fails to determine the pid, it will return Null.
 * Purpose for the Logger is to log any interaction for debugging.
 */
private static Long getWindowsProcessId(final Process process, final Logger logger) {
    /* determine the pid on windows plattforms */
    try {
        Field f = process.getClass().getDeclaredField("handle");
        f.setAccessible(true);
        long handl = f.getLong(process);

        Kernel32 kernel = Kernel32.INSTANCE;
        WinNT.HANDLE handle = new WinNT.HANDLE();
        handle.setPointer(Pointer.createConstant(handl));
        int ret = kernel.GetProcessId(handle);
        logger.debug("Detected pid: {}", ret);
        return Long.valueOf(ret);
    } catch (final IllegalAccessException | NoSuchFieldException nsfe) {
        logger.debug("Could not find PID for child process due to {}", nsfe);
    }
    return null;
}
 
Example 5
Source File: ConsumeWindowsEventLogTest.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test(expected = ProcessException.class)
public void testScheduleQueueStopThrowsException() throws Throwable {
    ReflectionUtils.invokeMethodsWithAnnotation(OnScheduled.class, evtSubscribe, testRunner.getProcessContext());

    WinNT.HANDLE handle = mockEventHandles(wEvtApi, kernel32, Arrays.asList("test")).get(0);
    getRenderingCallback().onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, handle);

    try {
        ReflectionUtils.invokeMethodsWithAnnotation(OnStopped.class, evtSubscribe, testRunner.getProcessContext());
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}
 
Example 6
Source File: ConsumeWindowsEventLogTest.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10 * 1000)
public void testProcessesBlockedEvents() throws UnsupportedEncodingException {
    testRunner.setProperty(ConsumeWindowsEventLog.MAX_EVENT_QUEUE_SIZE, "1");
    testRunner.run(1, false, true);
    EventSubscribeXmlRenderingCallback renderingCallback = getRenderingCallback();

    List<String> eventXmls = Arrays.asList("one", "two", "three", "four", "five", "six");
    List<WinNT.HANDLE> eventHandles = mockEventHandles(wEvtApi, kernel32, eventXmls);
    AtomicBoolean done = new AtomicBoolean(false);
    new Thread(() -> {
        for (WinNT.HANDLE eventHandle : eventHandles) {
            renderingCallback.onEvent(WEvtApi.EvtSubscribeNotifyAction.DELIVER, null, eventHandle);
        }
        done.set(true);
    }).start();

    // Wait until the thread has really started
    while (testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS).size() == 0) {
        testRunner.run(1, false, false);
    }

    // Process rest of events
    while (!done.get()) {
        testRunner.run(1, false, false);
    }

    testRunner.run(1, true, false);

    List<MockFlowFile> flowFilesForRelationship = testRunner.getFlowFilesForRelationship(ConsumeWindowsEventLog.REL_SUCCESS);
    assertEquals(eventXmls.size(), flowFilesForRelationship.size());
    for (int i = 0; i < eventXmls.size(); i++) {
        flowFilesForRelationship.get(i).assertContentEquals(eventXmls.get(i));
    }
}
 
Example 7
Source File: SystemService.java    From winthing with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("DM_CONVERT_CASE")
public Map<Integer, String> findProcesses(final String nameFragment) {
    Objects.requireNonNull(nameFragment);

    final String lowercaseNameFragment = nameFragment.toLowerCase();
    final Map<Integer, String> processIds = new HashMap<>();

    final WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(
        Tlhelp32.TH32CS_SNAPPROCESS,
        null
    );
    try {
        final Tlhelp32.PROCESSENTRY32.ByReference entryReference =
            new Tlhelp32.PROCESSENTRY32.ByReference();
        if (kernel32.Process32First(snapshot, entryReference)) {
            while (kernel32.Process32Next(snapshot, entryReference)) {
                final String processName = new String(entryReference.szExeFile).trim();
                if (processName.toLowerCase().contains(lowercaseNameFragment)) {
                    processIds.put(entryReference.th32ProcessID.intValue(), processName);
                }
            }
        }
    } finally {
        kernel32.CloseHandle(snapshot);
    }

    return processIds;
}
 
Example 8
Source File: Jna.java    From ipc-eventbus with Apache License 2.0 5 votes vote down vote up
static long getWindowsPid(Process process) {
  if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) {
    try {
      Field f = process.getClass().getDeclaredField("handle");
      f.setAccessible(true);
      long handl = f.getLong(process);
      Kernel32 kernel = Kernel32.INSTANCE;
      WinNT.HANDLE handle = new WinNT.HANDLE();
      handle.setPointer(Pointer.createConstant(handl));
      return kernel.GetProcessId(handle);
    } catch (Throwable ignored) {
    }
  }
  return -1;
}
 
Example 9
Source File: WindowsNamedPipeLibrary.java    From buck with Apache License 2.0 4 votes vote down vote up
boolean ReadFile(
WinNT.HANDLE hFile,
Memory pointer,
int nNumberOfBytesToRead,
IntByReference lpNumberOfBytesRead,
Pointer lpOverlapped);
 
Example 10
Source File: WEvtApi.java    From nifi with Apache License 2.0 4 votes vote down vote up
WinNT.HANDLE EvtSubscribe(WinNT.HANDLE session, WinNT.HANDLE signalEvent, String channelName, String xpathQuery,
WinNT.HANDLE bookmark, WinDef.PVOID context, EVT_SUBSCRIBE_CALLBACK evtSubscribeCallback, int flags);
 
Example 11
Source File: WindowsNamedPipe.java    From buck with Apache License 2.0 4 votes vote down vote up
private static WinBase.OVERLAPPED createOverlapped(WinNT.HANDLE event) {
  WinBase.OVERLAPPED olap = new WinBase.OVERLAPPED();
  olap.hEvent = event;
  olap.write();
  return olap;
}
 
Example 12
Source File: WindowsNamedPipeLibrary.java    From buck with Apache License 2.0 4 votes vote down vote up
boolean WriteFile(
WinNT.HANDLE hFile,
ByteBuffer lpBuffer,
int nNumberOfBytesToWrite,
IntByReference lpNumberOfBytesWritten,
Pointer lpOverlapped);
 
Example 13
Source File: WEvtApi.java    From nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Callback method that will be invoked when new events come in
 *
 * @param evtSubscribeNotifyAction the notify action
 * @param userContext              the user context
 * @param eventHandle              the event handle
 * @return an int that will be ignored by the Windows Log API (https://msdn.microsoft.com/en-us/library/windows/desktop/aa385577(v=vs.85).aspx)
 */
int onEvent(int evtSubscribeNotifyAction, WinDef.PVOID userContext, WinNT.HANDLE eventHandle);
 
Example 14
Source File: WEvtApi.java    From localization_nifi with Apache License 2.0 2 votes vote down vote up
/**
 * Callback method that will be invoked when new events come in
 *
 * @param evtSubscribeNotifyAction the notify action
 * @param userContext              the user context
 * @param eventHandle              the event handle
 * @return an int that will be ignored by the Windows Log API (https://msdn.microsoft.com/en-us/library/windows/desktop/aa385577(v=vs.85).aspx)
 */
int onEvent(int evtSubscribeNotifyAction, WinDef.PVOID userContext, WinNT.HANDLE eventHandle);
 
Example 15
Source File: Kernel32RW.java    From Flashtool with GNU General Public License v3.0 2 votes vote down vote up
/** 
 * Read data from USB HID device.
 */
boolean ReadFile(WinNT.HANDLE Handle, byte[] buffer, int nNumberOfBytesToRead,  IntByReference NumberOfBytesRead,  OVERLAPPED Overlapped);
 
Example 16
Source File: Kernel32Lib.java    From sheepit-client with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Retrieves information about the first process encountered in a system snapshot.
 *
 * @param hSnapshot A handle to the snapshot returned from a previous call to the CreateToolhelp32Snapshot function.
 * @param lppe      A pointer to a PROCESSENTRY32 structure. It contains process information such as the name of the
 *                  executable file, the process identifier, and the process identifier of the parent process.
 * @return Returns TRUE if the first entry of the process list has been copied to the buffer or FALSE otherwise. The
 * ERROR_NO_MORE_FILES error value is returned by the GetLastError function if no processes exist or the snapshot
 * does not contain process information.
 */
public boolean Process32First(WinNT.HANDLE hSnapshot, Kernel32Lib.PROCESSENTRY32.ByReference lppe);
 
Example 17
Source File: WindowsNamedPipeLibrary.java    From buck with Apache License 2.0 votes vote down vote up
boolean CloseHandle(WinNT.HANDLE hObject); 
Example 18
Source File: WEvtApi.java    From nifi with Apache License 2.0 votes vote down vote up
boolean EvtClose(WinNT.HANDLE subscriptionHandle); 
Example 19
Source File: WEvtApi.java    From localization_nifi with Apache License 2.0 votes vote down vote up
boolean EvtClose(WinNT.HANDLE subscriptionHandle); 
Example 20
Source File: WEvtApi.java    From localization_nifi with Apache License 2.0 votes vote down vote up
boolean EvtRender(WinNT.HANDLE context, WinNT.HANDLE fragment, int flags, int bufferSize, Pointer buffer, Pointer bufferUsed, Pointer propertyCount);