net.ymate.platform.core.util.RuntimeUtils.java Source code

Java tutorial

Introduction

Here is the source code for net.ymate.platform.core.util.RuntimeUtils.java

Source

/*
 * Copyright 2007-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.ymate.platform.core.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * ????
 *
 * @author  (suninformation@163.com) on 2010-8-2 ?10:10:16
 * @version 1.0
 */
public class RuntimeUtils {

    private static final Log _LOG = LogFactory.getLog(RuntimeUtils.class);

    /**
     * ??
     */
    private static final Map<String, String> SYSTEM_ENV_MAP = new HashMap<String, String>();

    static {
        initSystemEnvs();
    }

    /**
     * ?????
     */
    public static void initSystemEnvs() {
        Process p = null;
        BufferedReader br = null;
        try {
            if (SystemUtils.IS_OS_WINDOWS) {
                p = Runtime.getRuntime().exec("cmd /c set");
            } else if (SystemUtils.IS_OS_UNIX) {
                p = Runtime.getRuntime().exec("/bin/sh -c set");
            } else {
                _LOG.warn("Unknown os.name=" + SystemUtils.OS_NAME);
                SYSTEM_ENV_MAP.clear();
            }
            if (p != null) {
                br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    int i = line.indexOf('=');
                    if (i > -1) {
                        String key = line.substring(0, i);
                        String value = line.substring(i + 1);
                        SYSTEM_ENV_MAP.put(key, value);
                    }
                }
            }
        } catch (IOException e) {
            _LOG.warn(RuntimeUtils.unwrapThrow(e));
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    _LOG.warn("", e);
                }
            }
            if (p != null) {
                p.destroy();
            }
        }
    }

    /**
     * ???
     *
     * @return ??
     */
    public static Map<String, String> getSystemEnvs() {
        if (SYSTEM_ENV_MAP.isEmpty()) {
            initSystemEnvs();
        }
        return SYSTEM_ENV_MAP;
    }

    /**
     * ???
     *
     * @param envName ??null
     * @return ???????
     */
    public static String getSystemEnv(String envName) {
        if (StringUtils.isNotBlank(envName)) {
            if (SYSTEM_ENV_MAP.isEmpty()) {
                initSystemEnvs();
            }
            return SYSTEM_ENV_MAP.get(envName);
        }
        return null;
    }

    /**
     * @return ???Unix
     */
    public static boolean isUnixOrLinux() {
        return SystemUtils.IS_OS_UNIX;
    }

    /**
     * @return ???Windows
     */
    public static boolean isWindows() {
        return SystemUtils.IS_OS_WINDOWS;
    }

    /**
     * @return ?WEB.../WEB-INF/
     */
    public static String getRootPath() {
        return getRootPath(true);
    }

    /**
     * @param safe WEB??WEB-INF
     * @return 
     */
    public static String getRootPath(boolean safe) {
        //
        String _rootPath = null;
        //
        URL _rootURL = RuntimeUtils.class.getClassLoader().getResource("/");
        if (_rootURL == null) {
            _rootURL = RuntimeUtils.class.getClassLoader().getResource("");
            if (_rootURL != null) {
                _rootPath = _rootURL.getPath();
            }
        } else {
            _rootPath = StringUtils.removeEnd(
                    StringUtils.substringBefore(_rootURL.getPath(), safe ? "classes/" : "WEB-INF/"), "/");
        }
        //
        if (_rootPath != null) {
            _rootPath = StringUtils.replace(_rootPath, "%20", " ");
            if (isWindows()) {
                _rootPath = StringUtils.removeStart(_rootPath, "/");
            }
        }
        return StringUtils.trimToEmpty(_rootPath);
    }

    /**
     * @param origin 
     * @return ?${root}?${user.dir}${user.home}??
     */
    public static String replaceEnvVariable(String origin) {
        if ((origin = StringUtils.trimToNull(origin)) != null) {
            String _defaultPath = getRootPath();
            if (StringUtils.startsWith(origin, "${root}")) {
                origin = ExpressionUtils.bind(origin).set("root", _defaultPath).getResult();
            } else if (StringUtils.startsWith(origin, "${user.dir}")) {
                origin = ExpressionUtils.bind(origin).set("user.dir", System.getProperty("user.dir", _defaultPath))
                        .getResult();
            } else if (StringUtils.startsWith(origin, "${user.home}")) {
                origin = ExpressionUtils.bind(origin)
                        .set("user.home", System.getProperty("user.home", _defaultPath)).getResult();
            }
        }
        return origin;
    }

    /**
     * ????
     *
     * @param format ?
     * @param args   ?
     * @return ?
     */
    public static RuntimeException makeRuntimeThrow(String format, Object... args) {
        return new RuntimeException(String.format(format, args));
    }

    /**
     * ????
     *
     * @param e    
     * @param fmt  ?
     * @param args ?
     * @return ?
     */
    public static RuntimeException wrapRuntimeThrow(Throwable e, String fmt, Object... args) {
        return new RuntimeException(String.format(fmt, args), e);
    }

    /**
     * ??
     * <p>
     *  e  InvocationTargetException TargetException 
     * </p>
     *
     * @param e 
     * @return ?
     */
    public static RuntimeException wrapRuntimeThrow(Throwable e) {
        if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        }
        if (e instanceof InvocationTargetException) {
            return wrapRuntimeThrow(((InvocationTargetException) e).getTargetException());
        }
        return new RuntimeException(e);
    }

    public static Throwable unwrapThrow(Throwable e) {
        if (e == null) {
            return null;
        }
        if (e instanceof InvocationTargetException) {
            InvocationTargetException itE = (InvocationTargetException) e;
            if (itE.getTargetException() != null) {
                return unwrapThrow(itE.getTargetException());
            }
        }
        if (e.getCause() != null) {
            return unwrapThrow(e.getCause());
        }
        return e;
    }

    /**
     * 
     *
     * @return ??
     */
    public static long gc() {
        Runtime rt = Runtime.getRuntime();
        long lastUsed = rt.totalMemory() - rt.freeMemory();
        rt.gc();
        return lastUsed - rt.totalMemory() + rt.freeMemory();
    }

}