com.sun.jna.Native Java Examples
The following examples show how to use
com.sun.jna.Native.
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: Test.java From MercuryTrade with MIT License | 6 votes |
public static void main(String[] args) { final User32 user32 = User32.INSTANCE; user32.EnumWindows(new WinUser.WNDENUMPROC() { int count = 0; @Override public boolean callback(WinDef.HWND hwnd, Pointer pointer) { byte[] windowText = new byte[512]; byte[] className = new byte[512]; user32.GetWindowTextA(hwnd, windowText, 512); user32.GetClassNameA(hwnd, className, 512); String title = Native.toString(windowText); String classN = Native.toString(className); // get rid of this if block if you want all windows regardless of whether // or not they have text if (title.isEmpty()) { return true; } System.out.println("Title: " + title + " Class name: " + classN); return true; } },null); }
Example #2
Source File: LayoutFrame.java From java-example with MIT License | 6 votes |
private void setHasFrame(JFrame frame, boolean hasFrame) { if (!this.frameless) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { System.out.println(windowName + " hasFrame=" + hasFrame); WinDef.HWND hWnd = new WinDef.HWND(); hWnd.setPointer(Native.getComponentPointer(frame)); LayoutFrame.this.externalWindowObserver.setHasFrame(hWnd, hasFrame); frame.setResizable(hasFrame); frame.invalidate(); frame.validate(); frame.repaint(); SwingUtilities.updateComponentTreeUI(frame); } }); } }
Example #3
Source File: Restarter.java From consulo with Apache License 2.0 | 6 votes |
private static void restartOnWindows(@Nonnull final String... beforeRestart) throws IOException { Kernel32 kernel32 = Native.loadLibrary("kernel32", Kernel32.class); Shell32 shell32 = Native.loadLibrary("shell32", Shell32.class); final int pid = kernel32.GetCurrentProcessId(); final IntByReference argc = new IntByReference(); Pointer argv_ptr = shell32.CommandLineToArgvW(kernel32.GetCommandLineW(), argc); final String[] argv = argv_ptr.getWideStringArray(0, argc.getValue()); kernel32.LocalFree(argv_ptr); doScheduleRestart(new File(ContainerPathManager.get().getBinPath(), "restarter.exe"), ContainerPathManager.get().getAppHomeDirectory(), commands -> { Collections.addAll(commands, String.valueOf(pid), String.valueOf(beforeRestart.length)); Collections.addAll(commands, beforeRestart); Collections.addAll(commands, String.valueOf(argc.getValue())); Collections.addAll(commands, argv); }); // Since the process ID is passed through the command line, we want to make sure that we don't exit before the "restarter" // process has a chance to open the handle to our process, and that it doesn't wait for the termination of an unrelated // process which happened to have the same process ID. TimeoutUtil.sleep(500); }
Example #4
Source File: JOpenVRLibrary.java From jmonkeyengine with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Init the native binding to the underlying system library. */ public static void init() throws UnsatisfiedLinkError { Native.unregister(JOpenVRLibrary.class); String path = System.getProperty(JNA_OPENVR_LIBRARY_PATH); if (path != null){ JNA_LIBRARY_NAME = path; logger.config("Using OpenVR implementation located at "+JNA_LIBRARY_NAME); JNA_NATIVE_LIB = NativeLibrary.getInstance(JOpenVRLibrary.JNA_LIBRARY_NAME); Native.register(JOpenVRLibrary.class, JOpenVRLibrary.JNA_NATIVE_LIB); } else { JNA_LIBRARY_NAME = "openvr_api"; logger.config("Using embedded OpenVR implementation "+JOpenVRLibrary.JNA_LIBRARY_NAME); JNA_NATIVE_LIB = NativeLibrary.getInstance(JOpenVRLibrary.JNA_LIBRARY_NAME); Native.register(JOpenVRLibrary.class, JOpenVRLibrary.JNA_NATIVE_LIB); } }
Example #5
Source File: FileLogicDefault.java From canon-sdk-java with MIT License | 6 votes |
protected File getDestinationOfDownloadFile(final EdsDirectoryItemInfo dirItemInfo, @Nullable final File folderDestination, @Nullable final String filename) { final String itemFilename = Native.toString(dirItemInfo.szFileName, DEFAULT_CHARSET.name()); final String itemFileExtension = Files.getFileExtension(itemFilename); final File saveFolder = folderDestination == null ? SYSTEM_TEMP_DIR : folderDestination; final String saveFilename; if (StringUtils.isBlank(filename)) { saveFilename = itemFilename; } else { final String fileExtension = Files.getFileExtension(filename); if (StringUtils.isBlank(fileExtension)) { saveFilename = filename + "." + itemFileExtension; } else { if (fileExtension.equalsIgnoreCase(itemFileExtension)) { saveFilename = filename; } else { saveFilename = filename + "." + itemFileExtension; } } } saveFolder.mkdirs(); return new File(saveFolder, saveFilename); }
Example #6
Source File: NativeCallsJNAImpl.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
@Override public void lockCurrentMemory() { if (mlockall(MCL_CURRENT) == 0) { return; } final int errno = Native.getLastError(); final String msg, reason; if (errno == EPERM) { reason = "insufficient privileges"; } else if (errno == ENOMEM) { reason = "insufficient free space"; } else { reason = "errno=" + errno; } msg = "Unable to lock memory due to " + reason + ". Please check the RLIMIT_MEMLOCK soft resource limit " + "(ulimit -l) and increase the available memory if needed."; throw new IllegalStateException(msg); }
Example #7
Source File: Advapi32Util.java From jpexs-decompiler with GNU General Public License v3.0 | 6 votes |
public EventLogRecord(Pointer pevlr) { _record = new EVENTLOGRECORD(pevlr); _source = pevlr.getString(_record.size(), true); // data if (_record.DataLength.intValue() > 0) { _data = pevlr.getByteArray(_record.DataOffset.intValue(), _record.DataLength.intValue()); } // strings if (_record.NumStrings.intValue() > 0) { ArrayList<String> strings = new ArrayList<>(); int count = _record.NumStrings.intValue(); long offset = _record.StringOffset.intValue(); while (count > 0) { String s = pevlr.getString(offset, true); strings.add(s); offset += s.length() * Native.WCHAR_SIZE; offset += Native.WCHAR_SIZE; count--; } _strings = strings.toArray(new String[strings.size()]); } }
Example #8
Source File: NativeServices.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 6 votes |
protected ProcessEnvironment createProcessEnvironment(OperatingSystem operatingSystem) { if (useNativePlatform) { try { io.rubygrapefruit.platform.Process process = io.rubygrapefruit.platform.Native.get(Process.class); return new NativePlatformBackedProcessEnvironment(process); } catch (NativeIntegrationUnavailableException ex) { LOGGER.debug("Native-platform process integration is not available. Continuing with fallback."); } } try { if (operatingSystem.isUnix()) { return new LibCBackedProcessEnvironment(get(LibC.class)); } else { return new UnsupportedEnvironment(); } } catch (LinkageError e) { // Thrown when jna cannot initialize the native stuff LOGGER.debug("Unable to load native library. Continuing with fallback. Failure: {}", format(e)); return new UnsupportedEnvironment(); } }
Example #9
Source File: AbstractSocket.java From jnanomsg with Apache License 2.0 | 6 votes |
/** * Get file descriptor. * * @return file descriptor. */ private synchronized int getSocketFd(SocketOption opt) throws IOException { final int flag = opt.value(); final IntByReference fd = new IntByReference(); final IntByReference size_t = new IntByReference(Native.SIZE_T_SIZE); final int rc = NativeLibrary.nn_getsockopt(this.fd, OptionLevel.NN_SOL_SOCKET.value(), flag, fd.getPointer(), size_t.getPointer()); if (rc < 0) { Nanomsg.handleError(rc); } return fd.getValue(); }
Example #10
Source File: LevelDBKeyIterator.java From leveldb-jna with MIT License | 6 votes |
public byte[] next() { levelDB.checkDatabaseOpen(); checkIteratorOpen(); PointerByReference resultLengthPointer = new PointerByReference(); PointerByReference resultPointer = LevelDBNative.leveldb_iter_key(iterator, resultLengthPointer); long resultLength; if (Native.POINTER_SIZE == 8) { resultLength = resultLengthPointer.getPointer().getLong(0); } else { resultLength = resultLengthPointer.getPointer().getInt(0); } byte[] key = resultPointer.getPointer().getByteArray(0, (int) resultLength); LevelDBNative.leveldb_iter_next(iterator); return key; }
Example #11
Source File: WinUtil.java From runelite with BSD 2-Clause "Simplified" License | 6 votes |
/** * Forcibly set focus to the given component * */ public static void requestForeground(Frame frame) { // SetForegroundWindow can't set iconified windows to foreground, so set the // frame state to normal first frame.setState(Frame.NORMAL); User32 user32 = User32.INSTANCE; // Windows does not allow any process to set the foreground window, but it will if // the process received the last input event. So we send a F22 key event to the process. // https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setforegroundwindow WinUser.INPUT input = new WinUser.INPUT(); input.type = new WinDef.DWORD(WinUser.INPUT.INPUT_KEYBOARD); input.input.ki.wVk = new WinDef.WORD(0x85); // VK_F22 user32.SendInput(new WinDef.DWORD(1), (WinUser.INPUT[]) input.toArray(1), input.size()); // Now we may set the foreground window WinDef.HWND hwnd = new WinDef.HWND(Native.getComponentPointer(frame)); user32.SetForegroundWindow(hwnd); }
Example #12
Source File: Processes.java From Java-Memory-Manipulation with Apache License 2.0 | 6 votes |
public static Process byName(String name) { if (Platform.isWindows()) { Tlhelp32.PROCESSENTRY32.ByReference entry = new Tlhelp32.PROCESSENTRY32.ByReference(); Pointer snapshot = Kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPALL.intValue(), 0); try { while (Kernel32.Process32NextW(snapshot, entry)) { String processName = Native.toString(entry.szExeFile); if (name.equals(processName)) { return byId(entry.th32ProcessID.intValue()); } } } finally { Kernel32.CloseHandle(snapshot); } } else if (Platform.isMac() || Platform.isLinux()) { return byId(Utils.exec("bash", "-c", "ps -A | grep -m1 \"" + name + "\" | awk '{print $1}'")); } else { throw new UnsupportedOperationException("Unknown operating system! (" + System.getProperty("os.name") + ")"); } throw new IllegalStateException("Process '" + name + "' was not found. Are you sure its running?"); }
Example #13
Source File: HostnameFetching.java From buck with Apache License 2.0 | 5 votes |
private static String getHostnamePosix() throws IOException { byte[] hostnameBuf = new byte[HOSTNAME_MAX_LEN]; try { // Subtract 1 to ensure NUL termination. HostnameFetchingPosixLibrary.gethostname(hostnameBuf, hostnameBuf.length - 1); return Native.toString(hostnameBuf); } catch (LastErrorException e) { throw new IOException(e); } }
Example #14
Source File: NativeServices.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
protected SystemInfo createSystemInfo() { if (useNativePlatform) { try { return io.rubygrapefruit.platform.Native.get(SystemInfo.class); } catch (NativeIntegrationUnavailableException e) { LOGGER.debug("Native-platform system info is not available. Continuing with fallback."); } } return notAvailable(SystemInfo.class); }
Example #15
Source File: LMBCSStringArray.java From domino-jna with Apache License 2.0 | 5 votes |
public LMBCSStringArray(Object[] strValues) { super((strValues.length + 1) * Native.POINTER_SIZE); this.original = strValues; for (int i=0; i < strValues.length;i++) { Pointer p = null; if (strValues[i] != null) { Memory currStrMem = NotesStringUtils.toLMBCS(strValues[i].toString(), true); natives.add(currStrMem); p = currStrMem; } setPointer(Native.POINTER_SIZE * i, p); } setPointer(Native.POINTER_SIZE * strValues.length, null); }
Example #16
Source File: UnixSyslog.java From syslog4j-graylog2 with GNU Lesser General Public License v2.1 | 5 votes |
protected static synchronized void loadLibrary(UnixSyslogConfig config) throws SyslogRuntimeException { if (!OSDetectUtility.isUnix()) { throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms"); } if (libraryInstance == null) { libraryInstance = (CLibrary) Native.loadLibrary(config.getLibrary(), CLibrary.class); } }
Example #17
Source File: SecureStorageAppleManager.java From snowflake-jdbc with Apache License 2.0 | 5 votes |
public static SecurityLib getInstance() { if (INSTANCE == null) { synchronized (SecurityLibManager.class) { if (INSTANCE == null) { INSTANCE = (SecurityLib) Native.loadLibrary("Security", SecurityLib.class); } } } return INSTANCE; }
Example #18
Source File: JNABenchmark.java From indexr with Apache License 2.0 | 5 votes |
@Benchmark public void memory_malloc_jna2() { long native_p = Native.malloc(100); ByteSlice buffer = ByteSlice.wrap(MemoryUtil.getByteBuffer(native_p, 100, true)); for (int i = 0; i < 100; i++) { buffer.put(i, (byte) i); } Pointer.createConstant(native_p); //Native.free(native_p); }
Example #19
Source File: UnixDomainSocket.java From mariadb-connector-j with GNU Lesser General Public License v2.1 | 5 votes |
public void connect(SocketAddress endpoint, int timeout) throws IOException { try { int ret = connect(fd, sockaddr, sockaddr.size()); if (ret != 0) { throw new IOException(strerror(Native.getLastError())); } connected = true; } catch (LastErrorException lee) { throw new IOException("native connect() failed : " + formatError(lee)); } is = new UnixSocketInputStream(); os = new UnixSocketOutputStream(); }
Example #20
Source File: HostnameFetching.java From buck with Apache License 2.0 | 5 votes |
private static String getHostnameWin32() throws IOException { char[] hostnameBuf = new char[HOSTNAME_MAX_LEN]; IntByReference hostnameBufLen = new IntByReference(hostnameBuf.length); boolean result = HostnameFetchingWin32Library.INSTANCE.GetComputerNameEx( HostnameFetchingWin32Library.COMPUTER_NAME_FORMAT__ComputerNameDnsFullyQualified, hostnameBuf, hostnameBufLen); if (!result) { throw new IOException( String.format("Call to GetComputerNameEx failed with code %d", Native.getLastError())); } return new String(hostnameBuf, 0, hostnameBufLen.getValue()); }
Example #21
Source File: JnaBuilderTest.java From alpha-serac with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) { // get lib folder from resource URL url = JnaBuilderTest.class.getClassLoader().getResource("lib"); if (Objects.isNull(url)) { return; } File file = new File(url.getFile()); // set jna.library.path to the path of lib System.setProperty("jna.library.path", file.getAbsolutePath()); // load example.so from lib ExampleJNA example = Native.load("example", ExampleJNA.class); // call sum method from example library int a = 2; int b = 3; int result = example.sum(a, b); log.info(a + " + " + b + " = " + result); // example using arrays int size = 5; // input 2 integer arrays int[] listA = new int[]{1, 2, 3, 4, 5}; int[] listB = new int[]{5, 4, 3, 2, 1}; // output the sum of the arrays int[] listC = new int[size]; example.sumArray(listA, listB, listC, size); log.info("A = " + Arrays.toString(listA)); log.info("B = " + Arrays.toString(listB)); log.info("A + B = " + Arrays.toString(listC)); }
Example #22
Source File: JNANatives.java From Elasticsearch with Apache License 2.0 | 5 votes |
static void tryVirtualLock() { JNAKernel32Library kernel = JNAKernel32Library.getInstance(); Pointer process = null; try { process = kernel.GetCurrentProcess(); // By default, Windows limits the number of pages that can be locked. // Thus, we need to first increase the working set size of the JVM by // the amount of memory we wish to lock, plus a small overhead (1MB). SizeT size = new SizeT(JvmInfo.jvmInfo().getMem().getHeapInit().getBytes() + (1024 * 1024)); if (!kernel.SetProcessWorkingSetSize(process, size, size)) { logger.warn("Unable to lock JVM memory. Failed to set working set size. Error code " + Native.getLastError()); } else { JNAKernel32Library.MemoryBasicInformation memInfo = new JNAKernel32Library.MemoryBasicInformation(); long address = 0; while (kernel.VirtualQueryEx(process, new Pointer(address), memInfo, memInfo.size()) != 0) { boolean lockable = memInfo.State.longValue() == JNAKernel32Library.MEM_COMMIT && (memInfo.Protect.longValue() & JNAKernel32Library.PAGE_NOACCESS) != JNAKernel32Library.PAGE_NOACCESS && (memInfo.Protect.longValue() & JNAKernel32Library.PAGE_GUARD) != JNAKernel32Library.PAGE_GUARD; if (lockable) { kernel.VirtualLock(memInfo.BaseAddress, new SizeT(memInfo.RegionSize.longValue())); } // Move to the next region address += memInfo.RegionSize.longValue(); } LOCAL_MLOCKALL = true; } } catch (UnsatisfiedLinkError e) { // this will have already been logged by Kernel32Library, no need to repeat it } finally { if (process != null) { kernel.CloseHandle(process); } } }
Example #23
Source File: ProcessInfoManager.java From minsx-framework with Apache License 2.0 | 5 votes |
public static Integer getProcessId(Process process) { Integer processId = null; try { Field field = process.getClass().getDeclaredField("handle"); field.setAccessible(true); long fieldId = (Long) field.get(process); ProcessPIDGetter pidGetter = Native.loadLibrary("kernel32", ProcessPIDGetter.class); processId = (int) pidGetter.GetProcessId(fieldId); } catch (NoSuchFieldException | IllegalAccessException e) { throw new GetProcessInfoException("", e); } return processId; }
Example #24
Source File: Win32Protect.java From netbeans with Apache License 2.0 | 5 votes |
public @Override char[] decrypt(byte[] ciphertext) throws Exception { CryptIntegerBlob input = new CryptIntegerBlob(); input.store(ciphertext); CryptIntegerBlob output = new CryptIntegerBlob(); if (!CryptLib.INSTANCE.CryptUnprotectData(input, null, null, null, null, 0, output)) { throw new Exception("CryptUnprotectData failed: " + Native.getLastError()); } byte[] result = output.load(); // XXX gives CCE because not a Memory: output.zero(); char[] cleartext = Utils.bytes2Chars(result); Arrays.fill(result, (byte) 0); return cleartext; }
Example #25
Source File: UnixSocketSyslog.java From syslog4j-graylog2 with GNU Lesser General Public License v2.1 | 5 votes |
protected synchronized void loadLibrary() { if (!OSDetectUtility.isUnix()) { throw new SyslogRuntimeException("UnixSyslog not supported on non-Unix platforms"); } if (!this.libraryLoaded) { this.libraryInstance = (CLibrary) Native.loadLibrary(this.unixSocketSyslogConfig.getLibrary(), CLibrary.class); this.libraryLoaded = true; } }
Example #26
Source File: Advapi32Util.java From jpexs-decompiler with GNU General Public License v3.0 | 5 votes |
/** * Get a registry REG_MULTI_SZ value. * * @param root Root key. * @param key Registry path. * @param value Name of the value to retrieve. * @return String value. */ public static String[] registryGetStringArray(HKEY root, String key, String value) { HKEYByReference phkKey = new HKEYByReference(); int rc = Advapi32.INSTANCE.RegOpenKeyEx(root, key, 0, WinNT.KEY_READ | WinNT.KEY_WOW64_32KEY, phkKey); if (rc != W32Errors.ERROR_SUCCESS) { throw new Win32Exception(rc); } try { IntByReference lpcbData = new IntByReference(); IntByReference lpType = new IntByReference(); rc = Advapi32.INSTANCE.RegQueryValueEx( phkKey.getValue(), value, 0, lpType, (char[]) null, lpcbData); if (rc != W32Errors.ERROR_SUCCESS && rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(rc); } if (lpType.getValue() != WinNT.REG_MULTI_SZ) { throw new RuntimeException("Unexpected registry type " + lpType.getValue() + ", expected REG_SZ"); } Memory data = new Memory(lpcbData.getValue()); rc = Advapi32.INSTANCE.RegQueryValueEx( phkKey.getValue(), value, 0, lpType, data, lpcbData); if (rc != W32Errors.ERROR_SUCCESS && rc != W32Errors.ERROR_INSUFFICIENT_BUFFER) { throw new Win32Exception(rc); } ArrayList<String> result = new ArrayList<>(); int offset = 0; while (offset < data.size()) { String s = data.getString(offset, true); offset += s.length() * Native.WCHAR_SIZE; offset += Native.WCHAR_SIZE; result.add(s); } return result.toArray(new String[result.size()]); } finally { rc = Advapi32.INSTANCE.RegCloseKey(phkKey.getValue()); if (rc != W32Errors.ERROR_SUCCESS) { throw new Win32Exception(rc); } } }
Example #27
Source File: BaseArgon2.java From argon2-jvm with GNU Lesser General Public License v3.0 | 5 votes |
private boolean verifyBytes(String hash, byte[] pwd) { // encoded needs to be nul terminated for strlen to work byte[] encoded = Native.toByteArray(hash, ASCII); int result = callLibraryVerify(encoded, pwd); return result == Argon2Library.ARGON2_OK; }
Example #28
Source File: LibraryFinder.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public static synchronized CFLibrary getCFLibrary() { if (CF_INSTANCE != null) return CF_INSTANCE; if (foundCoreLibrary()) return ((CFLibrary)Native.loadLibrary(CFLibrary.class)); log.info("Could not find the CoreFoundation Library!"); return null; }
Example #29
Source File: HostnameUtilsUnix.java From netbeans with Apache License 2.0 | 5 votes |
/** * Returns the result of {@code gethostname()} function * from the standard Unix/Linux C Library. * * @return host name * @throws NativeException if there was an error executing the * system call. */ public static String cLibGetHostname() throws NativeException { byte[] buf = new byte[MAXHOSTNAMELEN]; int retCode = CLib.INSTANCE.gethostname(buf, buf.length); if (retCode == 0) { return Native.toString(buf); } throw new NativeException(retCode, "error calling 'gethostname()' function"); }
Example #30
Source File: ADS1115.java From SB_Elsinore_Server with MIT License | 5 votes |
public boolean i2cInit() { String devpath = String.format(I2CDevice.BASE_PATH, device_number); fd = libC.open(devpath, O_RDWR); if (fd < 0) { BrewServer.LOG.warning(String.format("Failed to read from %s. Error %s", devpath, Native.getLastError())); return false; } else { BrewServer.LOG.warning(String.format("Opened fd %s", fd)); } int iovalue = libC.ioctl(fd, I2CDevice.I2C_SLAVE, address); if (iovalue < 0) { BrewServer.LOG.warning(String.format("Failed to open slave device at address %s, wrote %s", address, iovalue)); BrewServer.LOG.warning(String.format("Error %s", Native.getLastError())); return false; } else { BrewServer.LOG.warning(String.format("I2C Slave %s opened %s", address, iovalue)); } return true; }