下面列出了怎么用com.sun.jna.Platform的API类实例代码及写法,或者点击链接到github查看源代码。
public static String getProcessId(Process process) {
long pid = -1;
Field field;
if (Platform.isWindows()) {
try {
field = process.getClass().getDeclaredField("handle");
field.setAccessible(true);
pid = Kernel32.INSTANCE.GetProcessId((Long) field.get(process));
} catch (Exception ex) {
logger.error("get process id for windows error {0}", ex);
}
} else if (Platform.isLinux() || Platform.isAIX()) {
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
field = clazz.getDeclaredField("pid");
field.setAccessible(true);
pid = (Integer) field.get(process);
} catch (Throwable e) {
logger.error("get process id for unix error {0}", e);
}
}
return String.valueOf(pid);
}
public String getCloudPlatform() {
try {
if (!Platform.isLinux()) {
return null;
}
//can generate false positives, but seems to be the simplest and least intrusive solution
//see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html
final File uuidFile = getUuidFile();
if (uuidFile.exists() && uuidFile.canRead()) {
final String content = FileUtils.readFileToString(uuidFile, StandardCharsets.UTF_8);
if (content.startsWith("ec2") || content.startsWith("EC2")) {
return "AWS EC2";
}
}
} catch (final Exception ex) {
log.trace("not able to determine if running on cloud platform", ex);
}
return null;
}
public String getContainerEnvironment() {
try {
if (!Platform.isLinux()) {
return null;
}
//a docker container always has the content "docker" in the cgroup file
//see https://stackoverflow.com/questions/23513045/
final File cgroupFile = getCgroupFile();
if (cgroupFile.exists() && cgroupFile.canRead()) {
final String content = FileUtils.readFileToString(cgroupFile, StandardCharsets.UTF_8);
if (content.contains("docker")) {
return "Docker";
}
}
} catch (final Exception ex) {
log.trace("not able to determine if running in container", ex);
}
return null;
}
@Test
public void test_getCloudPlatform_file_not_present() {
assumeTrue(Platform.isLinux());
final CloudPlatform cloudPlatform = new CloudPlatform() {
@NotNull
@Override
File getUuidFile() {
return new File("/this/file/does/not/exist");
}
};
assertEquals(null, cloudPlatform.getCloudPlatform());
}
/**
* <p>Method is called at every call of {@link #edsdkLibrary()}</p>
*/
protected void initLibrary() {
if (EDSDK == null) {
synchronized (initLibraryLock) {
if (EDSDK == null) {
final String libPath = getLibPath()
.orElseThrow(() -> new IllegalStateException("Could not init library, lib path not found"));
if (Platform.isWindows()) {
// no options for now
EDSDK = Native.loadLibrary(libPath, EdsdkLibrary.class, new HashMap<>());
registerCanonShutdownHook();
log.info("Library successfully loaded");
return;
}
throw new IllegalStateException("Not supported OS: " + Platform.getOSType());
}
}
}
}
@Test
void getLibPath() {
final CanonLibraryImpl canonLibrary = (CanonLibraryImpl) CanonFactory.canonLibrary();
if (Platform.is64Bit()) {
Assertions.assertEquals(DllUtil.DEFAULT_LIB_64_PATH, canonLibrary.getLibPath().get());
}
canonLibrary.setArchLibraryToUse(CanonLibrary.ArchLibrary.FORCE_32);
Assertions.assertEquals(DllUtil.DEFAULT_LIB_32_PATH, canonLibrary.getLibPath().get());
canonLibrary.setArchLibraryToUse(CanonLibrary.ArchLibrary.FORCE_64);
Assertions.assertEquals(DllUtil.DEFAULT_LIB_64_PATH, canonLibrary.getLibPath().get());
System.setProperty("blackdread.cameraframework.library.path", "test");
Assertions.assertEquals("test", canonLibrary.getLibPath().get());
}
/**
* Get global hotkey provider for current platform
*
* @param useSwingEventQueue whether the provider should be using Swing Event queue or a regular thread
* @return new instance of Provider, or null if platform is not supported
* @see X11Provider
* @see WindowsProvider
* @see CarbonProvider
*/
public static com.tulskiy.keymaster.common.Provider getCurrentProvider(boolean useSwingEventQueue) {
com.tulskiy.keymaster.common.Provider provider;
if (Platform.isX11()) {
provider = new X11Provider();
} else if (Platform.isWindows()) {
provider = new WindowsProvider();
} else if (Platform.isMac()) {
provider = new CarbonProvider();
} else {
//LOGGER.warn("No suitable provider for " + System.getProperty("os.name"));
return null;
}
provider.setUseSwingEventQueue(useSwingEventQueue);
provider.init();
return provider;
}
@Before
public void setUp() throws IOException, EvalException {
ProjectWorkspace workspace =
TestDataHelper.createProjectWorkspaceForScenario(this, "run_scripts", tmp);
workspace.setUp();
BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
filesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot());
runner = new TestActionExecutionRunner(filesystem, target);
scriptPath = Platform.isWindows() ? Paths.get("script.bat") : Paths.get("script.sh");
script = runner.declareArtifact(scriptPath);
// Make sure we're testing w/ a BuildArtifact instead of a SourceArtifact
runner.runAction(
new WriteAction(
runner.getRegistry(),
ImmutableSortedSet.of(),
ImmutableSortedSet.of(script.asOutputArtifact()),
filesystem.readFileIfItExists(scriptPath).get(),
true));
}
/**
* Subclasses should override this method to provide a custom binary to run.
*/
@Nullable
public static File getExecutable() {
String execPath = System.getProperty(PROPERTY_WATCHER_EXECUTABLE_PATH);
if (execPath != null) return new File(execPath);
String[] names = null;
if (SystemInfo.isWindows) {
if ("win32-x86".equals(Platform.RESOURCE_PREFIX)) names = new String[]{"fsnotifier.exe"};
else if ("win32-x86-64".equals(Platform.RESOURCE_PREFIX)) names = new String[]{"fsnotifier64.exe", "fsnotifier.exe"};
}
else if (SystemInfo.isMac) {
names = new String[]{"fsnotifier"};
}
else if (SystemInfo.isLinux) {
if ("linux-x86".equals(Platform.RESOURCE_PREFIX)) names = new String[]{"fsnotifier"};
else if ("linux-x86-64".equals(Platform.RESOURCE_PREFIX)) names = new String[]{"fsnotifier64"};
else if ("linux-arm".equals(Platform.RESOURCE_PREFIX)) names = new String[]{"fsnotifier-arm"};
}
if (names == null) return PLATFORM_NOT_SUPPORTED;
return Arrays.stream(names).map(ContainerPathManager.get()::findBinFile).filter(Objects::nonNull).findFirst().orElse(null);
}
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?");
}
public static Process byId(int id) {
if ((Platform.isMac() || Platform.isLinux()) && !isSudo()) {
throw new RuntimeException("You need to run as root/sudo for unix/osx based environments.");
}
if (Platform.isWindows()) {
return new Win32Process(id, Kernel32.OpenProcess(0x438, true, id));
} else if (Platform.isLinux()) {
return new UnixProcess(id);
} else if (Platform.isMac()) {
IntByReference out = new IntByReference();
if (mac.task_for_pid(mac.mach_task_self(), id, out) != 0) {
throw new IllegalStateException("Failed to find mach task port for process, ensure you are running as sudo.");
}
return new MacProcess(id, out.getValue());
}
throw new IllegalStateException("Process " + id + " was not found. Are you sure its running?");
}
@Test
public void requireThatDropFileFromCacheDoesNotThrow() throws IOException {
File testFile = new File("testfile");
FileOutputStream output = new FileOutputStream(testFile);
output.write('t');
output.flush();
output.close();
NativeIO nativeIO = new NativeIO();
if (Platform.isLinux()) {
assertTrue(nativeIO.valid());
} else {
assertFalse(nativeIO.valid());
assertEquals("Platform is unsúpported. Only supported on linux.", nativeIO.getError().getMessage());
}
nativeIO.dropFileFromCache(output.getFD());
nativeIO.dropFileFromCache(testFile);
testFile.delete();
nativeIO.dropFileFromCache(new File("file.that.does.not.exist"));
}
/**
* This method returns the path to the TF command line program.
* It relies on the vsts-settings file.
* This method will throw if no valid path exists.
*/
public static String getValidLocation() {
// Get the tf command location from file
final String location = getLocation();
if (StringUtil.isNullOrEmpty(location)) {
// tfHome property not set
throw new ToolException(ToolException.KEY_TF_HOME_NOT_SET);
}
final String[] filenames = Platform.isWindows() ? TF_WINDOWS_PROGRAMS : TF_OTHER_PROGRAMS;
// Verify the path leads to a tf command and exists
for (final String filename : filenames) {
if (StringUtils.endsWith(location, filename) && (new File(location)).exists()) {
return location;
}
}
// The saved location does not point to the tf command
throw new ToolException(ToolException.KEY_TF_EXE_NOT_FOUND);
}
@Test
public void sha256PluginTestWithoutServerRsaKey() throws SQLException {
Assume.assumeTrue(!Platform.isWindows() && minVersion(8, 0, 0));
try (Connection conn =
DriverManager.getConnection(
"jdbc:mariadb://"
+ ((hostname == null) ? "localhost" : hostname)
+ ":"
+ port
+ "/"
+ ((database == null) ? "" : database)
+ "?user=sha256User&password=password&allowPublicKeyRetrieval")) {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT '5'");
Assert.assertTrue(rs.next());
Assert.assertEquals("5", rs.getString(1));
}
}
public static boolean isAddedToContextMenu() {
if (!Platform.isWindows()) {
return false;
}
final WinReg.HKEY REG_CLASSES_HKEY = WinReg.HKEY_LOCAL_MACHINE;
final String REG_CLASSES_PATH = "Software\\Classes\\";
try {
if (!Advapi32Util.registryKeyExists(REG_CLASSES_HKEY, REG_CLASSES_PATH + ".swf")) {
return false;
}
String clsName = Advapi32Util.registryGetStringValue(REG_CLASSES_HKEY, REG_CLASSES_PATH + ".swf", "");
if (clsName == null) {
return false;
}
return Advapi32Util.registryKeyExists(REG_CLASSES_HKEY, REG_CLASSES_PATH + clsName + "\\shell\\ffdec");
} catch (Win32Exception ex) {
return false;
}
}
/**
* Check if server and client are on same host (not using containers).
*
* @return true if server and client are really on same host
*/
public boolean hasSameHost() {
try {
Statement st = sharedConnection.createStatement();
ResultSet rs = st.executeQuery("select @@version_compile_os");
if (rs.next()) {
if ((rs.getString(1).contains("linux") && Platform.isWindows())
|| (rs.getString(1).contains("win") && Platform.isLinux())) {
return false;
}
}
} catch (SQLException sqle) {
// eat
}
return true;
}
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?");
}
private static String findMobileLibrary() {
if (Platform.isWindows()) {
String path;
try {
path = getMDPath(true);
path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "iTunesMobileDeviceDLL");
} catch (Exception ignored) {
try {
path = getMDPath(false);
path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "iTunesMobileDeviceDLL");
} catch (Exception ignored1) {
log.info(ignored.getMessage());
return "";
}
}
File f = new File(path);
if (f.exists())
return path;
} else {
if (Platform.isMac()) {
return "/System/Library/PrivateFrameworks/MobileDevice.framework/MobileDevice";
}
}
return "";
}
private static String findCoreLibrary() {
String path="";
if (Platform.isWindows()) {
try {
path = getCPath(true);
path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "InstallDir");
} catch (Exception ignored) {
try {
path = getCPath(false);
path = Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE, path, "InstallDir");
} catch (Exception ignored1) {
return "";
}
}
path = path + "CoreFoundation.dll";
File f = new File(path);
if (f.exists())
return path;
} else if (Platform.isMac()) {
return "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
}
return "";
}
@Test
public void canRunBinariesAtWorkingDirRoot() throws CommandLineArgException, IOException {
Path sourceScriptPath = Platform.isWindows() ? Paths.get("script.bat") : Paths.get("script.sh");
Artifact sourceScript = SourceArtifactImpl.of(PathSourcePath.of(filesystem, sourceScriptPath));
ImmutableList<String> expectedStderr =
ImmutableList.of(
"Message on stderr",
"arg[--foo]",
"arg[bar]",
String.format("PWD: %s", filesystem.getRootPath().toString()),
"CUSTOM_ENV:");
RunAction action =
new RunAction(
runner.getRegistry(),
"list",
CommandLineArgsFactory.from(ImmutableList.of(sourceScript, "--foo", "bar")),
ImmutableMap.of());
StepExecutionResult result = runner.runAction(action).getResult();
assertTrue(result.isSuccess());
assertEquals(expectedStderr, getStderr(result));
}
@Test
public void test_getContainerEnvironment_file_not_present() {
assumeTrue(Platform.isLinux());
final ContainerEnvironment containerEnvironment = new ContainerEnvironment() {
@NotNull
@Override
File getCgroupFile() {
return new File("/this/file/does/not/exist");
}
};
assertEquals(null, containerEnvironment.getContainerEnvironment());
}
@Test
public void test_getContainerEnvironment_docker_file_present() throws Exception {
assumeTrue(Platform.isLinux());
final File cgroupFile = new File(temporaryFolder.getRoot(), "cgroup");
final String exampleContent = "11:name=systemd:/\n" +
"9:perf_event:/\n" +
"6:devices:/docker/435454325452353780436aa50e472bb46231663bb99a6bb8927649\n" +
"5:memory:/\n" +
"4:cpuacct:/\n" +
"3:cpu:/docker/234a23a4e23a4e234243e2a4e23a4e23a42ea42e34a2e3a423bb\n" +
"2:cpuset:/";
FileUtils.writeStringToFile(cgroupFile, exampleContent, StandardCharsets.UTF_8);
final ContainerEnvironment containerEnvironment = new ContainerEnvironment() {
@NotNull
@Override
File getCgroupFile() {
return cgroupFile;
}
};
assertEquals("Docker", containerEnvironment.getContainerEnvironment());
}
public static String getHostname() throws IOException {
if (Platform.isWindows()) {
return getHostnameWin32();
} else {
return getHostnamePosix();
}
}
private static String getLibraryResource() {
return "/wkhtmltox/0.12.5/"
+ (Platform.isWindows() ? "" : "lib")
+ "wkhtmltox"
+ (Platform.is64Bit() ? "" : ".32")
+ (Platform.isWindows() ? ".dll"
: Platform.isMac() ? ".dylib"
: ".so");
}
public PipeOutputStream(String pipeName, boolean newPipe) throws IOException {
if (!Platform.isWindows()) {
throw new IOException("Cannot create Pipe on nonWindows OS");
}
String fullPipePath = "\\\\.\\pipe\\" + pipeName;
if (newPipe) {
pipe = Kernel32.INSTANCE.CreateNamedPipe(fullPipePath, Kernel32.PIPE_ACCESS_OUTBOUND, Kernel32.PIPE_TYPE_BYTE, 1, 4096, 4096, 0, null);
if (pipe == null || !Kernel32.INSTANCE.ConnectNamedPipe(pipe, null)) {
throw new IOException("Cannot connect to the pipe. Error " + Kernel32.INSTANCE.GetLastError());
}
} else {
pipe = Kernel32.INSTANCE.CreateFile(fullPipePath, Kernel32.GENERIC_WRITE, Kernel32.FILE_SHARE_WRITE, null, Kernel32.OPEN_EXISTING, Kernel32.FILE_ATTRIBUTE_NORMAL, null);
if (pipe == null) {
throw new IOException("Cannot connect to the pipe. Error " + Kernel32.INSTANCE.GetLastError());
}
}
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
close();
} catch (IOException ex) {
//ignore
}
}
});
}
/**
* @return path to lib to load
*/
protected Optional<String> getLibPath() {
final String jnaPath = System.getProperty(LIBRARY_PATH_PROPERTY);
if (jnaPath != null) {
// user has specified himself the path, we follow what he gave
return Optional.of(jnaPath);
}
switch (archLibraryToUse) {
case AUTO:
// is64Bit() already checks java runtime with "sun.arch.data.model" for 32 or 64
if (Platform.is64Bit()) {
log.info("Dll auto selected to 64 bit");
return Optional.of(DllUtil.DEFAULT_LIB_64_PATH);
}
log.info("Dll auto selected to 32 bit");
return Optional.of(DllUtil.DEFAULT_LIB_32_PATH);
case FORCE_32:
log.info("Dll forced to 32 bit");
return Optional.of(DllUtil.DEFAULT_LIB_32_PATH);
case FORCE_64:
log.info("Dll forced to 64 bit");
return Optional.of(DllUtil.DEFAULT_LIB_64_PATH);
default:
throw new IllegalStateException("Enum unknown: " + archLibraryToUse);
}
}
/**
* {@inheritDoc}
*/
@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
this.restartTimeout = MAX_IDLE_BEFORE_RESTART;
String libraryPath = null;
if (Platform.isWindows()) {
libraryPath = "C:/Program Files/Telldus/;C:/Program Files (x86)/Telldus/";
}
logger.info("Called with config " + config);
if (config != null) {
String maxIdle = (String) config.get("max_idle");
String confLibraryPath = (String) config.get("library_path");
if (maxIdle != null) {
this.restartTimeout = Integer.valueOf(maxIdle);
}
if (confLibraryPath != null) {
libraryPath = confLibraryPath;
}
}
if (libraryPath != null) {
logger.info("Loading " + JNA.library + " from " + libraryPath);
System.setProperty("jna.library.path", libraryPath);
} else {
logger.info("Loading " + JNA.library + " from system default paths");
}
resetTellstick();
setProperlyConfigured(true);
}
private static long getProcessHandle(Process process) {
try {
Field handleField;
if (Platform.isWindows()) {
handleField = process.getClass().getDeclaredField("handle");
} else {
handleField = process.getClass().getDeclaredField("pid");
}
handleField.setAccessible(true);
return handleField.getLong(process);
} catch (Throwable e) {
log.error("getProcessHandle failed", e);
return 0;
}
}
public static String getProcessId(Process process)
{
long pid = -1;
Field field = null;
if (Platform.isWindows()) {
try {
field = process.getClass().getDeclaredField("handle");
field.setAccessible(true);
pid = Kernel32.INSTANCE.getProcessId((Long) field.get(process));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
else if (Platform.isLinux() || Platform.isAIX()) {
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
field = clazz.getDeclaredField("pid");
field.setAccessible(true);
pid = (Integer) field.get(process);
}
catch (Throwable e) {
e.printStackTrace();
}
}
return String.valueOf(pid);
}
public static void updateStageStyle(Stage stage) {
if (Platform.isWindows()) {
Pointer pointer = getWindowPointer(stage);
WinDef.HWND hwnd = new WinDef.HWND(pointer);
final User32 user32 = User32.INSTANCE;
int oldStyle = user32.GetWindowLong(hwnd, WinUser.GWL_STYLE);
int newStyle = oldStyle | 0x00020000; // WS_MINIMIZEBOX
user32.SetWindowLong(hwnd, WinUser.GWL_STYLE, newStyle);
}
}