ads = ni.getInetAddresses();
77 | while (ads.hasMoreElements()) {
78 | InetAddress ip = ads.nextElement();
79 | if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
80 | return ip.getHostAddress();
81 | }
82 | }
83 | }
84 | }
85 | catch (Exception e) {
86 | }
87 | return address;
88 | }
89 |
90 | }
91 |
--------------------------------------------------------------------------------
/diamond-server/src/main/resources/jdbc.properties:
--------------------------------------------------------------------------------
1 | db.url=jdbc:mysql://localhost:3306/diamond?characterEncoding=utf8&connectTimeout=1000&autoReconnect=true
2 | db.user=root
3 | db.password=
4 | db.initialSize=10
5 | db.maxActive=10
6 | db.maxIdle=5
7 | db.maxWait=5
8 | db.poolPreparedStatements=true
--------------------------------------------------------------------------------
/diamond-server/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=info, ServerDailyRollingFile
2 | log4j.appender.ServerDailyRollingFile=org.apache.log4j.DailyRollingFileAppender
3 | log4j.appender.ServerDailyRollingFile.DatePattern='.'yyyy-MM-dd_HH
4 | log4j.appender.ServerDailyRollingFile.File=${webapp.root}/WEB-INF/logs/diamondServer.log
5 | log4j.appender.ServerDailyRollingFile.layout=org.apache.log4j.PatternLayout
6 | log4j.appender.ServerDailyRollingFile.layout.ConversionPattern=%d %-5p %c{2} - %m%n
7 | log4j.appender.ServerDailyRollingFile.Append=true
--------------------------------------------------------------------------------
/diamond-server/src/main/resources/node.properties:
--------------------------------------------------------------------------------
1 | #ip\:port=
--------------------------------------------------------------------------------
/diamond-server/src/main/resources/system.properties:
--------------------------------------------------------------------------------
1 | dump_config_interval=600
2 | diamond.server.addr=127.0.0.1
--------------------------------------------------------------------------------
/diamond-server/src/main/resources/user.properties:
--------------------------------------------------------------------------------
1 | abc=123
2 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Class-Path:
3 |
4 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/WEB-INF/applicationContext.xml:
--------------------------------------------------------------------------------
1 |
2 |
11 |
12 |
14 |
15 |
17 |
19 |
20 |
22 |
23 |
24 |
26 |
27 |
28 | classpath:system.properties
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/WEB-INF/diamond-servlet.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 | webAppRootKey
9 | webapp.root
10 |
11 |
12 | log4jConfigLocation
13 | classpath:/log4j.properties
14 |
15 |
16 | log4jRefreshInterval
17 | 60000
18 |
19 |
20 |
21 | org.springframework.web.util.Log4jConfigListener
22 |
23 |
24 |
25 | org.springframework.web.context.ContextLoaderListener
26 |
27 |
28 |
29 |
30 | encodingFilter
31 | org.springframework.web.filter.CharacterEncodingFilter
32 |
33 | encoding
34 | utf-8
35 |
36 |
37 |
38 |
39 | authorizationFilter
40 | com.taobao.diamond.server.listener.AuthorizationFilter
41 |
42 |
43 |
44 | encodingFilter
45 | *.do
46 |
47 |
48 |
49 | authorizationFilter
50 | /jsp/admin/*
51 |
52 |
53 |
54 | authorizationFilter
55 | /admin.do
56 |
57 |
58 |
59 | diamond
60 | org.springframework.web.servlet.DispatcherServlet
61 | 1
62 |
63 |
64 |
65 | ConfigServlet
66 | com.taobao.diamond.server.controller.ConfigServlet
67 | -1
68 |
69 |
70 |
71 | diamond
72 | *.do
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | ConfigServlet
84 | /config.co
85 |
86 |
87 |
88 | /jsp/login.jsp
89 |
90 |
91 |
92 | 500
93 | /jsp/500.jsp
94 |
95 |
96 |
97 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/js/fabtabulous.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Fabtabulous! Simple tabs using Prototype
3 | * http://tetlaw.id.au/view/blog/fabtabulous-simple-tabs-using-prototype/
4 | * Andrew Tetlaw
5 | * version 1.1 2006-05-06
6 | * http://creativecommons.org/licenses/by-sa/2.5/
7 | */
8 | var Fabtabs = Class.create();
9 |
10 | Fabtabs.prototype = {
11 | initialize : function(element) {
12 | this.element = $(element);
13 | var options = Object.extend({}, arguments[1] || {});
14 | this.menu = $A(this.element.getElementsByTagName('a'));
15 | this.show(this.getInitialTab());
16 | this.menu.each(this.setupTab.bind(this));
17 | },
18 | setupTab : function(elm) {
19 | Event.observe(elm,'click',this.activate.bindAsEventListener(this),false)
20 | },
21 | activate : function(ev) {
22 | var elm = Event.findElement(ev, "a");
23 | //Event.stop(ev);
24 | this.show(elm);
25 | this.menu.without(elm).each(this.hide.bind(this));
26 | },
27 | hide : function(elm) {
28 | $(elm).removeClassName('active-tab');
29 | $(this.tabID(elm)).removeClassName('active-tab-body');
30 | },
31 | show : function(elm) {
32 | $(elm).addClassName('active-tab');
33 | $(this.tabID(elm)).addClassName('active-tab-body');
34 |
35 | },
36 | tabID : function(elm) {
37 | elm.href.match(/#(\w.+)/);
38 | return RegExp.$1;
39 | },
40 | getInitialTab : function() {
41 | if(document.location.href.match(/#(\w.+)/)) {
42 | var loc = RegExp.$1;
43 | var elm = this.menu.find(function(value) { value.href.match(/#(\w.+)/); return RegExp.$1 == loc; });
44 | return elm || this.menu.first();
45 | } else {
46 | return this.menu.first();
47 | }
48 | }
49 | }
50 |
51 | Event.observe(window,'load',function(){ new Fabtabs('tabs'); },false);
52 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/js/tooltips.js:
--------------------------------------------------------------------------------
1 | //compatible with prototype
2 | if(typeof Prototype != 'undefined' && (typeof $ != 'undefined')) {
3 | $prototype = $;
4 | }
5 |
6 |
7 | // Tooltip Object
8 | var Tooltip = Class.create();
9 | Tooltip.prototype = {
10 | initialize: function(el, options) {
11 | this.el = $prototype(el);
12 | this.initialized = false;
13 | this.setOptions(options);
14 |
15 | // Event handlers
16 | this.showEvent = this.show.bindAsEventListener(this);
17 | this.hideEvent = this.hide.bindAsEventListener(this);
18 | this.updateEvent = this.update.bindAsEventListener(this);
19 | Event.observe(this.el, "mouseover", this.showEvent );
20 | Event.observe(this.el, "mouseout", this.hideEvent );
21 |
22 | // Removing title from DOM element to avoid showing it
23 | this.content = this.el.title;
24 | this.el.title = "";
25 |
26 | // If descendant elements has 'alt' attribute defined, clear it
27 | this.el.descendants().each(function(el){
28 | if(Element.readAttribute(el, 'alt'))
29 | el.alt = "";
30 | });
31 | },
32 | setOptions: function(options) {
33 | this.options = {
34 | backgroundColor: '#999', // Default background color
35 | borderColor: '#666', // Default border color
36 | textColor: '', // Default text color (use CSS value)
37 | textShadowColor: '', // Default text shadow color (use CSS value)
38 | maxWidth: 250, // Default tooltip width
39 | align: "left", // Default align
40 | delay: 250, // Default delay before tooltip appears in ms
41 | mouseFollow: true, // Tooltips follows the mouse moving
42 | opacity: .75, // Default tooltips opacity
43 | appearDuration: .25, // Default appear duration in sec
44 | hideDuration: .25 // Default disappear duration in sec
45 | };
46 | Object.extend(this.options, options || {});
47 | },
48 | show: function(e) {
49 | this.xCord = Event.pointerX(e);
50 | this.yCord = Event.pointerY(e);
51 | if(!this.initialized)
52 | this.timeout = window.setTimeout(this.appear.bind(this), this.options.delay);
53 | },
54 | hide: function(e) {
55 | if(this.initialized) {
56 | //this.appearingFX.cancel();
57 | if(this.options.mouseFollow)
58 | Event.stopObserving(this.el, "mousemove", this.updateEvent);
59 | this.tooltip.hide();
60 | //new Effect.Fade(this.tooltip, {duration: this.options.hideDuration, afterFinish: function() { Element.remove(this.tooltip) }.bind(this) });
61 | }
62 | this._clearTimeout(this.timeout);
63 |
64 | this.initialized = false;
65 | },
66 | update: function(e){
67 | this.xCord = Event.pointerX(e);
68 | this.yCord = Event.pointerY(e);
69 | this.setup();
70 | },
71 | appear: function() {
72 | // Building tooltip container
73 | /*
74 | this.tooltip = Builder.node("div", {className: "tooltip", style: "display: none;" }, [
75 | Builder.node("div", {className:"xtop"}, [
76 | Builder.node("div", {className:"xb1", style:"background-color:" + this.options.borderColor + ";"}),
77 | Builder.node("div", {className:"xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
78 | Builder.node("div", {className:"xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
79 | Builder.node("div", {className:"xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"})
80 | ]),
81 | Builder.node("div", {className: "xboxcontent", style: "background-color:" + this.options.backgroundColor +
82 | "; border-color:" + this.options.borderColor +
83 | ((this.options.textColor != '') ? "; color:" + this.options.textColor : "") +
84 | ((this.options.textShadowColor != '') ? "; text-shadow:2px 2px 0" + this.options.textShadowColor + ";" : "")}, this.content),
85 | Builder.node("div", {className:"xbottom"}, [
86 | Builder.node("div", {className:"xb4", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
87 | Builder.node("div", {className:"xb3", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
88 | Builder.node("div", {className:"xb2", style: "background-color:" + this.options.backgroundColor + "; border-color:" + this.options.borderColor + ";"}),
89 | Builder.node("div", {className:"xb1", style:"background-color:" + this.options.borderColor + ";"})
90 | ]),
91 | ]);
92 | */
93 |
94 | var tooltipString = ''+
95 | ''
112 | new Insertion.Before(document.body.childNodes[0], tooltipString)
113 | this.tooltip = document.body.childNodes[0];
114 | //document.body.insertBefore(this.tooltip, document.body.childNodes[0]);
115 |
116 | Element.extend(this.tooltip); // IE needs element to be manually extended
117 | this.options.width = this.tooltip.getWidth();
118 | this.tooltip.style.width = this.options.width + 'px'; // IE7 needs width to be defined
119 |
120 | this.setup();
121 |
122 | if(this.options.mouseFollow)
123 | Event.observe(this.el, "mousemove", this.updateEvent);
124 |
125 | this.initialized = true;
126 | this.tooltip.show();
127 | //this.appearingFX = new Effect.Appear(this.tooltip, {duration: this.options.appearDuration, to: this.options.opacity });
128 | },
129 | setup: function(){
130 | // If content width is more then allowed max width, set width to max
131 | if(this.options.width > this.options.maxWidth) {
132 | this.options.width = this.options.maxWidth;
133 | this.tooltip.style.width = this.options.width + 'px';
134 | }
135 |
136 | // Tooltip doesn't fit the current document dimensions
137 | if(this.xCord + this.options.width >= Element.getWidth(document.body)) {
138 | this.options.align = "right";
139 | this.xCord = this.xCord - this.options.width + 20;
140 | }
141 |
142 | this.tooltip.style.left = this.xCord - 7 + "px";
143 | this.tooltip.style.top = this.yCord + 12 + "px";
144 | },
145 | stop: function () {
146 | this.hide();
147 | Event.stopObserving(this.el, "mouseover", this.showEvent);
148 | Event.stopObserving(this.el, "mouseout", this.hideEvent);
149 | Event.stopObserving(this.el, "mousemove", this.updateEvent);
150 | },
151 | _clearTimeout: function(timer) {
152 | clearTimeout(timer);
153 | clearInterval(timer);
154 | return null;
155 | }
156 | };
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/js/validation_cn.js:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/js/validation_cn.js
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/200.jsp:
--------------------------------------------------------------------------------
1 | <%
2 | Object o = request.getAttribute("content");
3 | if(o==null||o.equals("")){
4 | out.println("OK");
5 | }else{
6 | out.println(o);
7 | }
8 | %>
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/400.jsp:
--------------------------------------------------------------------------------
1 | remote ip is null
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/500.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/500.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/503.jsp:
--------------------------------------------------------------------------------
1 | Serivce is unavailable now.Request is refused.
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/admin.jsp:
--------------------------------------------------------------------------------
1 | <%@ page contentType="text/html; charset=GBK" pageEncoding="GBK"%>
2 |
6 |
7 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/config/batch_result.jsp:
--------------------------------------------------------------------------------
1 | ${json}
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/config/edit.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/config/edit.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/config/list.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/config/list.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/config/list_json.jsp:
--------------------------------------------------------------------------------
1 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 | <%@ page contentType="application/json;charset=GBK" pageEncoding="GBK"%>
3 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/config/new.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/config/new.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/config/upload.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/config/upload.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/count.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/count.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/menu.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/menu.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/user/list.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/user/list.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/user/new.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/user/new.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/admin/welcome.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/admin/welcome.jsp
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/common/message.jsp:
--------------------------------------------------------------------------------
1 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 | <%@ page contentType="text/html; charset=GBK" pageEncoding="GBK"%>
3 |
4 |
5 |
--------------------------------------------------------------------------------
/diamond-server/src/main/webapp/jsp/login.jsp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gzllol/diamond/f559792388c5f340c3dfaf45a4b082af5246ec38/diamond-server/src/main/webapp/jsp/login.jsp
--------------------------------------------------------------------------------
/diamond-utils/pom.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 | diamond-all
6 | com.taobao.diamond
7 | 2.0.5.4.taocode-SNAPSHOT
8 |
9 |
10 | 4.0.0
11 | diamond-utils
12 | diamond-utils v${project.version}
13 |
14 |
15 |
16 | commons-logging
17 | commons-logging
18 |
19 |
20 | commons-io
21 | commons-io
22 |
23 |
24 | org.codehaus.jackson
25 | jackson-core-lgpl
26 |
27 |
28 | org.codehaus.jackson
29 | jackson-mapper-lgpl
30 |
31 |
32 | junit
33 | junit
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/common/Constants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.common;
11 |
12 | public interface Constants {
13 |
14 | public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
15 |
16 | public static final String BASE_DIR = "config-data";
17 |
18 | public static final String DEFAULT_DOMAINNAME = "config.diamond.org";
19 |
20 | public static final String DAILY_DOMAINNAME = "config.diamond.org";
21 |
22 | public static final int DEFAULT_PORT = 8080;
23 |
24 | public static final String NULL = "";
25 |
26 | public static final String DATAID = "dataId";
27 |
28 | public static final String GROUP = "group";
29 |
30 | public static final String LAST_MODIFIED = "Last-Modified";
31 |
32 | public static final String ACCEPT_ENCODING = "Accept-Encoding";
33 |
34 | public static final String CONTENT_ENCODING = "Content-Encoding";
35 |
36 | public static final String PROBE_MODIFY_REQUEST = "Probe-Modify-Request";
37 |
38 | public static final String PROBE_MODIFY_RESPONSE = "Probe-Modify-Response";
39 |
40 | public static final String PROBE_MODIFY_RESPONSE_NEW = "Probe-Modify-Response-New";
41 |
42 | public static final String CONTENT_MD5 = "Content-MD5";
43 |
44 | public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
45 |
46 | public static final String SPACING_INTERVAL = "client-spacing-interval";
47 |
48 | public static final int POLLING_INTERVAL_TIME = 15;// 秒
49 |
50 | public static final int ONCE_TIMEOUT = 2000;// 毫秒
51 |
52 | public static final int CONN_TIMEOUT = 2000;// 毫秒
53 |
54 | public static final int RECV_WAIT_TIMEOUT = ONCE_TIMEOUT * 5;// 毫秒
55 |
56 | public static final String HTTP_URI_FILE = "/config.co";
57 |
58 | public static final String CONFIG_HTTP_URI_FILE = "/url.do";
59 |
60 | public static final String HTTP_URI_LOGIN = "/url";
61 |
62 | public static final String ENCODE = "GBK";
63 |
64 | public static final String LINE_SEPARATOR = Character.toString((char) 1);
65 |
66 | public static final String WORD_SEPARATOR = Character.toString((char) 2);
67 |
68 | public static final String DEFAULT_USERNAME = "xxx";
69 |
70 | public static final String DEFAULT_PASSWORD = "xxx";
71 |
72 | /*
73 | * 批量操作时, 单条数据的状态码
74 | */
75 | // 发生异常
76 | public static final int BATCH_OP_ERROR = -1;
77 | // 查询成功, 数据存在
78 | public static final int BATCH_QUERY_EXISTS = 1;
79 | // 查询成功, 数据不存在
80 | public static final int BATCH_QUERY_NONEXISTS = 2;
81 | // 新增成功
82 | public static final int BATCH_ADD_SUCCESS = 3;
83 | // 更新成功
84 | public static final int BATCH_UPDATE_SUCCESS = 4;
85 |
86 | String CONF_KEY_CONFIG_IP = "diamond.config.ip";
87 | String CONF_KEY_PORT = "diamond.port";
88 |
89 | }
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/domain/ConfigInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.domain;
11 |
12 | import java.io.PrintWriter;
13 | import java.io.Serializable;
14 |
15 | import com.taobao.diamond.md5.MD5;
16 |
17 |
18 | /**
19 | * 配置信息类
20 | *
21 | * @author boyan
22 | * @date 2010-5-4
23 | */
24 | public class ConfigInfo implements Serializable, Comparable {
25 | static final long serialVersionUID = -1L;
26 | private String dataId;
27 | private String content;
28 | private String md5;
29 |
30 | private String group;
31 | private long id;
32 |
33 |
34 | public ConfigInfo() {
35 |
36 | }
37 |
38 |
39 | public ConfigInfo(String dataId, String group, String content) {
40 | super();
41 | this.dataId = dataId;
42 | this.content = content;
43 | this.group = group;
44 | if (this.content != null) {
45 | this.md5 = MD5.getInstance().getMD5String(this.content);
46 | }
47 | }
48 |
49 |
50 | public long getId() {
51 | return id;
52 | }
53 |
54 |
55 | public void setId(long id) {
56 | this.id = id;
57 | }
58 |
59 |
60 | public String getDataId() {
61 | return dataId;
62 | }
63 |
64 |
65 | public void setDataId(String dataId) {
66 | this.dataId = dataId;
67 | }
68 |
69 |
70 | public String getGroup() {
71 | return group;
72 | }
73 |
74 |
75 | public void setGroup(String group) {
76 | this.group = group;
77 | }
78 |
79 |
80 | public String getContent() {
81 | return content;
82 | }
83 |
84 |
85 | public void setContent(String content) {
86 | this.content = content;
87 | }
88 |
89 |
90 | public void dump(PrintWriter writer) {
91 | writer.write(this.content);
92 | }
93 |
94 |
95 | public String getMd5() {
96 | return md5;
97 | }
98 |
99 |
100 | public void setMd5(String md5) {
101 | this.md5 = md5;
102 | }
103 |
104 |
105 | public int compareTo(ConfigInfo o) {
106 | if (o == null)
107 | return 1;
108 |
109 | if (this.dataId == null && o.getDataId() != null)
110 | return -1;
111 | int cmpDataId = this.dataId.compareTo(o.getDataId());
112 | if (cmpDataId != 0) {
113 | return cmpDataId;
114 | }
115 | if (this.group == null && o.getGroup() != null)
116 | return -1;
117 | int cmpGroup = this.group.compareTo(o.getGroup());
118 | if (cmpGroup != 0) {
119 | return cmpGroup;
120 | }
121 | if (this.content == null && o.getContent() != null)
122 | return -1;
123 | int cmpContent = this.content.compareTo(o.getContent());
124 | if (cmpContent != 0) {
125 | return cmpContent;
126 | }
127 | return 0;
128 | }
129 |
130 |
131 | @Override
132 | public int hashCode() {
133 | final int prime = 31;
134 | int result = 1;
135 | result = prime * result + ((content == null) ? 0 : content.hashCode());
136 | result = prime * result + ((dataId == null) ? 0 : dataId.hashCode());
137 | result = prime * result + ((group == null) ? 0 : group.hashCode());
138 | result = prime * result + ((md5 == null) ? 0 : md5.hashCode());
139 | return result;
140 | }
141 |
142 |
143 | @Override
144 | public boolean equals(Object obj) {
145 | if (this == obj)
146 | return true;
147 | if (obj == null)
148 | return false;
149 | if (getClass() != obj.getClass())
150 | return false;
151 | ConfigInfo other = (ConfigInfo) obj;
152 | if (content == null) {
153 | if (other.content != null)
154 | return false;
155 | }
156 | else if (!content.equals(other.content))
157 | return false;
158 | if (dataId == null) {
159 | if (other.dataId != null)
160 | return false;
161 | }
162 | else if (!dataId.equals(other.dataId))
163 | return false;
164 | if (group == null) {
165 | if (other.group != null)
166 | return false;
167 | }
168 | else if (!group.equals(other.group))
169 | return false;
170 | if (md5 == null) {
171 | if (other.md5 != null)
172 | return false;
173 | }
174 | else if (!md5.equals(other.md5))
175 | return false;
176 | return true;
177 | }
178 |
179 |
180 | @Override
181 | public String toString() {
182 | return "[" + "dataId=" + dataId + "," + "groupName=" + group + "," + "context=" + content + "," + "]";
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/domain/ConfigInfoEx.java:
--------------------------------------------------------------------------------
1 | package com.taobao.diamond.domain;
2 |
3 | /**
4 | * ConfigInfo的扩展类, 解决老版本的SDK与新版本的server由于反序列化字段错误而产生的不兼容问题
5 | *
6 | * @author leiwen.zh
7 | *
8 | */
9 | public class ConfigInfoEx extends ConfigInfo {
10 |
11 | private static final long serialVersionUID = -1L;
12 |
13 | // 批量查询时, 单条数据的状态码, 具体的状态码在Constants.java中
14 | private int status;
15 | // 批量查询时, 单条数据的信息
16 | private String message;
17 |
18 |
19 | public ConfigInfoEx() {
20 | super();
21 | }
22 |
23 |
24 | public ConfigInfoEx(String dataId, String group, String content) {
25 | super(dataId, group, content);
26 | }
27 |
28 |
29 | public int getStatus() {
30 | return status;
31 | }
32 |
33 |
34 | public void setStatus(int status) {
35 | this.status = status;
36 | }
37 |
38 |
39 | public String getMessage() {
40 | return message;
41 | }
42 |
43 |
44 | public void setMessage(String message) {
45 | this.message = message;
46 | }
47 |
48 |
49 | @Override
50 | public String toString() {
51 | return "ConfigInfoEx [status=" + status + ", message=" + message
52 | + ", getDataId()=" + getDataId() + ", getGroup()=" + getGroup()
53 | + ", getContent()=" + getContent() + ", getMd5()=" + getMd5()
54 | + "]";
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/domain/Page.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.domain;
11 |
12 | import java.io.Serializable;
13 | import java.util.ArrayList;
14 | import java.util.List;
15 |
16 |
17 | /**
18 | * 分页对象
19 | *
20 | * @author boyan
21 | * @date 2010-5-6
22 | * @param
23 | */
24 | public class Page implements Serializable {
25 | static final long serialVersionUID = -1L;
26 |
27 | private int totalCount; // 总记录数
28 | private int pageNumber; // 页数
29 | private int pagesAvailable; // 总页数
30 | private List pageItems = new ArrayList(); // 该页内容
31 |
32 |
33 | public void setPageNumber(int pageNumber) {
34 | this.pageNumber = pageNumber;
35 | }
36 |
37 |
38 | public void setPagesAvailable(int pagesAvailable) {
39 | this.pagesAvailable = pagesAvailable;
40 | }
41 |
42 |
43 | public void setPageItems(List pageItems) {
44 | this.pageItems = pageItems;
45 | }
46 |
47 |
48 | public int getTotalCount() {
49 | return totalCount;
50 | }
51 |
52 |
53 | public void setTotalCount(int totalCount) {
54 | this.totalCount = totalCount;
55 | }
56 |
57 |
58 | public int getPageNumber() {
59 | return pageNumber;
60 | }
61 |
62 |
63 | public int getPagesAvailable() {
64 | return pagesAvailable;
65 | }
66 |
67 |
68 | public List getPageItems() {
69 | return pageItems;
70 | }
71 | }
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/FileSystem.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io;
11 |
12 | import com.taobao.diamond.io.watch.WatchService;
13 |
14 |
15 | /**
16 | * 文件系统类,提供基础操作
17 | *
18 | * @author boyan
19 | * @date 2010-5-4
20 | */
21 | public class FileSystem {
22 | private static final FileSystem instance = new FileSystem();
23 |
24 | private String interval = System.getProperty("diamon.watch.interval", "5000");
25 |
26 |
27 | public void setInterval(String interval) {
28 | this.interval = interval;
29 | }
30 |
31 |
32 | public static final FileSystem getDefault() {
33 | return instance;
34 | }
35 |
36 |
37 | /**
38 | * 生成一个新的WatchService
39 | *
40 | * @return
41 | */
42 | public WatchService newWatchService() {
43 | return new WatchService(Long.valueOf(interval));
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/Path.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io;
11 |
12 | import java.io.File;
13 | import java.io.FileFilter;
14 | import java.io.FilenameFilter;
15 | import java.io.IOException;
16 | import java.net.URI;
17 |
18 | import com.taobao.diamond.io.watch.WatchEvent.Kind;
19 | import com.taobao.diamond.io.watch.WatchKey;
20 | import com.taobao.diamond.io.watch.WatchService;
21 | import com.taobao.diamond.io.watch.Watchable;
22 |
23 |
24 | /**
25 | * File对象的封装
26 | *
27 | * @author boyan
28 | * @date 2010-5-4
29 | */
30 | public class Path implements Watchable {
31 | private File file;
32 |
33 |
34 | public Path(File file) {
35 | super();
36 | this.file = file;
37 | }
38 |
39 |
40 | public File getFile() {
41 | return file;
42 | }
43 |
44 |
45 | public boolean canExecute() {
46 | return file.canExecute();
47 | }
48 |
49 |
50 | public boolean canRead() {
51 | return file.canRead();
52 | }
53 |
54 |
55 | public boolean canWrite() {
56 | return file.canWrite();
57 | }
58 |
59 |
60 | public int compareTo(File pathname) {
61 | return file.compareTo(pathname);
62 | }
63 |
64 |
65 | public boolean createNewFile() throws IOException {
66 | return file.createNewFile();
67 | }
68 |
69 |
70 | public boolean delete() {
71 | return file.delete();
72 | }
73 |
74 |
75 | public void deleteOnExit() {
76 | file.deleteOnExit();
77 | }
78 |
79 |
80 | public boolean equals(Object obj) {
81 | return file.equals(obj);
82 | }
83 |
84 |
85 | public boolean exists() {
86 | return file.exists();
87 | }
88 |
89 |
90 | public File getAbsoluteFile() {
91 | return file.getAbsoluteFile();
92 | }
93 |
94 |
95 | public String getAbsolutePath() {
96 | return file.getAbsolutePath();
97 | }
98 |
99 |
100 | public File getCanonicalFile() throws IOException {
101 | return file.getCanonicalFile();
102 | }
103 |
104 |
105 | public String getCanonicalPath() throws IOException {
106 | return file.getCanonicalPath();
107 | }
108 |
109 |
110 | public long getFreeSpace() {
111 | return file.getFreeSpace();
112 | }
113 |
114 |
115 | public String getName() {
116 | return file.getName();
117 | }
118 |
119 |
120 | public String getParent() {
121 | return file.getParent();
122 | }
123 |
124 |
125 | public File getParentFile() {
126 | return file.getParentFile();
127 | }
128 |
129 |
130 | public String getPath() {
131 | return file.getPath();
132 | }
133 |
134 |
135 | public long getTotalSpace() {
136 | return file.getTotalSpace();
137 | }
138 |
139 |
140 | public long getUsableSpace() {
141 | return file.getUsableSpace();
142 | }
143 |
144 |
145 | public int hashCode() {
146 | return file.hashCode();
147 | }
148 |
149 |
150 | public boolean isAbsolute() {
151 | return file.isAbsolute();
152 | }
153 |
154 |
155 | public boolean isDirectory() {
156 | return file.isDirectory();
157 | }
158 |
159 |
160 | public boolean isFile() {
161 | return file.isFile();
162 | }
163 |
164 |
165 | public boolean isHidden() {
166 | return file.isHidden();
167 | }
168 |
169 |
170 | public long lastModified() {
171 | return file.lastModified();
172 | }
173 |
174 |
175 | public long length() {
176 | return file.length();
177 | }
178 |
179 |
180 | public String[] list() {
181 | return file.list();
182 | }
183 |
184 |
185 | public String[] list(FilenameFilter filter) {
186 | return file.list(filter);
187 | }
188 |
189 |
190 | public File[] listFiles() {
191 | return file.listFiles();
192 | }
193 |
194 |
195 | public File[] listFiles(FileFilter filter) {
196 | return file.listFiles(filter);
197 | }
198 |
199 |
200 | public File[] listFiles(FilenameFilter filter) {
201 | return file.listFiles(filter);
202 | }
203 |
204 |
205 | public boolean mkdir() {
206 | return file.mkdir();
207 | }
208 |
209 |
210 | public boolean mkdirs() {
211 | return file.mkdirs();
212 | }
213 |
214 |
215 | public boolean renameTo(File dest) {
216 | return file.renameTo(dest);
217 | }
218 |
219 |
220 | public boolean setExecutable(boolean executable, boolean ownerOnly) {
221 | return file.setExecutable(executable, ownerOnly);
222 | }
223 |
224 |
225 | public boolean setExecutable(boolean executable) {
226 | return file.setExecutable(executable);
227 | }
228 |
229 |
230 | public boolean setLastModified(long time) {
231 | return file.setLastModified(time);
232 | }
233 |
234 |
235 | public boolean setReadable(boolean readable, boolean ownerOnly) {
236 | return file.setReadable(readable, ownerOnly);
237 | }
238 |
239 |
240 | public boolean setReadable(boolean readable) {
241 | return file.setReadable(readable);
242 | }
243 |
244 |
245 | public boolean setReadOnly() {
246 | return file.setReadOnly();
247 | }
248 |
249 |
250 | public boolean setWritable(boolean writable, boolean ownerOnly) {
251 | return file.setWritable(writable, ownerOnly);
252 | }
253 |
254 |
255 | public boolean setWritable(boolean writable) {
256 | return file.setWritable(writable);
257 | }
258 |
259 |
260 | public String toString() {
261 | return file.toString();
262 | }
263 |
264 |
265 | public URI toURI() {
266 | return file.toURI();
267 | }
268 |
269 |
270 | public WatchKey register(WatchService watcher, Kind>... events) {
271 | return watcher.register(this, events);
272 | }
273 |
274 | }
275 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/watch/StandardWatchEventKind.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io.watch;
11 |
12 | import com.taobao.diamond.io.Path;
13 |
14 |
15 | /**
16 | * 标准WatchEvent
17 | *
18 | * @author boyan
19 | *
20 | */
21 | public class StandardWatchEventKind {
22 |
23 | /**
24 | * Directory entry created
25 | */
26 | public static final WatchEvent.Kind ENTRY_CREATE = new WatchEvent.Kind() {
27 | public String name() {
28 | return "ENTRY_CREATE";
29 | }
30 |
31 |
32 | public Class type() {
33 | return Path.class;
34 | }
35 |
36 | };
37 |
38 | /**
39 | * Directory entry deleted
40 | */
41 | public static final WatchEvent.Kind ENTRY_DELETE = new WatchEvent.Kind() {
42 | public String name() {
43 | return "ENTRY_DELETE";
44 | }
45 |
46 |
47 | public Class type() {
48 | return Path.class;
49 | }
50 |
51 | };
52 |
53 | /**
54 | * Directory entry modified
55 | */
56 | public static final WatchEvent.Kind ENTRY_MODIFY = new WatchEvent.Kind() {
57 | public String name() {
58 | return "ENTRY_MODIFY";
59 | }
60 |
61 |
62 | public Class type() {
63 | return Path.class;
64 | }
65 |
66 | };
67 |
68 | /**
69 | * Directory entry overflow
70 | */
71 | public static final WatchEvent.Kind OVERFLOW = new WatchEvent.Kind() {
72 | public String name() {
73 | return "OVERFLOW";
74 | }
75 |
76 |
77 | public Class type() {
78 | return Void.class;
79 | }
80 |
81 | };
82 | }
83 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/watch/WatchEvent.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io.watch;
11 |
12 | /**
13 | *
14 | * @author boyan
15 | * @date 2010-5-4
16 | * @param
17 | */
18 | public class WatchEvent {
19 | public static interface Kind {
20 | public String name();
21 |
22 |
23 | public Class type();
24 | }
25 |
26 | private Kind kind;
27 |
28 | private int count;
29 |
30 | private T context;
31 |
32 |
33 | public WatchEvent(Kind kind, int count, T context) {
34 | super();
35 | this.kind = kind;
36 | this.count = count;
37 | this.context = context;
38 | }
39 |
40 |
41 | public Kind kind() {
42 | return kind;
43 |
44 | }
45 |
46 |
47 | public int count() {
48 | return count;
49 | }
50 |
51 |
52 | public T context() {
53 | return context;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/watch/WatchKey.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io.watch;
11 |
12 | import java.io.File;
13 | import java.util.HashSet;
14 | import java.util.Iterator;
15 | import java.util.LinkedList;
16 | import java.util.List;
17 | import java.util.Set;
18 |
19 | import com.taobao.diamond.io.Path;
20 | import com.taobao.diamond.io.watch.util.PathNode;
21 |
22 |
23 | /**
24 | * WatchKey,表示一个注册的的凭证
25 | *
26 | * @author boyan
27 | * @date 2010-5-4
28 | */
29 | public class WatchKey {
30 |
31 | private volatile boolean valid;
32 |
33 | private final PathNode root;
34 |
35 | private List> changedEvents;
36 |
37 | private final Set> filterSet = new HashSet>();
38 |
39 | private final WatchService watcher;
40 |
41 |
42 | public WatchKey(final Path path, final WatchService watcher, boolean fireCreatedEventOnIndex,
43 | WatchEvent.Kind>... events) {
44 | valid = true;
45 | this.watcher = watcher;
46 | // 建立内存索引
47 | this.root = new PathNode(path, true);
48 | if (events != null) {
49 | for (WatchEvent.Kind> event : events) {
50 | filterSet.add(event);
51 | }
52 | }
53 | LinkedList> changedEvents = new LinkedList>();
54 | index(this.root, fireCreatedEventOnIndex, changedEvents);
55 | this.changedEvents = changedEvents;
56 | }
57 |
58 |
59 | /**
60 | * 索引目录
61 | *
62 | * @param node
63 | */
64 | private void index(PathNode node, boolean fireCreatedEventOnIndex, LinkedList> changedEvents) {
65 | File file = node.getPath().getFile();
66 | if (!file.isDirectory()) {
67 | return;
68 | }
69 | File[] subFiles = file.listFiles();
70 | if (subFiles != null) {
71 | for (File subFile : subFiles) {
72 | PathNode subNode = new PathNode(new Path(subFile), false);
73 | if (fireCreatedEventOnIndex) {
74 | changedEvents.add(new WatchEvent(StandardWatchEventKind.ENTRY_CREATE, 1, subNode.getPath()));
75 | }
76 | node.addChild(subNode);
77 | if (subNode.getPath().isDirectory()) {
78 | index(subNode, fireCreatedEventOnIndex, changedEvents);
79 | }
80 | }
81 | }
82 | }
83 |
84 |
85 | public void cancel() {
86 | this.valid = false;
87 | }
88 |
89 |
90 | @Override
91 | public String toString() {
92 | return "WatchKey [root=" + root + ", valid=" + valid + "]";
93 | }
94 |
95 |
96 | public boolean isValid() {
97 | return valid && root != null;
98 | }
99 |
100 |
101 | public List> pollEvents() {
102 | if (changedEvents != null) {
103 | List> result = changedEvents;
104 | changedEvents = null;
105 | return result;
106 | }
107 | return null;
108 | }
109 |
110 |
111 | /**
112 | * 检测是否有变化
113 | *
114 | * @return
115 | */
116 | boolean check() {
117 | if (this.changedEvents != null && this.changedEvents.size() > 0)
118 | return true;
119 | if (!this.valid)
120 | return false;
121 | List> list = new LinkedList>();
122 | if (check(root, list)) {
123 | this.changedEvents = list;
124 | return true;
125 | }
126 | else {
127 | return false;
128 | }
129 | }
130 |
131 |
132 | private boolean check(PathNode node, List> changedEvents) {
133 | Path nodePath = node.getPath();
134 | File nodeNewFile = new File(nodePath.getAbsolutePath());
135 | if (nodePath != null) {
136 | if (node.isRoot()) {
137 | if (!nodeNewFile.exists())
138 | return fireOnRootDeleted(changedEvents, nodeNewFile);
139 | else {
140 | return checkNodeChildren(node, changedEvents, nodeNewFile);
141 | }
142 | }
143 | else {
144 | return checkNodeChildren(node, changedEvents, nodeNewFile);
145 | }
146 | }
147 | else
148 | throw new IllegalStateException("PathNode没有path");
149 | }
150 |
151 |
152 | private boolean checkNodeChildren(PathNode node, List> changedEvents, File nodeNewFile) {
153 | boolean changed = false;
154 | Iterator it = node.getChildren().iterator();
155 | // 用于判断是否有新增文件或者目录的现有名称集合
156 | Set childNameSet = new HashSet();
157 | while (it.hasNext()) {
158 | PathNode child = it.next();
159 | Path childPath = child.getPath();
160 | childNameSet.add(childPath.getName());
161 | File childNewFile = new File(childPath.getAbsolutePath());
162 | // 1、判断文件是否还存在
163 | if (!childNewFile.exists() && filterSet.contains(StandardWatchEventKind.ENTRY_DELETE)) {
164 | changed = true;
165 | changedEvents.add(new WatchEvent(StandardWatchEventKind.ENTRY_DELETE, 1, childPath));
166 | it.remove();// 移除节点
167 | }
168 | // 2、如果是文件,判断是否被修改
169 | if (childPath.isFile()) {
170 | if (checkFile(changedEvents, child, childNewFile) && !changed) {
171 | changed = true;
172 | }
173 |
174 | }
175 | // 3、递归检测目录
176 | if (childPath.isDirectory()) {
177 | if (check(child, changedEvents) && !changed) {
178 | changed = true;
179 | }
180 | }
181 | }
182 |
183 | // 查看是否有新增文件
184 | File[] newChildFiles = nodeNewFile.listFiles();
185 | if(newChildFiles!=null)
186 | for (File newChildFile : newChildFiles) {
187 | if (!childNameSet.contains(newChildFile.getName())
188 | && filterSet.contains(StandardWatchEventKind.ENTRY_CREATE)) {
189 | changed = true;
190 | Path newChildPath = new Path(newChildFile);
191 | changedEvents.add(new WatchEvent(StandardWatchEventKind.ENTRY_CREATE, 1, newChildPath));
192 | PathNode newSubNode = new PathNode(newChildPath, false);
193 | node.addChild(newSubNode);// 新增子节点
194 | // 如果是目录,递归调用
195 | if (newChildFile.isDirectory()) {
196 | checkNodeChildren(newSubNode, changedEvents, newChildFile);
197 | }
198 | }
199 | }
200 | return changed;
201 | }
202 |
203 |
204 | private boolean checkFile(List> changedEvents, PathNode child, File childNewFile) {
205 | boolean changed = false;
206 | // 查看文件是否被修改
207 | if (childNewFile.lastModified() != child.lastModified()
208 | && filterSet.contains(StandardWatchEventKind.ENTRY_MODIFY)) {
209 | changed = true;
210 | Path newChildPath = new Path(childNewFile);
211 | changedEvents.add(new WatchEvent(StandardWatchEventKind.ENTRY_MODIFY, 1, newChildPath));
212 | child.setPath(newChildPath);// 更新path
213 | }
214 | return changed;
215 | }
216 |
217 |
218 | private boolean fireOnRootDeleted(List> changedEvents, File nodeNewFile) {
219 | this.valid = false;
220 | if (filterSet.contains(StandardWatchEventKind.ENTRY_DELETE)) {
221 | changedEvents.add(new WatchEvent(StandardWatchEventKind.ENTRY_DELETE, 1, new Path(nodeNewFile)));
222 | return true;
223 | }
224 | return false;
225 | }
226 |
227 |
228 | public boolean reset() {
229 | if (!valid)
230 | return false;
231 | if (root == null)
232 | return false;
233 | return this.watcher.resetKey(this);
234 | }
235 | }
236 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/watch/WatchService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io.watch;
11 |
12 | import java.util.Iterator;
13 | import java.util.concurrent.BlockingQueue;
14 | import java.util.concurrent.Executors;
15 | import java.util.concurrent.LinkedBlockingQueue;
16 | import java.util.concurrent.ScheduledExecutorService;
17 | import java.util.concurrent.TimeUnit;
18 |
19 | import org.apache.commons.logging.Log;
20 | import org.apache.commons.logging.LogFactory;
21 |
22 | import com.taobao.diamond.io.Path;
23 |
24 |
25 | /**
26 | * Watch服务,为文件系统提供监视功能,当文件或者目录添加、删除或者更改的时候提供主动通知服务
27 | *
28 | * @author boyan
29 | * @date 2010-5-4
30 | */
31 | public final class WatchService {
32 | private BlockingQueue changedKeys = new LinkedBlockingQueue();
33 |
34 | private BlockingQueue watchedKeys = new LinkedBlockingQueue();
35 |
36 | private static final Log log = LogFactory.getLog(WatchService.class);
37 |
38 | private ScheduledExecutorService service;
39 |
40 |
41 | public WatchService(long checkInterval) {
42 | service = Executors.newSingleThreadScheduledExecutor();
43 | service.scheduleAtFixedRate(new CheckThread(), checkInterval, checkInterval, TimeUnit.MILLISECONDS);
44 | }
45 |
46 | private final class CheckThread implements Runnable {
47 | public void run() {
48 | check();
49 | }
50 |
51 | }
52 |
53 |
54 | /**
55 | * 主动check
56 | */
57 | public void check() {
58 | synchronized (this) {
59 | Iterator it = watchedKeys.iterator();
60 | while (it.hasNext()) {
61 | WatchKey key = it.next();
62 | try {
63 | if (key.check()) {
64 | changedKeys.add(key);
65 | it.remove();
66 | }
67 | }
68 | catch (Throwable t) {
69 | log.error("检测WatchKey异常,key=" + key, t);
70 | }
71 | }
72 | }
73 | }
74 |
75 |
76 | /**
77 | * 注册目录
78 | *
79 | * @param root
80 | * @param events
81 | * @return
82 | */
83 | public WatchKey register(Path root, WatchEvent.Kind>... events) {
84 | if (events == null || events.length == 0)
85 | throw new UnsupportedOperationException("null events");
86 | if (this.service.isShutdown())
87 | throw new IllegalStateException("服务已经关闭");
88 | if (!root.exists())
89 | throw new IllegalArgumentException("监视的目录不存在");
90 | WatchKey key = new WatchKey(root, this, false, events);
91 | resetKey(key);
92 | return key;
93 | }
94 |
95 |
96 | public WatchKey register(Path root, boolean fireCreatedEventOnIndex, WatchEvent.Kind>... events) {
97 | if (events == null || events.length == 0)
98 | throw new UnsupportedOperationException("null events");
99 | if (this.service.isShutdown())
100 | throw new IllegalStateException("服务已经关闭");
101 | if (!root.exists())
102 | throw new IllegalArgumentException("监视的目录不存在");
103 | WatchKey key = new WatchKey(root, this, fireCreatedEventOnIndex, events);
104 | resetKey(key);
105 | return key;
106 | }
107 |
108 |
109 | boolean resetKey(WatchKey key) {
110 | return this.watchedKeys.add(key);
111 | }
112 |
113 |
114 | /**
115 | * 停止服务
116 | */
117 | public void close() {
118 | this.service.shutdown();
119 | }
120 |
121 |
122 | /**
123 | * 获取改变的WatchKey
124 | *
125 | * @return
126 | */
127 | public WatchKey poll() {
128 | return changedKeys.poll();
129 | }
130 |
131 |
132 | /**
133 | * 获取改变的WatchKey
134 | *
135 | * @return
136 | */
137 | public WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException {
138 | return changedKeys.poll(timeout, unit);
139 | }
140 |
141 |
142 | /**
143 | * 获取改变的WatchKey
144 | *
145 | * @return
146 | */
147 | public WatchKey take() throws InterruptedException {
148 | return changedKeys.take();
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/watch/Watchable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io.watch;
11 |
12 | /**
13 | * 标记接口,实现此接口的类可以被注册到WatchService
14 | *
15 | * @author boyan
16 | *
17 | */
18 | public interface Watchable {
19 | public WatchKey register(WatchService watcher, WatchEvent.Kind>... events);
20 | }
21 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/io/watch/util/PathNode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.io.watch.util;
11 |
12 | import java.util.LinkedList;
13 | import java.util.List;
14 |
15 | import com.taobao.diamond.io.Path;
16 |
17 |
18 | /**
19 | * 树形目录结构的节点,缓存lastModified
20 | *
21 | * @author boyan
22 | *
23 | */
24 | public class PathNode {
25 | private List children;
26 |
27 | public Path path;
28 |
29 | private final boolean root;
30 |
31 | private long lastModified;
32 |
33 |
34 | public PathNode(Path path, boolean root) {
35 | super();
36 | this.children = new LinkedList();
37 | this.path = path;
38 | this.root = root;
39 | this.lastModified = path.lastModified();
40 | }
41 |
42 |
43 | public long lastModified() {
44 | return lastModified;
45 | }
46 |
47 |
48 | public boolean isRoot() {
49 | return root;
50 | }
51 |
52 |
53 | public List getChildren() {
54 | return children;
55 | }
56 |
57 |
58 | public void setPath(Path path) {
59 | this.path = path;
60 | this.lastModified = path.lastModified();
61 | }
62 |
63 |
64 | public Path getPath() {
65 | return path;
66 | }
67 |
68 |
69 | public void addChild(PathNode node) {
70 | this.children.add(node);
71 | }
72 |
73 |
74 | public void removeChild(PathNode node) {
75 | this.children.remove(node);
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/md5/MD5.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.md5;
11 |
12 | import java.io.UnsupportedEncodingException;
13 | import java.security.MessageDigest;
14 | import java.util.HashMap;
15 | import java.util.Map;
16 | import java.util.concurrent.locks.ReentrantLock;
17 |
18 | import org.apache.commons.logging.Log;
19 | import org.apache.commons.logging.LogFactory;
20 |
21 | import com.taobao.diamond.common.Constants;
22 |
23 |
24 | public class MD5 {
25 | private static final Log log = LogFactory.getLog(MD5.class);
26 | private static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
27 |
28 | private static Map rDigits = new HashMap(16);
29 | static {
30 | for (int i = 0; i < digits.length; ++i) {
31 | rDigits.put(digits[i], i);
32 | }
33 | }
34 |
35 | private static MD5 me = new MD5();
36 | private MessageDigest mHasher;
37 | private ReentrantLock opLock = new ReentrantLock();
38 |
39 |
40 | private MD5() {
41 | try {
42 | mHasher = MessageDigest.getInstance("md5");
43 | }
44 | catch (Exception e) {
45 | throw new RuntimeException(e);
46 | }
47 |
48 | }
49 |
50 |
51 | public static MD5 getInstance() {
52 | return me;
53 | }
54 |
55 |
56 | public String getMD5String(String content) {
57 | return bytes2string(hash(content));
58 | }
59 |
60 |
61 | public String getMD5String(byte[] content) {
62 | return bytes2string(hash(content));
63 | }
64 |
65 |
66 | public byte[] getMD5Bytes(byte[] content) {
67 | return hash(content);
68 | }
69 |
70 |
71 | /**
72 | * 对字符串进行md5
73 | *
74 | * @param str
75 | * @return md5 byte[16]
76 | */
77 | public byte[] hash(String str) {
78 | opLock.lock();
79 | try {
80 | byte[] bt = mHasher.digest(str.getBytes(Constants.ENCODE));
81 | if (null == bt || bt.length != 16) {
82 | throw new IllegalArgumentException("md5 need");
83 | }
84 | return bt;
85 | }
86 | catch (UnsupportedEncodingException e) {
87 | throw new RuntimeException("unsupported utf-8 encoding", e);
88 | }
89 | finally {
90 | opLock.unlock();
91 | }
92 | }
93 |
94 |
95 | /**
96 | * 对二进制数据进行md5
97 | *
98 | * @param str
99 | * @return md5 byte[16]
100 | */
101 | public byte[] hash(byte[] data) {
102 | opLock.lock();
103 | try {
104 | byte[] bt = mHasher.digest(data);
105 | if (null == bt || bt.length != 16) {
106 | throw new IllegalArgumentException("md5 need");
107 | }
108 | return bt;
109 | }
110 | finally {
111 | opLock.unlock();
112 | }
113 | }
114 |
115 |
116 | /**
117 | * 将一个字节数组转化为可见的字符串
118 | *
119 | * @param bt
120 | * @return
121 | */
122 | public String bytes2string(byte[] bt) {
123 | int l = bt.length;
124 |
125 | char[] out = new char[l << 1];
126 |
127 | for (int i = 0, j = 0; i < l; i++) {
128 | out[j++] = digits[(0xF0 & bt[i]) >>> 4];
129 | out[j++] = digits[0x0F & bt[i]];
130 | }
131 |
132 | if (log.isDebugEnabled()) {
133 | log.debug("[hash]" + (new String(out)));
134 | }
135 |
136 | return new String(out);
137 | }
138 |
139 |
140 | /**
141 | * 将字符串转换为bytes
142 | *
143 | * @param str
144 | * @return byte[]
145 | */
146 | public byte[] string2bytes(String str) {
147 | if (null == str) {
148 | throw new NullPointerException("参数不能为空");
149 | }
150 | if (str.length() != 32) {
151 | throw new IllegalArgumentException("字符串长度必须是32");
152 | }
153 | byte[] data = new byte[16];
154 | char[] chs = str.toCharArray();
155 | for (int i = 0; i < 16; ++i) {
156 | int h = rDigits.get(chs[i * 2]).intValue();
157 | int l = rDigits.get(chs[i * 2 + 1]).intValue();
158 | data[i] = (byte) ((h & 0x0F) << 4 | (l & 0x0F));
159 | }
160 | return data;
161 | }
162 |
163 | }
164 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/utils/FileUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.utils;
11 |
12 | import java.io.File;
13 | import java.io.IOException;
14 | import java.io.RandomAccessFile;
15 |
16 | import com.taobao.diamond.common.Constants;
17 |
18 |
19 | public class FileUtils {
20 |
21 | public static boolean isFile(String path) {
22 | File file = new File(path);
23 | return file.isFile();
24 | }
25 |
26 |
27 | public static boolean isDirectory(String path) {
28 | File dir = new File(path);
29 | return dir.isDirectory();
30 | }
31 |
32 |
33 | public static String getFileName(String path) {
34 | File file = new File(path);
35 | if (!file.isFile()) {
36 | throw new RuntimeException("此路径表达的不是文件");
37 | }
38 | return file.getName();
39 | }
40 |
41 |
42 | public static String getParentDir(String path) {
43 | File file = new File(path);
44 | if (!file.isFile()) {
45 | throw new RuntimeException("此路径表达的不是文件");
46 | }
47 | File parent = file.getParentFile();
48 | if (parent.isDirectory()) {
49 | return parent.getName();
50 | }
51 | else {
52 | throw new RuntimeException("父目录不是目录");
53 | }
54 | }
55 |
56 |
57 | public static String getGrandpaDir(String path) {
58 | File file = new File(path);
59 | if (file.isDirectory()) {
60 | throw new RuntimeException("此路径表达的不是文件");
61 | }
62 | File parent = file.getParentFile();
63 | if (parent.isDirectory()) {
64 | File grandpa = parent.getParentFile();
65 | if (grandpa.isDirectory()) {
66 | return grandpa.getName();
67 | }
68 | else {
69 | throw new RuntimeException("祖目录不是目录");
70 | }
71 | }
72 | else {
73 | throw new RuntimeException("父目录不是目录");
74 | }
75 | }
76 |
77 |
78 | public static String getFileContent(String path) throws IOException {
79 | File tFile = new File(path);
80 | if (!tFile.isFile()) {
81 | throw new RuntimeException("不是文件");
82 | }
83 | RandomAccessFile file = new RandomAccessFile(tFile, "r");
84 | long fileSize = file.length();
85 | byte[] bytes = new byte[(int) fileSize];
86 | long readLength = 0L;
87 | while (readLength < fileSize) {
88 | int onceLength = file.read(bytes, (int) readLength, (int) (fileSize - readLength));
89 | if (onceLength > 0) {
90 | readLength += onceLength;
91 | }
92 | else {
93 | break;
94 | }
95 | }
96 | try {
97 | file.close();
98 | }
99 | catch (Exception e) {
100 |
101 | }
102 | return new String(bytes, Constants.ENCODE);
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/utils/JSONUtils.java:
--------------------------------------------------------------------------------
1 | package com.taobao.diamond.utils;
2 |
3 | import org.codehaus.jackson.map.ObjectMapper;
4 | import org.codehaus.jackson.type.TypeReference;
5 |
6 |
7 | public class JSONUtils {
8 |
9 | static ObjectMapper mapper = new ObjectMapper();
10 |
11 | public static String serializeObject(Object o) throws Exception {
12 | return mapper.writeValueAsString(o);
13 | }
14 |
15 | public static Object deserializeObject(String s, Class> clazz) throws Exception {
16 | return mapper.readValue(s, clazz);
17 | }
18 |
19 | public static Object deserializeObject(String s,TypeReference> typeReference) throws Exception {
20 | return mapper.readValue(s, typeReference);
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/utils/LoggerInit.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.utils;
11 |
12 | import java.io.File;
13 | import java.util.Enumeration;
14 | import java.util.Properties;
15 |
16 | import org.apache.commons.logging.Log;
17 | import org.apache.commons.logging.LogFactory;
18 | import org.apache.log4j.Appender;
19 | import org.apache.log4j.FileAppender;
20 | import org.apache.log4j.Logger;
21 | import org.apache.log4j.PropertyConfigurator;
22 |
23 |
24 | /**
25 | *
26 | *
27 | * logger初始化,把日志输出到应用的目录里
28 | *
29 | */
30 | public class LoggerInit {
31 | static public final String LOG_NAME_CONFIG_DATA = "DiamondConfigDataLog";
32 |
33 | static public final Log log = LogFactory.getLog(LoggerInit.class);
34 |
35 | static private volatile boolean initOK = false;
36 |
37 | static private Properties defaultProperties = new Properties();
38 | static {
39 | defaultProperties.put("log4j.logger.DiamondConfigDataLog", "info, DiamondConfigDataLogFile");
40 | defaultProperties.put("log4j.additivity.DiamondConfigDataLog", "false");
41 | defaultProperties.put("log4j.appender.DiamondConfigDataLogFile", "org.apache.log4j.DailyRollingFileAppender");
42 | defaultProperties.put("log4j.appender.DiamondConfigDataLogFile.DatePattern", "'.'yyyy-MM-dd");
43 | defaultProperties.put("log4j.appender.DiamondConfigDataLogFile.File", "diamond_config_data.log");
44 | defaultProperties.put("log4j.appender.DiamondConfigDataLogFile.layout", "org.apache.log4j.PatternLayout");
45 | defaultProperties.put("log4j.appender.DiamondConfigDataLogFile.layout.ConversionPattern",
46 | "%d{MM-dd HH:mm:ss} - %m%n");
47 | defaultProperties.put("log4j.appender.DiamondConfigDataLogFile.Append", "true");
48 | }
49 |
50 |
51 | public static void initLogFromBizLog() {
52 |
53 | if (initOK) {
54 | return;
55 | }
56 |
57 | ClassLoader cl = Thread.currentThread().getContextClassLoader();
58 | Thread.currentThread().setContextClassLoader(LoggerInit.class.getClassLoader());
59 |
60 | try {
61 | // 使缺省的配置生效(Logger, Appender)
62 | PropertyConfigurator.configure(defaultProperties);
63 |
64 | /**
65 | * 找到上层应用在Root Logger上设置的FileAppender,以及HSF配置的FileAppender。
66 | * 目的是为了让HSF的日志与上层应用的日志输出到同一个目录。
67 | */
68 | FileAppender bizFileAppender = getFileAppender(Logger.getRootLogger());
69 | if (null == bizFileAppender) {
70 | log.warn("上层业务层没有在ROOT LOGGER上设置FileAppender!!!");
71 | bizFileAppender = new FileAppender();
72 | bizFileAppender.setFile(System.getProperty("user.home") + "/diamond/logs/diamond_config_data.log");
73 | }
74 |
75 | setFileAppender(bizFileAppender, LOG_NAME_CONFIG_DATA);
76 |
77 | initOK = true;
78 | }
79 | finally {
80 | Thread.currentThread().setContextClassLoader(cl);
81 | }
82 | }
83 |
84 |
85 | private static void setFileAppender(FileAppender bizFileAppender, String logName) {
86 | FileAppender fileAppender = getFileAppender(Logger.getLogger(logName));
87 | String bizLogDir = new File(bizFileAppender.getFile()).getParent();
88 |
89 | File newLogFile = new File(bizLogDir, fileAppender.getFile());
90 |
91 | fileAppender.setFile(newLogFile.getAbsolutePath());
92 | fileAppender.activateOptions(); // 很重要,否则原有日志内容会被清空
93 | log.warn("成功为" + logName + "添加Appender. 输出路径:" + newLogFile.getAbsolutePath());
94 | }
95 |
96 |
97 | static private FileAppender getFileAppender(Logger logger) {
98 | FileAppender fileAppender = null;
99 | for (Enumeration> appenders = logger.getAllAppenders(); (null == fileAppender) && appenders.hasMoreElements();) {
100 | Appender appender = (Appender) appenders.nextElement();
101 | if (FileAppender.class.isInstance(appender)) {
102 | fileAppender = (FileAppender) appender;
103 | }
104 | }
105 | return fileAppender;
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/utils/ResourceUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.utils;
11 |
12 | import java.io.File;
13 | import java.io.IOException;
14 | import java.io.InputStream;
15 | import java.io.InputStreamReader;
16 | import java.io.Reader;
17 | import java.net.URL;
18 | import java.util.Properties;
19 |
20 |
21 | /**
22 | *
23 | * @author boyan
24 | * @date 2010-5-4
25 | */
26 | public class ResourceUtils extends Object {
27 |
28 | /** */
29 | /**
30 | * Returns the URL of the resource on the classpath
31 | *
32 | * @param resource
33 | * The resource to find
34 | * @throws IOException
35 | * If the resource cannot be found or read
36 | * @return The resource
37 | */
38 | public static URL getResourceURL(String resource) throws IOException {
39 | URL url = null;
40 | ClassLoader loader = ResourceUtils.class.getClassLoader();
41 | if (loader != null)
42 | url = loader.getResource(resource);
43 | if (url == null)
44 | url = ClassLoader.getSystemResource(resource);
45 | if (url == null)
46 | throw new IOException("Could not find resource " + resource);
47 | return url;
48 | }
49 |
50 |
51 | /** */
52 | /**
53 | * Returns the URL of the resource on the classpath
54 | *
55 | * @param loader
56 | * The classloader used to load the resource
57 | * @param resource
58 | * The resource to find
59 | * @throws IOException
60 | * If the resource cannot be found or read
61 | * @return The resource
62 | */
63 | public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
64 | URL url = null;
65 | if (loader != null)
66 | url = loader.getResource(resource);
67 | if (url == null)
68 | url = ClassLoader.getSystemResource(resource);
69 | if (url == null)
70 | throw new IOException("Could not find resource " + resource);
71 | return url;
72 | }
73 |
74 |
75 | /** */
76 | /**
77 | * Returns a resource on the classpath as a Stream object
78 | *
79 | * @param resource
80 | * The resource to find
81 | * @throws IOException
82 | * If the resource cannot be found or read
83 | * @return The resource
84 | */
85 | public static InputStream getResourceAsStream(String resource) throws IOException {
86 | InputStream in = null;
87 | ClassLoader loader = ResourceUtils.class.getClassLoader();
88 | if (loader != null)
89 | in = loader.getResourceAsStream(resource);
90 | if (in == null)
91 | in = ClassLoader.getSystemResourceAsStream(resource);
92 | if (in == null)
93 | throw new IOException("Could not find resource " + resource);
94 | return in;
95 | }
96 |
97 |
98 | /** */
99 | /**
100 | * Returns a resource on the classpath as a Stream object
101 | *
102 | * @param loader
103 | * The classloader used to load the resource
104 | * @param resource
105 | * The resource to find
106 | * @throws IOException
107 | * If the resource cannot be found or read
108 | * @return The resource
109 | */
110 | public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
111 | InputStream in = null;
112 | if (loader != null)
113 | in = loader.getResourceAsStream(resource);
114 | if (in == null)
115 | in = ClassLoader.getSystemResourceAsStream(resource);
116 | if (in == null)
117 | throw new IOException("Could not find resource " + resource);
118 | return in;
119 | }
120 |
121 |
122 | /** */
123 | /**
124 | * Returns a resource on the classpath as a Properties object
125 | *
126 | * @param resource
127 | * The resource to find
128 | * @throws IOException
129 | * If the resource cannot be found or read
130 | * @return The resource
131 | */
132 | public static Properties getResourceAsProperties(String resource) throws IOException {
133 | Properties props = new Properties();
134 | InputStream in = null;
135 | String propfile = resource;
136 | in = getResourceAsStream(propfile);
137 | props.load(in);
138 | in.close();
139 | return props;
140 | }
141 |
142 |
143 | /** */
144 | /**
145 | * Returns a resource on the classpath as a Properties object
146 | *
147 | * @param loader
148 | * The classloader used to load the resource
149 | * @param resource
150 | * The resource to find
151 | * @throws IOException
152 | * If the resource cannot be found or read
153 | * @return The resource
154 | */
155 | public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
156 | Properties props = new Properties();
157 | InputStream in = null;
158 | String propfile = resource;
159 | in = getResourceAsStream(loader, propfile);
160 | props.load(in);
161 | in.close();
162 | return props;
163 | }
164 |
165 |
166 | /** */
167 | /**
168 | * Returns a resource on the classpath as a Reader object
169 | *
170 | * @param resource
171 | * The resource to find
172 | * @throws IOException
173 | * If the resource cannot be found or read
174 | * @return The resource
175 | */
176 | public static InputStreamReader getResourceAsReader(String resource) throws IOException {
177 | return new InputStreamReader(getResourceAsStream(resource));
178 | }
179 |
180 |
181 | /** */
182 | /**
183 | * Returns a resource on the classpath as a Reader object
184 | *
185 | * @param loader
186 | * The classloader used to load the resource
187 | * @param resource
188 | * The resource to find
189 | * @throws IOException
190 | * If the resource cannot be found or read
191 | * @return The resource
192 | */
193 | public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
194 | return new InputStreamReader(getResourceAsStream(loader, resource));
195 | }
196 |
197 |
198 | /** */
199 | /**
200 | * Returns a resource on the classpath as a File object
201 | *
202 | * @param resource
203 | * The resource to find
204 | * @throws IOException
205 | * If the resource cannot be found or read
206 | * @return The resource
207 | */
208 | public static File getResourceAsFile(String resource) throws IOException {
209 | return new File(getResourceURL(resource).getFile());
210 | }
211 |
212 |
213 | /** */
214 | /**
215 | * Returns a resource on the classpath as a File object
216 | *
217 | * @param loader
218 | * The classloader used to load the resource
219 | * @param resource
220 | * The resource to find
221 | * @throws IOException
222 | * If the resource cannot be found or read
223 | * @return The resource
224 | */
225 | public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
226 | return new File(getResourceURL(loader, resource).getFile());
227 | }
228 |
229 | }
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/utils/SimpleCache.java:
--------------------------------------------------------------------------------
1 | /*
2 | * (C) 2007-2012 Alibaba Group Holding Limited.
3 | *
4 | * This program is free software; you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License version 2 as
6 | * published by the Free Software Foundation.
7 | * Authors:
8 | * leiwen , boyan
9 | */
10 | package com.taobao.diamond.utils;
11 |
12 | import java.util.concurrent.ConcurrentHashMap;
13 | import java.util.concurrent.ConcurrentMap;
14 |
15 | import com.taobao.diamond.common.Constants;
16 |
17 |
18 | /**
19 | * 一个带TTL的简单Cache,对于过期的entry没有清理
20 | *
21 | * @author fenghan
22 | *
23 | * @param
24 | */
25 | public class SimpleCache {
26 |
27 | private ConcurrentMap> cache;
28 |
29 | private long cacheTTL;
30 |
31 | private static class CacheEntry {
32 | public final long timestamp;
33 | public final E value;
34 |
35 |
36 | public CacheEntry(E value, long timestamp) {
37 | this.timestamp = timestamp;
38 | this.value = value;
39 | }
40 |
41 | }
42 |
43 |
44 | public SimpleCache() {
45 | this(Constants.POLLING_INTERVAL_TIME * 1000L);
46 | }
47 |
48 |
49 | public SimpleCache(long cacheTTL) {
50 | this.cache = new ConcurrentHashMap>();
51 | this.cacheTTL = cacheTTL;
52 | }
53 |
54 |
55 | public void put(String key, E e) {
56 | if (key == null || e == null) {
57 | return;
58 | }
59 | CacheEntry entry = new CacheEntry(e, System.currentTimeMillis() + cacheTTL);
60 | cache.put(key, entry);
61 | }
62 |
63 |
64 | public E get(String key) {
65 | E result = null;
66 | CacheEntry entry = cache.get(key);
67 | if (entry != null) {
68 | if (entry.timestamp > System.currentTimeMillis()) {
69 | result = entry.value;
70 | }
71 | }
72 |
73 | return result;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/diamond-utils/src/main/java/com/taobao/diamond/utils/TimeUtils.java:
--------------------------------------------------------------------------------
1 | package com.taobao.diamond.utils;
2 |
3 | import java.sql.Timestamp;
4 | import java.util.Date;
5 |
6 |
7 | public class TimeUtils {
8 |
9 | public static Timestamp getCurrentTime() {
10 | Date date = new Date();
11 | return new Timestamp(date.getTime());
12 | }
13 |
14 | }
15 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | 4.0.0
5 | 2010
6 | com.taobao.diamond
7 | diamond-all
8 | pom
9 | 2.0.5.4.taocode-SNAPSHOT
10 | taobao diamond v${project.version}
11 |
12 |
13 | UTF-8
14 |
15 |
16 |
17 | diamond-client
18 | diamond-sdk
19 | diamond-server
20 | diamond-utils
21 |
22 |
23 |
24 |
25 |
26 | com.atlassian.maven.plugins
27 | maven-clover2-plugin
28 |
29 | clover.license
30 | true
31 |
32 | **/notjunit/*.java
33 |
34 | true
35 | true
36 |
37 |
38 |
39 | org.apache.maven.plugins
40 | maven-eclipse-plugin
41 | 2.5.1
42 |
43 | true
44 | false
45 |
46 |
47 |
48 | org.apache.maven.plugins
49 | maven-surefire-plugin
50 | 2.3
51 |
52 | -Xms512m -Xmx1024m
53 | always
54 |
55 | **/*Test.java
56 |
57 |
58 |
59 |
60 | org.apache.maven.plugins
61 | maven-site-plugin
62 |
63 | zh_CN
64 | GBK
65 | GBK
66 |
67 |
68 |
69 |
70 | org.apache.maven.plugins
71 | maven-release-plugin
72 | 2.0-beta-9
73 |
74 | http://www.xx.com/repos/diamond/tags
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | ${pom.groupId}
85 | diamond-client
86 | ${project.version}
87 |
88 |
89 | ${pom.groupId}
90 | diamond-utils
91 | ${project.version}
92 |
93 |
94 | javax.servlet
95 | servlet-api
96 | 2.5
97 | provided
98 |
99 |
100 | jstl
101 | jstl
102 | 1.1.2
103 |
104 |
105 | taglibs
106 | standard
107 | 1.1.2
108 |
109 |
110 | org.springframework
111 | spring-jdbc
112 | 3.1.1.RELEASE
113 |
114 |
115 | org.springframework
116 | spring-webmvc
117 | 3.1.1.RELEASE
118 |
119 |
120 |
121 | mysql
122 | mysql-connector-java
123 | 5.1.5
124 |
125 |
126 |
127 | log4j
128 | log4j
129 | 1.2.14
130 |
131 |
132 | commons-logging
133 | commons-logging
134 | 1.1
135 |
136 |
137 | commons-httpclient
138 | commons-httpclient
139 | 3.1
140 |
141 |
142 | commons-dbcp
143 | commons-dbcp
144 | 1.2.2
145 |
146 |
147 | commons-io
148 | commons-io
149 | 1.4
150 |
151 |
152 | commons-lang
153 | commons-lang
154 | 2.6
155 |
156 |
157 |
158 | org.codehaus.jackson
159 | jackson-core-lgpl
160 | 1.4.0
161 |
162 |
163 | org.codehaus.jackson
164 | jackson-mapper-lgpl
165 | 1.4.0
166 |
167 |
168 |
169 | junit
170 | junit
171 | 4.4
172 | test
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 | org.apache.maven.plugins
181 | maven-javadoc-plugin
182 | 2.5
183 |
184 | GBK
185 | GBK
186 |
187 |
188 |
189 |
190 | javadoc
191 |
192 |
193 |
194 |
195 |
196 |
197 | org.apache.maven.plugins
198 | maven-surefire-report-plugin
199 | 2.4.2
200 |
201 |
202 | org.apache.maven.plugins
203 | maven-checkstyle-plugin
204 | 2.3
205 |
206 | checkstyle.xml
207 |
208 |
209 |
210 | org.apache.maven.plugins
211 | maven-clover-plugin
212 |
213 | clover.license
214 | true
215 | true
216 | true
217 |
218 |
219 |
220 | org.apache.maven.plugins
221 | maven-pmd-plugin
222 |
223 | true
224 | 1.6
225 |
226 |
227 |
228 | org.codehaus.mojo
229 | findbugs-maven-plugin
230 | 2.0.1
231 |
232 | true
233 | true
234 | true
235 |
236 |
237 |
238 | maven-compiler-plugin
239 |
240 | 1.7
241 | 1.7
242 | UTF-8
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 |
--------------------------------------------------------------------------------