zoukankan      html  css  js  c++  java
  • netty检测系统工具PlatformDependent

    1. 检测jdk版本

     @SuppressWarnings("LoopStatementThatDoesntLoop")
        private static int javaVersion0() {
            int javaVersion;
    
            // Not really a loop
            for (;;) {
                // Android
                if (isAndroid()) {
                    javaVersion = 6;
                    break;
                }
    
                try {
                    Class.forName("java.time.Clock", false, getClassLoader(Object.class));
                    javaVersion = 8;
                    break;
                } catch (Exception e) {
                    // Ignore
                }
    
                try {
                    Class.forName("java.util.concurrent.LinkedTransferQueue", false, getClassLoader(BlockingQueue.class));
                    javaVersion = 7;
                    break;
                } catch (Exception e) {
                    // Ignore
                }
    
                javaVersion = 6;
                break;
            }
    
            if (logger.isDebugEnabled()) {
                logger.debug("Java version: {}", javaVersion);
            }
            return javaVersion;
        }

    2. 检测是否window

        private static boolean isWindows0() {
            boolean windows = SystemPropertyUtil.get("os.name", "").toLowerCase(Locale.US).contains("win");
            if (windows) {
                logger.debug("Platform: Windows");
            }
            return windows;
        }

    3. 检测是否root权限

    private static boolean isRoot0() {
            if (isWindows()) {
                return false;
            }
    
            String[] ID_COMMANDS = { "/usr/bin/id", "/bin/id", "/usr/xpg4/bin/id", "id"};
            Pattern UID_PATTERN = Pattern.compile("^(?:0|[1-9][0-9]*)$");
            for (String idCmd: ID_COMMANDS) {
                Process p = null;
                BufferedReader in = null;
                String uid = null;
                try {
                    p = Runtime.getRuntime().exec(new String[] { idCmd, "-u" });
                    in = new BufferedReader(new InputStreamReader(p.getInputStream(), CharsetUtil.US_ASCII));
                    uid = in.readLine();
                    in.close();
    
                    for (;;) {
                        try {
                            int exitCode = p.waitFor();
                            if (exitCode != 0) {
                                uid = null;
                            }
                            break;
                        } catch (InterruptedException e) {
                            // Ignore
                        }
                    }
                } catch (Exception e) {
                    // Failed to run the command.
                    uid = null;
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            // Ignore
                        }
                    }
                    if (p != null) {
                        try {
                            p.destroy();
                        } catch (Exception e) {
                            // Android sometimes triggers an ErrnoException.
                        }
                    }
                }
    
                if (uid != null && UID_PATTERN.matcher(uid).matches()) {
                    logger.debug("UID: {}", uid);
                    return "0".equals(uid);
                }
            }
    
            logger.debug("Could not determine the current UID using /usr/bin/id; attempting to bind at privileged ports.");
    
            Pattern PERMISSION_DENIED = Pattern.compile(".*(?:denied|not.*permitted).*");
            for (int i = 1023; i > 0; i --) {
                ServerSocket ss = null;
                try {
                    ss = new ServerSocket();
                    ss.setReuseAddress(true);
                    ss.bind(new InetSocketAddress(i));
                    if (logger.isDebugEnabled()) {
                        logger.debug("UID: 0 (succeded to bind at port {})", i);
                    }
                    return true;
                } catch (Exception e) {
                    // Failed to bind.
                    // Check the error message so that we don't always need to bind 1023 times.
                    String message = e.getMessage();
                    if (message == null) {
                        message = "";
                    }
                    message = message.toLowerCase();
                    if (PERMISSION_DENIED.matcher(message).matches()) {
                        break;
                    }
                } finally {
                    if (ss != null) {
                        try {
                            ss.close();
                        } catch (Exception e) {
                            // Ignore.
                        }
                    }
                }
            }
    
            logger.debug("UID: non-root (failed to bind at any privileged ports)");
            return false;
        }

    4.检测最大直接内存

    private static long maxDirectMemory0() {
            long maxDirectMemory = 0;
            try {
                // Try to get from sun.misc.VM.maxDirectMemory() which should be most accurate.
                Class<?> vmClass = Class.forName("sun.misc.VM", true, getSystemClassLoader());
                Method m = vmClass.getDeclaredMethod("maxDirectMemory");
                maxDirectMemory = ((Number) m.invoke(null)).longValue();
            } catch (Throwable t) {
                // Ignore
            }
    
            if (maxDirectMemory > 0) {
                return maxDirectMemory;
            }
    
            try {
                // Now try to get the JVM option (-XX:MaxDirectMemorySize) and parse it.
                // Note that we are using reflection because Android doesn't have these classes.
                Class<?> mgmtFactoryClass = Class.forName(
                        "java.lang.management.ManagementFactory", true, getSystemClassLoader());
                Class<?> runtimeClass = Class.forName(
                        "java.lang.management.RuntimeMXBean", true, getSystemClassLoader());
    
                Object runtime = mgmtFactoryClass.getDeclaredMethod("getRuntimeMXBean").invoke(null);
    
                @SuppressWarnings("unchecked")
                List<String> vmArgs = (List<String>) runtimeClass.getDeclaredMethod("getInputArguments").invoke(runtime);
                for (int i = vmArgs.size() - 1; i >= 0; i --) {
                    Matcher m = MAX_DIRECT_MEMORY_SIZE_ARG_PATTERN.matcher(vmArgs.get(i));
                    if (!m.matches()) {
                        continue;
                    }
    
                    maxDirectMemory = Long.parseLong(m.group(1));
                    switch (m.group(2).charAt(0)) {
                        case 'k': case 'K':
                            maxDirectMemory *= 1024;
                            break;
                        case 'm': case 'M':
                            maxDirectMemory *= 1024 * 1024;
                            break;
                        case 'g': case 'G':
                            maxDirectMemory *= 1024 * 1024 * 1024;
                            break;
                    }
                    break;
                }
            } catch (Throwable t) {
                // Ignore
            }
    
            if (maxDirectMemory <= 0) {
                maxDirectMemory = Runtime.getRuntime().maxMemory();
                logger.debug("maxDirectMemory: {} bytes (maybe)", maxDirectMemory);
            } else {
                logger.debug("maxDirectMemory: {} bytes", maxDirectMemory);
            }
    
            return maxDirectMemory;
        }

    等等

  • 相关阅读:
    列表的创建02
    python如何设置注释模板,文件模板
    python语言使用rsa密码算法对数据加密时不能对中文加密问题的解决
    python编码解码,字符数据转换问题(自学笔记)
    字符串与数组之间的互相转换
    vc++文本编辑
    OCP 062【中文】考试题库(cuug内部资料)第28题
    OCP 062【中文】考试题库(cuug内部资料)第27题
    OCP 062【中文】考试题库(cuug内部资料)第26题
    OCP 062【中文】考试题库(cuug内部资料)第25题
  • 原文地址:https://www.cnblogs.com/davidwang456/p/5121956.html
Copyright © 2011-2022 走看看