java代碼獲取項目版本號實例

package com.hzcominfo.application.etl.settings.web.controller.highconfig;

import com.hzcominfo.application.common.base.cmpt.web.controller.index.BaseController;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

@Controller
@RequestMapping("/mavenTest/")
public class MavenTest extends BaseController {

    /**
     * 是不是windows系統
     *
     * @return
     */
    private static boolean isWindows() {
        String osName = System.getProperty("os.name");
        if (osName != null && osName.toLowerCase().indexOf("win") >= 0) {
            return true;
        }
        return false;
    }

    /**
     * 查看jar包中maven版本號
     *
     * @return
     * @throws IOException
     * @throws XmlPullParserException
     */
    @ResponseBody
    @RequestMapping("test")
    public String getJarPath() throws IOException, XmlPullParserException {
        //查看jar包裏面pom.properties版本號
        String jarPath = MavenTest.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        jarPath = java.net.URLDecoder.decode(jarPath, "UTF-8");
        try {
            URL url = new URL("jar:file:" + jarPath + "!/META-INF/maven/com.hzcominfo.application.etl-settings/application-etl-settings/pom.properties");
            InputStream inputStream = url.openStream();
            Properties properties = new Properties();
            properties.load(inputStream);
            String version = properties.getProperty("version");
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            //開發過程當中查看pom.xml版本號
            MavenXpp3Reader reader = new MavenXpp3Reader();
            String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
            if (isWindows() && basePath.startsWith("/")) {
                basePath = basePath.substring(1);
            }
            if (basePath.indexOf("/target/") != -1) {
                basePath = basePath.substring(0, basePath.indexOf("/target/"));
            }
            Model model = reader.read(new FileReader(new File(basePath + "\\pom.xml")));
            String version = model.getVersion();
            return version;
        }
    }
}

 

package com.hzcominfo.application.common.base.cmpt.web.controller.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.hzcominfo.application.common.base.cmpt.web.controller.index.BaseController;
import com.hzcominfo.application.common.util.DatetimeUtil;
import com.hzcominfo.application.common.util.StringUtil;

/**
 * 獲取項目maven版本號
 *
 * @Author:linzp
 */
@Controller
@RequestMapping("/mavenVersion/")
public class MavenVersion extends BaseController {

    @Value("${other.info:Copyright info}")
    private String otherInfo;
    
    /**
     * 查看jar包中maven版本號
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getVersion")
    public JSONObject getJarPath(String groupId, String artifactId,String jarName, String fileName) {
        JSONObject jSONObject = new JSONObject();
        Map<String, Object> versionInfo = new HashMap<String, Object>();
        //查看jar包裏面pom.properties版本號
        try {
//            String jarPath = MavenVersion.class.getProtectionDomain().getCodeSource().getLocation().getFile();
            String pomVersion = "";
            try{
                String jarPath = System.getProperty("user.dir") + File.separator + jarName;
                jarPath = java.net.URLDecoder.decode(jarPath, "UTF-8");
                logger.info("version info : " + jarPath);
                URL url = new URL("jar:file:" + jarPath + "!/META-INF/maven/" + groupId + "/" + artifactId + "/pom.properties");
                Properties properties = new Properties();
                properties.load(url.openStream());
                pomVersion = properties.getProperty("version");
            }catch(Exception e){
                logger.error("read jar or pom error:",e);
            }
            String version = "";
            if(StringUtil.isEmpty(fileName))fileName="version.txt";
//            if(StringUtil.isNotEmpty(fileName)){
                File otherInfoFile = new File(System.getProperty("user.dir") + File.separator + fileName);
                Long filelength = otherInfoFile.length();  
                byte[] filecontent = new byte[filelength.intValue()];  
                try {  
                    FileInputStream in = new FileInputStream(otherInfoFile);  
                    in.read(filecontent);  
                    in.close();  
                    version += new String(filecontent, "utf-8");
                } catch (FileNotFoundException e) {  
                    logger.error("version file not found :" , e);  
                } catch (IOException e) {  
                    logger.error("version file read error :" , e);  
                } 
//            }
            versionInfo.put("versionInfo", version);
            versionInfo.put("pomVersion", pomVersion);
            versionInfo.put("jvmName", System.getProperty("java.vm.name"));
            versionInfo.put("jvmVendor", System.getProperty("java.vm.vendor"));
            versionInfo.put("javaVersion", System.getProperty("java.version"));
            versionInfo.put("otherInfo", otherInfo);
            versionInfo.put("serviceTime", DatetimeUtil.getDate());
            jSONObject.put("result", "0");
            jSONObject.put("versionInfo", versionInfo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            jSONObject.put("result", "1");
        }
        return jSONObject;
    }
    public static void aaa(){
//        System.out.println(MavenVersion.class.getProtectionDomain().getCodeSource().getLocation().getFile());
//        System.out.println(System.getProperty("java.vm.name"));
        System.out.println(DatetimeUtil.getDate());
    }
    public static void main(String[] args) {
//        System.out.println(MavenVersion.class.getProtectionDomain().getCodeSource().getLocation().getFile());
        MavenVersion.aaa();
    }
}
versionDataFlag = true;
    
    function getVersionInfo(){
    if(versionDataFlag){
        versionDataFlag = false;
        //獲取版本號
        $.ajax({
            type: "post",
            datatype: "json",
            async: true,
            url: rootPath + "/mavenVersion/getVersion",
            data: {
                groupId: "com.hzcominfo.application.etl-settings",
                artifactId: "application-etl-settings",
                jarName: "etl.jar",
                fileName: "version.txt"
            },
            success: function (data) {
                 versionDataFlag = true;
                 var resultObject = JSON.parse(data);
                if (resultObject.result == "0") {
                    $("#versionInfo").text(resultObject.versionInfo.versionInfo);
                    $("#jvmName").text(resultObject.versionInfo.jvmName);
                    $("#jvmVendor").text(resultObject.versionInfo.jvmVendor);
                    $("#javaVersion").text(resultObject.versionInfo.javaVersion);
                    $("#serviceTime").text(resultObject.versionInfo.serviceTime);
                    //$("#projectVersionA").show();
                } else {
                    //$("#projectVersionA").remove();
                    $("#versionInfo").text("");
                    $("#jvmName").text("");
                    $("#jvmVendor").text("");
                    $("#javaVersion").text("");
                    $("#serviceTime").text("");
                } 
                 pageii = layer.open({
                  type: 1,
                  title: '關於',
                  shadeClose: true,
                  shade: 0.8,
                  area: ['400px', '250px'],
                  content: $("#aboutVersion").html() 
                  });
            },
            error: function(data){
                versionDataFlag = true;
                $("#versionInfo").text("");
                $("#jvmName").text("");
                $("#jvmVendor").text("");
                $("#javaVersion").text("");
                $("#serviceTime").text("");
                pageii = layer.open({
                  type: 1,
                  title: '關於',
                  shadeClose: true,
                  shade: 0.8,
                  area: ['400px', '250px'],
                  content: $("#aboutVersion").html() 
                  });
            }
        });
       }
    }
    function closeAbout(){
        layer.close(pageii);
    }
相關文章
相關標籤/搜索