`
sungang_1120
  • 浏览: 310170 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
收藏列表
标题 标签 来源
mongodb GridFS java Apis mongo
package examples.mongodb.crud;

import java.io.File;
import java.io.IOException;

import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

public class MongoDBBinaryExample 
{
	public static void main(String[] args) throws IOException 
	{
		MongoClient mongo = new MongoClient("localhost", 27017);
		DB db = mongo.getDB("howtodoinjava");
		//Save a image in DB
		saveImageIntoMongoDB(db);
		//Get a image from DB
		getSingleImageExample(db);
		//Get all images from DB
		listAllImages(db);
		saveToFileSystem(db);		
		//Delete images from DB
		deleteImageFromMongoDB(db);
		
		//Verifying if image was deleted or not
		getSingleImageExample(db);
	}
	
	private static void saveImageIntoMongoDB(DB db) throws IOException {
		String dbFileName = "DemoImage";
		File imageFile = new File("c:\\DemoImage.png");
		GridFS gfsPhoto = new GridFS(db, "photo");
		GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
		gfsFile.setFilename(dbFileName);
		gfsFile.save();
	}
	
	private static void getSingleImageExample(DB db) {
		String newFileName = "c:/DemoImage";
		GridFS gfsPhoto = new GridFS(db, "photo");
		GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
		System.out.println(imageForOutput);
	}

	
	private static void listAllImages(DB db) {
		GridFS gfsPhoto = new GridFS(db, "photo");
		DBCursor cursor = gfsPhoto.getFileList();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}
	
	private static void saveToFileSystem(DB db) throws IOException {
		String dbFileName = "DemoImage";
		GridFS gfsPhoto = new GridFS(db, "photo");
		GridFSDBFile imageForOutput = gfsPhoto.findOne(dbFileName);
		imageForOutput.writeTo("c:/DemoImageNew.png");
	}
	
	private static void deleteImageFromMongoDB(DB db) {
		String dbFileName = "DemoImage";
		GridFS gfsPhoto = new GridFS(db, "photo");
		gfsPhoto.remove(gfsPhoto.findOne(dbFileName));
	}
}


Output:

{ "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" :  null  , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" :  null }
{ "_id" : { "$oid" : "53cff8d736414e8af4a4f0b8"} , "chunkSize" : 262144 , "length" : 138855 , "md5" : "b75f77c16c3ac6472365c06cde15d0da" , "filename" : "DemoImage" , "contentType" :  null  , "uploadDate" : { "$date" : "2014-07-23T18:03:03.403Z"} , "aliases" :  null }

null
算法数据结构资源 java
https://www.cs.usfca.edu/~galles/visualization/Algorithms.html
http://visualgo.net/


//codeforces
http://codeforces.com/

//数据结构
http://www.jisuanke.com/course

//郝斌数据结构视频
http://down.51cto.com/zt/306

//网易公开课  机器学习视频
http://open.163.com/special/opencourse/machinelearning.html
云架构技术
//openstack 查询监控数据
https://metering.az1.dc1.domainname.com:443/v2/resources?q.field=metadata.instance_id&q.value=4ff0c49a-a8a7-44d7-a13e-90fcb1f8b958

//查询主机监控
https://metering.az1.dc1.domainname.com:443/v2/resources?q.field=resource_id&q.value=12CD57A0-09A1-11E5-A141-5A0FFB3EA27C

移动app资源
http://bbs.deviceone.net/forum.php?mod=viewthread&tid=222&extra=page%3D1


//工具:

React Native
Device one

ionic+angular+phonegap开发APP入门


http://wex5.com/cn/doc/

//腾讯开源UI
http://frozenui.github.io/


//React Native DOC
http://wiki.jikexueyuan.com/project/react-native/homepage.html
http://reactnative.cn/docs/getting-started.html#content


http://reactnative.cn/

spring 相关技术
//SpringSide学习资料合集(教程+视频+Jar包)
http://down.51cto.com/zt/1953
学习视频url java
//Python网络爬虫实战-Scrapy(已完结)
http://www.maiziedu.com/course/python/458-7430/

//Mongodb最佳实践(已完结)
http://www.maiziedu.com/course/php/395-4445/
//HTML5+CSS3快速入门(已完结)
http://www.maiziedu.com/course/web/228-2627/
//scala教程
http://www.maiziedu.com/course/others/521-7132/


//高等数学
http://video.1kejian.com/video/?12395-0-0.html
gitbooks url java
**************************规范约定*******************************
//git books
https://www.gitbook.com/explore
//kancloud
http://www.kancloud.cn/explore

https://www.gitbook.com/book/wastemobile/gitbook-chinese/details //GitBook 中文解說 - 2.4

https://www.gitbook.com/book/jervyshi/google-java-styleguide-zh/details //Google JAVA编程规范

**************************JAVA*******************************

https://www.gitbook.com/book/askingwindy/gitbook-java-interview-note/details  //Java面试准备
http://www.admin10000.com/document/6919.html //Java面试准备


http://www.kancloud.cn/kancloud/the-art-of-programming //编程之法:面试和算法心得

https://waylau.gitbooks.io/jersey-2-user-guide/content/ //Jersey 2.x 用户指南

https://qbgbook.gitbooks.io/spring-boot-reference-guide-zh/content/ //Spring Boot参考指南

https://www.gitbook.com/book/kimmking/springbatchreference/details //Spring Batch参考文档中文版

https://www.gitbook.com/book/czeng/spring-data/details //Spring Data 中文版本

https://www.gitbook.com/book/waylau/apache-shiro-1-2-x-reference/details //Shiro User Guide中文翻译

**************************Python******************************
//python 学习
http://www.kancloud.cn/kancloud/python3-cookbook/


**************************前端类*******************************

https://checkcheckzz.gitbooks.io/angularjs-learning-notes/content/ //AngularJS学习笔记
//2015年50+ JavaScript 工具、资源合集
http://www.kancloud.cn/kancloud/javascript-resources-2015

**************************工具类*******************************

https://dongchuan.gitbooks.io/gradle-user-guide-/content/ //Gradle User Guide 中文版

**************************NO sql*******************************

https://kelby.gitbooks.io/rails-beginner-s-guide/content/ //Rails 4-2-stable 参考手册(Beta)

*************************运维********************************

https://www.gitbook.com/book/kisspuppet/puppet/details //Puppet运维实战

*************************大数据********************************

ELKstack 中文指南
https://www.gitbook.com/book/chenryn/kibana-guide-cn/details

************************* MQ ********************************

http://geewu.gitbooks.io/rabbitmq-quick/content/index.html//rabbitMQ 快速上手文档 

************************* 网络编程 ********************************

https://www.gitbook.com/book/waylau/apache-mina-2-user-guide/details //MINA User Guide中文翻译

http://www.kancloud.cn/kancloud/essential-netty-in-action //Essential Netty in Action 《Netty 实战(精髓)》

*************************云计算*******************************

https://yeasy.gitbooks.io/docker_practice/content/ //Docker —— 从入门到实践
https://joshhu.gitbooks.io/docker_theory_install/content/ //最完整的Docker聖經 - Docker原理圖解及全環境安裝


************************查询*********************************
http://es.xiaoleilu.com/ //Elasticsearch 权威指南(中文版)
//Spring-data-elasticsearch
http://es.yemengying.com/ 

*************************第三方*******************************

https://www.gitbook.com/book/wohugb/alipay-direct/details //支付宝即时到账交易接口
一些不错的资源URL
//**************************************Git***************************
//手把手教你如何加入到github的开源世界
http://www.cnblogs.com/wenber/p/3630921.html

//**************************************最代码***************************
//java积累的一些代码重构方法与示例代码分享
http://www.zuidaima.com/share/2167696549661696.htm
//Apache Shiro+SpringMVC+Hibernate Search+Hibernate+Bootstrap企业信息管理系统
http://www.zuidaima.com/share/1764524204903424.htm


//**************************************Git**************************
//jersey MVC bean 验证
http://blog.dejavu.sk/2014/01/28/handling-jax-rs-and-bean-validation-errors-with-mvc/
https://github.com/jersey/jersey/tree/master/examples/shortener-webapp


//小微OA系统使用说明
http://www.kancloud.cn/xiaowei/user_guide

//各种系统 软件 工具安装教程
http://www.server-world.info/en/

//颜色调式器
http://tool.c7sky.com/webcolor/

//开源项目导航
http://www.oschina.net/company



//算法
http://www.jisuanke.com/
http://codeforces.com/
http://acm.hdu.edu.cn/

//apache 开源源码下载
https://apache.googlesource.com/?format=HTML


//比较详细的log4j教程
http://www.codeceo.com/article/log4j-usage.html


//Code forge
http://www.codeforge.cn/

//CDH下载
http://archive-primary.cloudera.com/cm5/cm/5/
Windows安装Mongo mongo
1.解压mongodb-win32-i386-1.8.1.zip ,创建路径C:\Program Files\mongodb ,将解压后的Bin文件Copy to 此文件夹下

2.C:\Program Files\mongodb 下建立data,logs文件夹 然后在data下建立db文件夹,在logs下面创建MongoDB.log文件,
至此mongodb下有以下文件夹:
C:\Program Files\mongodb\bin
C:\Program Files\mongodb\data\db
C:\Program Files\mongodb\logs\MongoDB.log

//启动
mongod -dbpath "C:\Program Files\data\db"

//然后进入bin
双击mongo.exe 即可操作

mongod -dbpath "C:\Program Files\data\db"  --auth --httpinterface --rest
//安装windows 服务
mongod --dbpath "C:\Program Files\data\db" --logpath "C:\Program Files\logs\MongoDB.log" --auth --rest --httpinterface --install --serviceName "MongoDB"
//删除 windows 服务
mongod --dbpath  --remove --serviceName "MongoDB"

//用户权限问题
MongoDB的用户分为两种,一种是admin用户,另一种是特定数据库用户。admin用户拥有最高的权限,而特定数据库用户则只能访问特定的数据库。当MongoDB的admin库里没有任何用户的时候,也就是说整个MongoDB没有一个MongoDB用户的时候,即便–auth权限需求打开了,用户还是可以通过localhost界面进入MongoDB进行用户设置,否则的话整个MongoDB就完全没法访问了。而当这个用户创建完成之后,之后的用户登录和操作就需要授权了,不是直接登录就能使用的了

use admin
db.addUser('root','root')

//重启服务
//--auth  加上认证 --httpinterface web监控28017 --rest
mongod -dbpath "C:\Program Files\data\db"  --auth --httpinterface --rest

//下次就需要认证后才可以操作
db.auth("root", "root")
不错在线URL地址 java
//各种技术经验总结
https://github.com/lyfeyaj/awesome-resources#web-%E5%89%8D%E7%AB%AF
//infoQ
http://www.infoq.com/cn/rest-deep-dive
//jquery之家
http://www.htmleaf.com/jQuery/
//国外java 网站
http://www.javacodegeeks.com/


//架构
http://www.aboutyun.com/thread-12095-1-1.html
//互联网公司技术架构资料:淘宝、百度、腾讯、新浪、京东资料汇总
https://github.com/Qihoo360/Atlas/blob/master/README_ZH.md//360 MySQL中间层 Atlas



//云计算 & 虚拟化 & 大数据
//openstack版本下载
https://wiki.openstack.org/wiki/Releases
//IBM Opecstack安装介绍
https://www.ibm.com/developerworks/community/blogs/5144904d-5d75-45ed-9d2b-cf1754ee936a/entry/deploy_openstack_with_packstack?lang=en
//学习linux网站
http://bbs.hh010.com/
//docker
http://yuedu.baidu.com/ebook/d817967416fc700abb68fca1?fr=aladdin&key=docker###//入门教程
http://www.aboutyun.com/forum.php//about 云

http://archive.ics.uci.edu/ml/datasets.html//hadoop 离线日志分析数据格式
http://hadooptutorial.info/category/hadoop/  //hadoop 国外学习网站
http://www.iteblog.com/ //大数据学习网站

//Spark Streaming Examples
https://github.com/apache/spark/tree/master/examples/src/main/java/org/apache/spark/examples
https://github.com/apache/spark/tree/master/examples/src/main/java/org/apache/spark/examples/streaming


//hadoop 下载地址
http://apache.fayea.com/hadoop/common/
//hadoop 大数据集测试数据
http://archive.ics.uci.edu/ml/datasets.html
//hbase中文文档
http://yankaycom-wordpress.stor.sinaapp.com/hbase/book.html?q=/wp-content/hbase/book.html
//Hadoop Shell命令
http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_shell.html

Spring框架参考文档 翻译
文档地址
中文文档:http://spring.oschina.mopaas.com/
https://github.com/waylau/spring-framework-4-reference/blob/master/SUMMARY.md
http://waylau.gitbooks.io/spring-framework-4-reference/content/index.html
英文文档:http://spring.oschina.mopaas.com/html_en/
http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#overview-maven-bom
//spring hadoop
http://docs.spring.io/spring-hadoop/docs/current/reference/html/
//Spring Boot
http://afoo.me/posts/2015-07-09-how-spring-boot-works.html



//JAVA学习框架 和 前端技术
http://www.ideagrace.com/sf/containers/  
//Amdatu是一组开源组件和工具在Java构建模块化应用程序。
http://amdatu.org/
https://github.com/waylau/netty-4-user-guide/blob/master/SUMMARY.md//netty-4-user-guide
//jquery 插件库
http://www.jq22.com/
http://www.pintuer.com/  //pintuer
//前端开发利器 - Emmet 
http://www.gbtags.com/gb/gbliblist/3.htm

//apiCloud
http://www.apicloud.com/
http://docs.apicloud.com/APICloud/videos-and-codes
//AUI for apiCloud
http://www.kancloud.cn/liulangnan/aui


//翻墙
https://hosts.huhamhire.com/
http://ssnode.com/

https://www.zybuluo.com/mdeditor//md 编辑器在线
https://stackedit.io/editor


//工具 博客类
http://www.taobaotest.com/ //淘宝test
http://geewu.gitbooks.io/rabbitmq-quick/content/index.html//rabbitMQ 快速上手文档

http://www.java2s.com/Open-Source/Java_Free_Code/index.htm //Java Free Code


//百度云
16套游戏开发+项目实战链接: http://pan.baidu.com/s/1sjA146L 密码: akpp
IOS12月最新就业班链接: http://pan.baidu.com/s/1hqepfbm 密码: bxe9
IOS5期链接: http://pan.baidu.com/s/1mgiMepi 密码: farg
IOS4期链接: http://pan.baidu.com/s/1qWC4FJe 密码: zjs7

黑马7天hadoop链接: http://pan.baidu.com/s/1pJKD48b 密码: x7n3


//UI
http://my.chinaz.com/accounts/login.html//站长之家
http://www.sitestar.cn/default.aspx//建站之星

//运维博客
http://azhuang.blog.51cto.com/ //状大神

//小甲鱼bbs python
http://bbs.fishc.com/

//nginx 学习
http://openresty.org/download/agentzh-nginx-tutorials-zhcn.html
//开源的网站访问统计系统
http://www.piwik.cn/
linux rabbitmq高可靠集群配置 java
linux 安装rabbitmq java
//linux 安装rabbitmq
//  http://www.rabbitmq.com/releases/rabbitmq-server/ 下载mq地址

//****************首先需要安装mq运行环境erlang******************************
//可参照:http://amornio.iteye.com/blog/1551502
//1:下载erlang安装包 和  依赖
wget http://www.erlang.org/download/otp_src_R15B01.tar.gz

//2解压:
tar -zxvf otp_src_R16B03-1.tar.gz
//3编译安装:
/configure --prefix=/usr/local/servers/erlang

如果本步骤出现
error: no acceptable C compiler found in $PATH
说明你没有安装gcc编译器,去安装gcc编译器
//1,
yum -y install gcc

//然后在执行:配置安装环境
/configure --prefix=/usr/local/install_file/erlang

错误:
configure: error: Perl is required to generate v2 to v1 mib converter script
configure: error: /bin/sh '/usr/local/install_package/rabbitmq/otp_src_17.4b/snmp/./configure' failed for snmp/.
configure: error: /bin/sh '/usr/local/install_package/rabbitmq/otp_src_17.4b/configure' failed for lib


解决:
yum -y install perl


错误:
configure: error: No curses library functions found
configure: error: /bin/sh '/usr/local/install_package/rabbitmq/otp_src_17.4/erts/configure' failed for erts

解决:
yum -y install ncurses-devel

执行编译命令:make
执行安装:make install

//环境变量
ERL_HOME=/usr/local/install_file/erlang
PATH=$ERL_HOME/bin:$PATH
export ERL_HOME PATH


//****************安装mq*****************************
// 依赖包xmlto
yum install xmlto
//参考 http://blog.csdn.net/sonnet123/article/details/9188429

wget http://www.rabbitmq.com/releases/rabbitmq-server/v3.4.3/rabbitmq-server-3.4.3-1.noarch.rpm  
//不同版本自己可以修改下就可以了

rpm -ivh  --nodeps  rabbitmq-server-3.4.3-1.noarch.rpm
//这样就安装成功了

//使用 -detached 参数运行各节点

rabbitmqctl stop
rabbitmq-server -detached

//启动web监控功能
rabbitmq-plugins enable rabbitmq_management  

//重启MQ

//访问 IP:15672
//登录如果要是用默认的guest  (远程不能使用需要设置)

//修改安装目录下面ebin下的rabbit.app文件  {loopback_users,[<<guest>>]} 吧guest去了 重启MQ就可以了
hessian序列化工具类 hessian,java
package com.ghca.easyview.server.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


import org.apache.log4j.Logger;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
/**
 * 通过Hessian进行序列化对象
 * @author xiaoshuang
 * @Date   2014-10-23
 *
 */
public class ObjectCodec {
	
	private static final Logger logger = Logger.getLogger(ObjectCodec.class);
	
	/**
	 * 将对象转换成byte数组
	 * @param obj
	 * @return
	 * @throws IOException
	 */
	public static byte[] serialize(Object obj) throws IOException {
		ByteArrayOutputStream baos = null;
		HessianOutput output = null;
		try {
			baos = new ByteArrayOutputStream(1024);
			output = new HessianOutput(baos);
			output.startCall();
			output.writeObject(obj);
			output.completeCall();
		} catch (final IOException ex) {
			throw ex;
		} finally {
			if (output != null) {
				try {
					baos.close();
				} catch (final IOException ex) {
					logger.error("Failed to close stream.", ex);
				}
			}
		}
		return baos != null ? baos.toByteArray() : null;
	}
	
	/**
	 * 将byte数组转换为对象
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static Object deSerialize(byte[] in) throws IOException {
		Object obj = null;
		ByteArrayInputStream bais = null;
		HessianInput input = null;
		try {
			bais = new ByteArrayInputStream(in);
			input = new HessianInput(bais);
			input.startReply();
			obj = input.readObject();
			input.completeReply();
		} catch (final IOException ex) {
			throw ex;
		} catch (final Throwable e) {
			logger.error("Failed to decode object.", e);
		} finally {
			if (input != null) {
				try {
					bais.close();
				} catch (final IOException ex) {
					logger.error("Failed to close stream.", ex);
                }
            }
        }
        return obj;
	}
}
一些好用工具 及其 开源框架 java
//******************************************项目管理***************************************
653363623
Redmine
JIRA
todolist
project(适合小团队)
xmind freemind mindmanager(思维导图软件)
Trac(适合小团队)
禅道(bug管理)

//***************************************运维、监控类*******************************************
Hyperic HQ//监控
zabbix//监控
Nagios//是一款开源的免费网络监视工具
Keepalived//Keepalived的作用是检测web服务器的状态
drbd+heartbeat//
squid  //前端缓存框架

//******************************************工具类***************************************
teamcCity//持续集成工具
upsource//svn 代码仓库浏览器和代码审查工具
SonarQube//代码质量管理平台

gitblit//git web管理工具
SmartGit//git 版本控制管理工具

//************************************报表*******************************************
//前端
http://www.hcharts.cn/index.php //Highcharts
functioncharts //不开源 有收费 支持一些不收费

//****************************************分布式架构***********************************************
snappy//google公司内部广泛使用的一种压缩技术 google开源
hessian//一种更加高效的序列化和反序列化技术

//****************************************大数据架构***********************************************
Cloudera Manager
CDH5
Ansible
//CDH5的Ansible配置
https://github.com/mcsrainbow/ansible-playbooks-cdh5

//hadoop2.x项目组相关
HDFS MapReduce yarn Hive Pig Mathout Hbase Zookeeper Sqoop Flume Oozie impala hue Sentry 

//hbase tool
apache phoenix drill

//Hue 配置
http://gethue.com/how-to-configure-hue-in-your-hadoop-cluster/
http://cloudera.github.io/hue/docs-3.6.0/manual.html#_the_hue_database

//cdh下载
http://archive.cloudera.com/cm5/installer/
http://archive.cloudera.com/cm5/redhat/6/x86_64/cm/

//hadoop安装部署 工具
//开源的
HDP,
CDH // http://archive.cloudera.com/cdh5/cdh/5/
Apche Knox Gateway //hadoop安全
apache accumulo


//******************************************框架类***************************************
Apache Avro 与 Thrift //基于二进制的高性能的通讯中间件. 它们都提供了数据序列化的功能和RPC服务
rabbitmq //分布式系统消息中间件
Disruptor//是一个高性能的异步处理框架,或者可以认为是最快的消息框架(轻量的JMS)
Kafka//分布式消息队列
CuratorFramework //一个队zookeeper封装client与server通信框架
Mule//是一个企业服务总线(ESB)消息框架.它的主要特性包括:

Cobar介绍及配置//alibaba mysql集群工具
TProfiler//alibaba  TProfiler是一个可以在生产环境长期使用的性能分析工具
Akka //编写高并发框架
Disruptor//
Jactors//

//***********************************好用的第三方jar***************************************
//时间插件
joda-time

//***********************************JAVA 并发***************************************
JActor  //Actor模式的Java实现 
Kilim //是一个Java的actor框架

//***********************************加密算法***************************************
MD5/SHA1/SHA256,或者MD5withRSA、SHA1withRSA、SHA256withRSA


//***********************************IM***************************************
Tigase XMPP

Comet4J
mysql 根据当前坐标 范围计算附近 java
SELECT
	t.id,
	t.store_name,
	t.logo_url,
	t.store_address,
	t.store_phone,
	t.x_point AS lon,
	t.y_point AS lat,
	sqrt(((
				(104.071127- t.x_point) * PI() * 12656 * cos(
					((30.577438 + t.y_point) / 2) * PI() / 180
				) / 180
			) * (
				(104.071127 - t.x_point) * PI() * 12656 * cos(
					((30.577438 + t.y_point) / 2) * PI() / 180
				) / 180
			)
		) + (
			(
				(30.577438 - t.y_point) * PI() * 12656 / 180
			) * (
				(30.577438 - t.y_point) * PI() * 12656 / 180
			)
		)
	) AS distance
FROM
	t_store AS t
GROUP BY distance 
HAVING distance <= 3
ORDER BY distance ASC 
LIMIT 20




public List<Map<String, Object>> getNearStore(String lon, String lat, String scope,Integer count) {
		ArrayList<Object> params = Lists.newArrayList();
		StringBuffer sql = new StringBuffer();
//		sql.append(" select t.id,t.store_name,t.logo_url,t.store_address,t.store_phone,t.x_point AS lon,t.y_point AS lat, ");
//		sql.append(" (POWER(MOD (ABS(t.x_point - " + lon + "), 360),2) +");
//		sql.append(" POWER(ABS(t.y_point - " + lat + "), 2");
//		sql.append(" )) as distance");
//		sql.append(" from t_store as t");
//		sql.append(" GROUP BY distance HAVING distance <= " + scope + "");
//		sql.append(" ORDER BY distance ASC LIMIT " + count);
		sql.append("SELECT");
		sql.append(" t.id,t.store_name,t.logo_url,t.store_address,t.store_phone,");
		sql.append(" t.x_point AS lon,t.y_point AS lat,");
		sql.append(" sqrt( ");
		sql.append(" (");
		sql.append(" ( ("+lon+" - t.x_point) * PI() * 12656 * cos(");
		sql.append(" ( ("+lat+" + t.y_point) / 2) * PI() / 180");
		sql.append(" ) / 180 )");
		sql.append(" *");
		sql.append(" (("+lon+" - t.x_point) * PI() * 12656 * cos(");
		sql.append(" (("+lat+" + t.y_point) / 2) * PI() / 180");
		sql.append(" ) / 180)");
		sql.append(" )");
		sql.append(" + ");
		sql.append(" (");
		sql.append(" (("+lat+" - t.y_point) * PI() * 12656 / 180 ) ");
		sql.append(" *");
		sql.append(" (("+lat+" - t.y_point) * PI() * 12656 / 180 )");
		sql.append(" )");
		sql.append(" ) AS distance");
		sql.append(" FROM");
		sql.append(" t_store AS t");
		sql.append(" GROUP BY distance ");
		sql.append(" HAVING distance <= "+scope+"");
		sql.append(" ORDER BY distance ASC ");
		sql.append(" LIMIT "+count+"");
		LogUtils.logInfo("查询附近店铺SQL:" + sql.toString());
		return findByJDBCSql(sql.toString(), params);
	}
SVN 账号 权限分配 java
### This file is an example authorization file for svnserve.
### Its format is identical to that of mod_authz_svn authorization
### files.
### As shown below each section defines authorizations for the path and
### (optional) repository specified by the section name.
### The authorizations follow. An authorization line can refer to:
###  - a single user,
###  - a group of users defined in a special [groups] section,
###  - an alias defined in a special [aliases] section,
###  - all authenticated users, using the '$authenticated' token,
###  - only anonymous users, using the '$anonymous' token,
###  - anyone, using the '*' wildcard.
###
### A match can be inverted by prefixing the rule with '~'. Rules can
### grant read ('r') access, read-write ('rw') access, or no access
### ('').

[aliases]

[groups]
admin_worker = sung,caogw,yangt,xuqs,jinx
android_worker = yangck,zhouq
ios_worker = lim,yuch
design_worker = hetx

#SVN根目录的权限
[/]
@android_worker = rw
@admin_worker = rw
@ios_worker = rw
@design_worker = rw
xtt = rw
* = r

[tiger:/]
@android_worker = rw
@admin_worker = rw
@ios_worker = rw
@design_worker = rw
xtt = rw
* = r

[tiger:/web]
@admin_worker = rw
* = 
[tiger:/web/code]
@admin_worker = rw
* = 

[tiger:/web/store]
@admin_worker = rw
xtt = rw
* = 

[tiger:/android/code]
@android_worker = rw
@admin_worker = rw
* = 

[tiger:/ios/code]
@ios_worker = rw
@admin_worker = rw
* = 

[tiger:/design]
@admin_worker = rw
@android_worker = rw
@ios_worker = rw
@design_worker = rw
* = r

[tiger:/doc]
@admin_worker = rw
@android_worker = rw
@ios_worker = rw
@design_worker = rw
* = r

[tiger:/temp]
* = rw

[tiger:/sport]
@admin_worker = rw
@android_worker = rw
@ios_worker = rw
@design_worker = rw
* = r
ZK CRUD
var setting = {
		
		async: {
            enable: true,
            url:GetBasePath()+ "/LoadZKNodeList",
            dataFilter: null
        },
		view: {
			addHoverDom: addHoverDom,//当用户鼠标移动到节点上时,显示用户自定义控件,显示隐藏状态同zTree内部的编辑,删除按钮
			removeHoverDom: removeHoverDom//移出节点时,显示隐藏状态同zTree内部的编辑、删除按钮
		},
		data: {
			simpleData: {
				enable: true
			}
		}
	};

//鼠标在节点获取焦点显示添加按钮
function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0){
		return;
	}
	if (treeNode.editNameFlag || $("#delBtn_"+treeNode.tId).length>0){
		return;
	}
	if (treeNode.editNameFlag || $("#updBtn_"+treeNode.tId).length>0){
		return;
	} 
	//删除
	if(treeNode.showDeleteBut){
		var parentPath = getParentNode(treeNode);
		alert(parentPath);
		var delStr = "<span class='' id='delBtn_" + treeNode.tId
		+ "' title='删除' style='color:red;' onclick='deleteNode(\""+parentPath+"\")'>删除</span>";
		sObj.after(delStr);
	}
	//修改
	if(treeNode.showUpdateBut){
		var parentPath = getParentNode(treeNode);
		var updStr = "<span class='' id='updBtn_" + treeNode.tId
		+ "' title='修改' style='color:red;' onclick='updateNode(\""+parentPath+"\")'>修改</span>";
		sObj.after(updStr);
	}
	//修改
	if(treeNode.showInsertBut){
		var parentPath = getParentNode(treeNode,0);
		var updStr = "<span class='' id='updBtn_" + treeNode.tId
		+ "' title='添加' style='color:red;' onclick='addNode(\""+parentPath+"\")'>添加</span>";
		sObj.after(updStr);
	}
};
	
//隐藏按钮
function removeHoverDom(treeId, treeNode) {
	$("#addBtn_"+treeNode.tId).unbind().remove();
	$("#updBtn_"+treeNode.tId).unbind().remove();
	$("#delBtn_"+treeNode.tId).unbind().remove();
};

//添加
function addNode(parentPath){
	alert("add : " + parentPath);
}
//修改
function updateNode(parentPath){
	alert("upd : " + parentPath);
}
//删除
function deleteNode(parentPath){
	alert("del : " + parentPath);
}

$(document).ready(function(){
	//加载树结构数据
	$.fn.zTree.init($("#treeDemo"), setting);
});

var parentPath = "";
var currentNodeName = "";
function getParentNode(treeNode,i){
	if(i == 0){
		parentPath = "";
		currentNodeName = "";
		currentNodeName = treeNode.name;
	}
	var pNode  = treeNode.getParentNode();
	var parentPathTemp = "";
	if(null != pNode){
		i++;
		parentPathTemp = pNode.name;
		parentPath = parentPathTemp + "/" +parentPath;
		getParentNode(pNode);
	}
	//根节点
	if(parentPath == ""){
		return currentNodeName;
	}
	return parentPath + currentNodeName;
}



div style="padding-left: 100px;padding-top: 10px;color:red;text-indent: 10px;">ZK NODE LIST DATA</div>
	<div class="zTreeDemoBackground left" style="padding-left: 100px;padding-top: 50px;">
		<ul id="treeDemo" class="ztree"></ul>
	</div>
Maven 使用 Nexus 私服配置 maven
首先 可以配置全局的 Setting.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user, 
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in 
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
   <localRepository>D:\mavenRepo</localRepository>
  -->
  

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     | 
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are 
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
    
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
	
	  <server>  
		<id>nexus-releases</id>  
		<username>admin</username>  
		<password>admin123</password>  
	  </server>  
	  <server>  
		<id>nexus-snapshots</id>  
		<username>admin</username>  
		<password>admin123</password>  
	  </server>    
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   | 
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred 
   | server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
	 <mirror>
         <id>nexus</id>  
         <mirrorOf>*</mirrorOf>  
         <name>Nexus Mirror</name>  
         <url>http://10.143.132.150:16518/nexus/content/groups/public/</url>  
     </mirror>  
  </mirrors>
  
  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is 
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a 
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |   
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
		<!--Nexus centent repo -->
		<profile>  
		<id>nexus</id>  
		<repositories>  
		  <repository>  
			<id>local-nexus</id>  
			<url>http://10.143.132.150:16518/nexus/content/groups/public/</url>  
			<releases>  
			  <enabled>true</enabled>  
			</releases>  
			<snapshots>  
			  <enabled>true</enabled>  
			</snapshots>  
		  </repository>  
		</repositories>  
	  </profile>    
  </profiles>

  
  <activeProfiles>  
     <activeProfile>nexus</activeProfile>  
  </activeProfiles>  
  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>






// ==================pom.xml=====================

<!-- 配置 发布的版本位置 -->
	<distributionManagement>
		<repository>
			<id>nexus-releases</id>
			<name>Nexus Release Repository</name>
			<url>http://10.143.132.150:16518/nexus/content/repositories/releases/</url>
		</repository>
		<snapshotRepository>
			<id>nexus-snapshots</id>
			<name>Nexus Snapshot Repository</name>
			<url>http://10.143.132.150:16518/nexus/content/repositories/snapshots/</url>
		</snapshotRepository>
	</distributionManagement>
java logback手动加载配置文件 java
public static void main(String[] args) {
		LogUtils.logInfo("start dbMidddleware project...");
		try {
			LogBackConfigLoader.load("conf/logback.xml");
		} catch (Exception e) {
			e.printStackTrace();
		}
}




package com.gukq.dbMidddleware;

import java.io.File;
import java.io.IOException;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;

public class LogBackConfigLoader {
	public static void load(String externalConfigFileLocation)
			throws IOException, JoranException {
		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

		File externalConfigFile = new File(externalConfigFileLocation);
		if (!externalConfigFile.exists()) {
			throw new IOException(
					"Logback External Config File Parameter does not reference a file that exists");
		} else {
			if (!externalConfigFile.isFile()) {
				throw new IOException(
						"Logback External Config File Parameter exists, but does not reference a file");
			} else {
				if (!externalConfigFile.canRead()) {
					throw new IOException(
							"Logback External Config File exists and is a file, but cannot be read.");
				} else {
					JoranConfigurator configurator = new JoranConfigurator();
					configurator.setContext(lc);
					lc.reset();
					configurator.doConfigure(externalConfigFileLocation);
					StatusPrinter.printInCaseOfErrorsOrWarnings(lc);
				}
			}
		}
	}
}
解决Eclipse中 使用Maven 中executions 节点报错问题,
//直接在build中 添加这个,其中有个 1.3 是你根据 你的错误提示,看看说的是什么
//错误如下:有个1.3
//Plugin execution not covered by lifecycle configuration: org.apache.maven.plugins:maven-antrun-//plugin:1.3:run (execution: generate-sources, phase: generate-sources)



<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings 
					only. It has no influence on the Maven build itself. -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>org.apache.maven.plugins</groupId>
										<artifactId>maven-antrun-plugin</artifactId>
										<versionRange>[1.3,)</versionRange>
										<goals>
											<goal>run</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore />
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
java 创建 和 读取 zookeeper 节点 zookeeper
package zookeeper.study1;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class SetConfig {

	public static String url = "192.168.1.101:2181";
	private final static String root = "/myConf";
	private final static String urlNode = root + "/url";
	private final static String userNameNode = root + "/userName";
	private final static String passwordNode = root + "/password";

	private final static String auth_type = "digest";
	private final static String auth_passwd = "password";

	private final static String DB_URL = "192.168.1.101";
	private final static String DB_USERNAME = "root";
	private final static String DB_PASSWD = "root123";

	public static void main(String[] args) throws Exception {
		ZooKeeper zk = new ZooKeeper(url, 3000, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				System.out.println("触发了事件...");
			}
		});

		while (ZooKeeper.States.CONNECTED != zk.getState()) {
			Thread.sleep(3000);
		}

		zk.addAuthInfo(auth_type, auth_passwd.getBytes());
		//zk.delete(urlNode, -1);
		//zk.delete(userNameNode, -1);
		//zk.delete(passwordNode, -1);
		//zk.delete(root, -1);

		if (zk.exists(root, true) == null) {
			zk.create(root, "root".getBytes(), Ids.CREATOR_ALL_ACL,
					CreateMode.PERSISTENT);
		}
		if (zk.exists(urlNode, true) == null) {
			zk.create(urlNode, DB_URL.getBytes(), Ids.CREATOR_ALL_ACL,
					CreateMode.PERSISTENT);
		}
		if (zk.exists(userNameNode, true) == null) {
			zk.create(userNameNode, DB_USERNAME.getBytes(),
					Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
		}
		if (zk.exists(passwordNode, true) == null) {
			zk.create(passwordNode, DB_PASSWD.getBytes(), Ids.CREATOR_ALL_ACL,
					CreateMode.PERSISTENT);
		}
		zk.close();
	}
}


//=============================


package zookeeper.study1;

import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

public class Client implements Watcher{
	
	public static String url = "192.168.1.101:2181";
	
	private final static String root = "/myConf";
	private final static String urlNode = root + "/url";
	private final static String userNameNode = root + "/userName";
	private final static String passwordNode = root + "/password";
	
	private final static String auth_type = "digest";
	private final static String auth_passwd = "password";
	
	private String urlString ;
	private String userName;
	private String passwd;
	
	private ZooKeeper zk = null;
	
	
	public void initValue() throws KeeperException, InterruptedException{
		//zk = new ZooKeeper(url, 3000, watcher)
		urlString = new String(zk.getData(urlNode, true, null)); 
		userName = new String(zk.getData(userNameNode, true, null)); 
		passwd = new String(zk.getData(passwordNode, true, null)); 
	}
	
	public ZooKeeper getZK() throws Exception{
		zk =  new ZooKeeper(url,3000,this);
		//权限认证
		zk.addAuthInfo(auth_type,auth_passwd.getBytes());
		while (zk.getState() != ZooKeeper.States.CONNECTED) {
			Thread.sleep(3000);
		}
		System.out.println("");
		return zk;
	}
	
	public static void main(String[] args) throws Exception {
		Client client = new Client();
		ZooKeeper zooKeeper = client.getZK();
		client.initValue();
		int i = 0;
		while (true) {
			System.out.println("userString : " + client.getUrlString());
			System.out.println("userName : " + client.getUserName());
			System.out.println("passwd : " + client.getPasswd());
			System.out.println("======================================");
			Thread.sleep(5000);
			i++;
			if (i == 5) {
				break;
			}
		}
	}
	
	@Override
	public void process(WatchedEvent event) {
		if (event.getType() == Watcher.Event.EventType.None) {
			System.out.println("连接服务器成功");
		}
		if (event.getType() == Watcher.Event.EventType.NodeCreated) {
			System.out.println("节点创建成功");
		}
		if(event.getType() == Watcher.Event.EventType.NodeChildrenChanged){
			System.out.println("子节点更新成功");
			//更新读取新的配置
			try {
				initValue();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (event.getType() == Watcher.Event.EventType.NodeDataChanged) {
			System.out.println("节点更新成功");
			//更新读取新的配置
			try {
				initValue();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (event.getType() == Watcher.Event.EventType.NodeDeleted) {
			System.out.println("节点删除成功");
		}
	}


	public String getUrlString() {
		return urlString;
	}


	public void setUrlString(String urlString) {
		this.urlString = urlString;
	}


	public String getUserName() {
		return userName;
	}


	public void setUserName(String userName) {
		this.userName = userName;
	}


	public String getPasswd() {
		return passwd;
	}


	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

}
Spring jar下载 spring
http://www.java2s.com/Code/Jar/o/org.springframework.htm
使用构造器来代替参数比较多的构造方法 java
package effective.study1.constructor.build;

public class Person {
	
	private final String name;
	private final int age;
	private final int sex;
	private final String iphone;
	private final String address;
	
	
	public Person(Builder builder) {
		this.name = builder.name;
		this.age = builder.age;
		this.sex = builder.sex;
		this.iphone = builder.iphone;
		this.address = builder.address;
	}




	public static class Builder{
		private final String name;
		private final int age;
		private final int sex;

		//default
		private String iphone = "13076061657";
		private String address = "成都市";
		
		public Builder(String name,int age,int sex){
			this.name = name;
			this.age = age;
			this.sex = sex;
		}
		
		public Builder iphone(String val){
			iphone = val;
			return this;
		}
		public Builder address(String val){
			address = val;
			return this;
		}
		
		public Person build(){
			return new Person(this);
		}
	}
	
	
	public String getName() {
		return name;
	}
	public int getAge() {
		return age;
	}
	public int getSex() {
		return sex;
	}
	public String getIphone() {
		return iphone;
	}
	public String getAddress() {
		return address;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", sex=" + sex
				+ ", iphone=" + iphone + ", address=" + address + "]";
	}
}




//使用
package effective.study1.constructor.build;

import effective.study1.constructor.build.Person.Builder;

public class Main {
	
	public static void main(String[] args) {
		Person p = new Person.Builder("孙刚",22,1).iphone("188888888888").build();
		System.out.println(p.toString());
	}
}



//=========================第二种方式=====================================
package effective.study1.constructor.build;

public interface AttributeBuilder<T> {
	
	T build();
}


//=========================实现不同bean的 builder=========================
package effective.study1.constructor.build;

public class PersonBuilder implements AttributeBuilder<Person>{
	
	public final String name;
	public final int age;
	public final int sex;

	//default
	public String iphone = "13076061657";
	public String address = "成都市";
	
	public PersonBuilder(String name,int age,int sex){
		this.name = name;
		this.age = age;
		this.sex = sex;
	}
	
	public PersonBuilder iphone(String val){
		iphone = val;
		return this;
	}
	public PersonBuilder address(String val){
		address = val;
		return this;
	}
	
	@Override
	public Person build() {
		return new Person(this);
	}
}


//TEST
package effective.study1.constructor.build;


public class Main {
	
	public static void main(String[] args) {
		Person p = new PersonBuilder("孙刚", 22, 1).iphone("1888888888").build();
		System.out.println(p.toString());
	}
}
java处理时间 java
//开始时间
private String startTime;
//结束时间
private String endTime;


/**
	 * 处理时间
	 * @throws ParseException
	 */
	private void processTime() {
		String sTime = null;
		String eTime = null;
		if (null != energyDataRecord.getDataFormatType()) {
			String dataFormatType = energyDataRecord.getDataFormatType();
			
			//小时
			if ("HH".equals(dataFormatType)) {
				sTime = this.startTime+ ":00:00";
				eTime = this.endTime+ ":59:59";
			}
			//天
			if ("DD".equals(dataFormatType)) {
				sTime = this.startTime + " 00:00:00";
				eTime = this.endTime + " 23:59:59";
			}
			//月
			if ("MM".equals(dataFormatType)) {
				sTime = this.startTime + "-01 00:00:00";
				String[] dateStrs = this.endTime.split("-");
				int month = Integer.parseInt(dateStrs[1]);
				if(month == 12){//处理12月
					eTime = endTime + "-31 23:59:59";
				}else{
					//结束时间设置为下个月的1号零点零分
					eTime = dateStrs[0] + "-" + (month + 1) + "-01 00:00:00";
				}
			}
			//年
			if ("YY".equals(dataFormatType)) {
				sTime = startTime + "-01-01 00:00:00";
				eTime = endTime + "-12-31 23:59:59";
			}
		}
		if (null != sTime && null != eTime) {
			try {
				this.energyDataRecord.setStartDate(DataUtil.SDF_DATE_DETAIL_TIME.parse(sTime));
				this.energyDataRecord.setEndDate(DataUtil.SDF_DATE_DETAIL_TIME.parse(eTime));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
}




/**
	 * 日期格式:yyyy-MM-dd HH:mm:ss
	 */
	public static final SimpleDateFormat SDF_DATE_DETAIL_TIME = new SimpleDateFormat( "yyyy-MM-dd H:m:s");
Spring 事件监听器使用 spring
package cd.itcast.spring.day2.event;

public class Customer {
	private Long id;
	private String name;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


//=====================================================

package cd.itcast.spring.day2.event;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CustomerServiceImpl implements ApplicationContextAware {

	private ApplicationContext ctx;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.ctx = applicationContext;
	}

	public void save(Customer c) {
		System.out.println("save customer...." + c.getName());
		// 向容器发出一个信息:一个customer保存了.
		this.ctx.publishEvent(new CustomerEventObject(this, c));
	}
}

//=====================================================
package cd.itcast.spring.day2.event;

import org.springframework.context.ApplicationEvent;

public class CustomerEventObject extends ApplicationEvent {
	public CustomerEventObject(Object source, Customer c) {
		super(source);
		this.customer = c;
	}

	private Customer customer;

	public Customer getCustomer() {
		return customer;
	}

}

//=========================日志事件============================

package cd.itcast.spring.day2.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class LogServiceImpl implements ApplicationListener<ApplicationEvent> {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof CustomerEventObject) {
			CustomerEventObject eo = (CustomerEventObject) event;
			this.log(eo.getCustomer().getName());
		}
	}

	private void log(String msg) {
		System.out.println("add log..." + msg);
	}
}

//=========================发送邮件事件============================
package cd.itcast.spring.day2.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class SmsServiceImpl implements ApplicationListener<ApplicationEvent> {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof CustomerEventObject) {
			CustomerEventObject eo = (CustomerEventObject) event;
			this.send(eo.getCustomer().getName());
		}
	}

	public void send(String msg) {
		System.out.println("send sms..." + msg);
	}
}


//========================Spring 配置 注入 bean============================
 <bean id="customerService" class="cd.itcast.spring.day2.event.CustomerServiceImpl" />
 <bean class="cd.itcast.spring.day2.event.LogServiceImpl" />
 <bean class="cd.itcast.spring.day2.event.SmsServiceImpl" />


//=======================TEST ============================

package cd.itcast.spring.day2.event;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

	@Test
	public void testService2() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"application.xml");
		CustomerServiceImpl service = ctx.getBean("customerService",
				CustomerServiceImpl.class);

		Customer c = new Customer();
		c.setName("itcast");
		service.save(c);
	}

}

//=======================TEST ============================
//save customer....itcast
//add log...itcast
//send sms...itcast


通过Spring 拦截器实现 获取 request的 contentPath 和 当前路径、BackPath java

public interface Constants {

    /****/
    String CONTEXT_PATH = "ctx";

    /**
     * 当前请求的地址 带参数
     */
    String CURRENT_URL = "currentURL";


    /**
     * 当前请求的地址 不带参数
     */
    String NO_QUERYSTRING_CURRENT_URL = "noQueryStringCurrentURL";

    /**
     * 上个页面地址
     */
    String BACK_URL = "BackURL";

}


//8*******************Spring  拦截器类*************************
package com.sishuok.es.common.web.interceptor;

import com.sishuok.es.common.Constants;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 设置通用数据的Interceptor
 * <p/>
 * 使用Filter时 文件上传时 getParameter时为null 所以改成Interceptor
 * <p/>
 * 1、ctx---->request.contextPath
 * 2、currentURL---->当前地址
 * <p>User: Zhang Kaitao
 * <p>Date: 13-1-22 下午4:35
 * <p>Version: 1.0
 */
public class SetCommonDataInterceptor extends HandlerInterceptorAdapter {

    private final PathMatcher pathMatcher = new AntPathMatcher();

    private static final String[] DEFAULT_EXCLUDE_PARAMETER_PATTERN = new String[]{
            "\\&\\w*page.pn=\\d+",
            "\\?\\w*page.pn=\\d+",
            "\\&\\w*page.size=\\d+"
    };

    private String[] excludeParameterPatterns = DEFAULT_EXCLUDE_PARAMETER_PATTERN;
    private String[] excludeUrlPatterns = null;

    public void setExcludeParameterPatterns(String[] excludeParameterPatterns) {
        this.excludeParameterPatterns = excludeParameterPatterns;
    }

    public void setExcludeUrlPatterns(final String[] excludeUrlPatterns) {
        this.excludeUrlPatterns = excludeUrlPatterns;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(isExclude(request)) {
            return true;
        }

        if (request.getAttribute(Constants.CONTEXT_PATH) == null) {
            request.setAttribute(Constants.CONTEXT_PATH, request.getContextPath());
        }
        if (request.getAttribute(Constants.CURRENT_URL) == null) {
            request.setAttribute(Constants.CURRENT_URL, extractCurrentURL(request, true));
        }
        if (request.getAttribute(Constants.NO_QUERYSTRING_CURRENT_URL) == null) {
            request.setAttribute(Constants.NO_QUERYSTRING_CURRENT_URL, extractCurrentURL(request, false));
        }
        if (request.getAttribute(Constants.BACK_URL) == null) {
            request.setAttribute(Constants.BACK_URL, extractBackURL(request));
        }

        return true;
    }

    private boolean isExclude(final HttpServletRequest request) {
        if(excludeUrlPatterns == null) {
            return false;
        }
        for(String pattern : excludeUrlPatterns) {
            if(pathMatcher.match(pattern, request.getServletPath())) {
                return true;
            }
        }
        return false;
    }


    private String extractCurrentURL(HttpServletRequest request, boolean needQueryString) {
        String url = request.getRequestURI();
        String queryString = request.getQueryString();
        if (!StringUtils.isEmpty(queryString)) {
            queryString = "?" + queryString;
            for (String pattern : excludeParameterPatterns) {
                queryString = queryString.replaceAll(pattern, "");
            }
            if (queryString.startsWith("&")) {
                queryString = "?" + queryString.substring(1);
            }
        }
        if (!StringUtils.isEmpty(queryString) && needQueryString) {
            url = url + queryString;
        }
        return getBasePath(request) + url;
    }

    /**
     * 上一次请求的地址
     * 1、先从request.parameter中查找BackURL
     * 2、获取header中的 referer
     *
     * @param request
     * @return
     */
    private String extractBackURL(HttpServletRequest request) {
        String url = request.getParameter(Constants.BACK_URL);

        //使用Filter时 文件上传时 getParameter时为null 所以改成Interceptor

        if (StringUtils.isEmpty(url)) {
            url = request.getHeader("Referer");
        }

        if(!StringUtils.isEmpty(url) && (url.startsWith("http://") || url.startsWith("https://"))) {
            return url;
        }

        if (!StringUtils.isEmpty(url) && url.startsWith(request.getContextPath())) {
            url = getBasePath(request) + url;
        }
        return url;
    }

    private String getBasePath(HttpServletRequest req) {
        StringBuffer baseUrl = new StringBuffer();
        String scheme = req.getScheme();
        int port = req.getServerPort();

        //String		servletPath = req.getServletPath ();
        //String		pathInfo = req.getPathInfo ();

        baseUrl.append(scheme);        // http, https
        baseUrl.append("://");
        baseUrl.append(req.getServerName());
        if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) {
            baseUrl.append(':');
            baseUrl.append(req.getServerPort());
        }
        return baseUrl.toString();
    }
}


//****************Spring 拦截配置******************
 <!-- 拦截器设置 -->
    <mvc:interceptors>
        <bean class="org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor">
            <constructor-arg ref="conversionService"/>
        </bean>
        <bean class="com.sishuok.es.common.web.interceptor.SetCommonDataInterceptor">
            <property name="excludeUrlPatterns">
                <value>/admin/polling </value>
            </property>
        </bean>
        <mvc:interceptor>
            <mvc:mapping path="/admin/**" />
            <mvc:mapping path="/office/**" />
            <mvc:exclude-mapping path="/admin/polling"/>
            <bean class="org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor"/>
        </mvc:interceptor>
        <!--<mvc:interceptor>-->
        <!--<mvc:mapping path="/**"/>-->
        <!--<bean class="cn.javass.test.interceptor.TestInterceptor"/>-->
        <!--</mvc:interceptor>-->
    </mvc:interceptors>


//*******************页面使用******************

//直接可以:

${ctx}
${currentURL}
将区域一些数据加载到内存中 java
public class LoadAreaServlet extends HttpServlet{
	
	
	/**
	*/
	private static final long serialVersionUID = 1457805673123717992L;

	@Override
	public void init() throws ServletException {
		//初始化  区域数据
		CitySection.CITY_SECTION.init();
	}
}




//=====================================================


package com.supinfo.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.opensymphony.xwork2.ActionContext;
import com.supinfo.jieneng.domains.Area;
import com.supinfo.jieneng.domains.City;
import com.supinfo.jieneng.domains.County;
import com.supinfo.jieneng.services.AreaService;


public class CitySection {
	public static ApplicationContext CONTEXT = new ClassPathXmlApplicationContext(
			new String[] { "applicationContext-mybatis.xml",
					"applicationContext-services.xml" });
	
	private static AreaService areaService = CONTEXT.getBean("areaService",AreaService.class);
	
	public static final String DEFAULT_CITY_NAME = "成都";//默认城市名
	
	
	public static final CitySection CITY_SECTION = new CitySection(); 
	
	/**
	 * key:城市名,value:区域集合
	 */
	private static final Map<String, List<String>> CITY_SECTION_MAP = new HashMap<String, List<String>>();
	
	/**
	 * key:省名,value:城市Map集合
	 * 城市Map集合的key:城市名,value:区域集合
	 */
	public static final Map<String, Map<String, List<Area>>> PROVINCE_CITY_SECTION_MAP = new HashMap<String, Map<String, List<Area>>>();
	
	/**
	 * 获取所有城市名
	 * 
	 * @return
	 */
	public static List<City> findAllAreaName() {
		
		//存储城市
		List<City> cityList = new ArrayList<City>();
		//存储区域
		List<County> countyList = new ArrayList<County>();
		
		try {
			//获取所有省份
			List<Area> provinces = areaService.getAreaByPID(0l);
			if(DataUtil.checkListNullAndSize(provinces)){
				for (Area areaProvince : provinces) {
					//根据省份ID获取  所属省份下的城市
					List<Area> citys = areaService.getAreaByPID(areaProvince.getId());
					if (DataUtil.checkListNullAndSize(citys)) {
						for (Area areaCity : citys) {
							City  city = new City();
							city.setId(areaCity.getId());
							city.setTie(areaCity.getAreaName());
							city.setCode(areaCity.getCode());
							
							//根据城市ID 获取所属城市下的区县
							List<Area> countys = areaService.getAreaByPID(areaCity.getId());
							if (DataUtil.checkListNullAndSize(countys)) {
								for (Area areaCounty : countys) {
									County county = new County();
									county.setId(areaCounty.getId());
									county.setTie(areaCounty.getAreaName());
									county.setCode(areaCounty.getCode());
									
									countyList.add(county);
									
									city.setCouns(countyList);
								}
							}
							
							cityList.add(city);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cityList;
	}
	
	/**
	 * 根据城市名获取其ID
	 * @author 
	 * @return
	 */
	public static Long findCityIdByName(String cityName) {
		
		Long cityId = null;//待查找城市的ID
		try {
			// 查询所有的省份
			List<Area> provinces = areaService.getAreaByPID(0L);
			if (DataUtil.checkListNullAndSize(provinces)) {
				for (Area areaProvince : provinces) {
					//获取城市
					List<Area> citys = areaService.getAreaByPID(areaProvince.getId());
					if (DataUtil.checkListNullAndSize(citys)) {
						for (Area areaCity : citys) {
							if (null != cityName && cityName.equals(areaCity.getAreaName())) {
								return areaCity.getId();
							}
							
							//找默认城市的ID
							if(cityId == null && DEFAULT_CITY_NAME.equals(areaCity.getAreaName())){
								
								cityId = areaCity.getId();//设置默认城市ID
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cityId;
	}
	

	/**
	 * 获取某城市下的所有区域
	 * 
	 * @param cityName
	 * @return
	 */
	public static List<String> findSectionInCity(String cityName) {
		List<String> re = new ArrayList<String>();
			try {
				if (null != cityName) {
					List<Area> citys = areaService.getAreaByName(cityName);
					if (DataUtil.checkListNullAndSize(citys)) {
						List<Area> areas = areaService.getAreaByPID(citys.get(0).getId());
						if (DataUtil.checkListNullAndSize(areas)) {
							for (Area area : areas) {
								re.add(area.getAreaName());
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return re;
	}
	
	/**
	 * 根据城市对象、获取某城市下的所有区域
	 * 
	 * @param cityName
	 * @return
	 */
	public static List<Area> findSectionInCity(Area area) {
		if (null != area) {
			try {
				return areaService.getAreaByPID(area.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	/**
	 * 根据省份名获取省份对象
	 * @param provName
	 * @return
	 */
	public static Area findProvinceByProvName(String provName){
		if (provName != null) {
			try {
				List<Area> areas = areaService.getAreaByName(provName);
				if (DataUtil.checkListNullAndSize(areas)) {
					for (Area area : areas) {
						if (area.getPid() == 0) {
							return area;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 根据省份对象、城市名获取城市对象
	 * @return
	 */
	public static Area findCityByProvAndCityName(Area provObj, String cityName){
		if (null != cityName) {
			try {
				List<Area> areas = areaService.getAreaByName(cityName);
				if (DataUtil.checkListNullAndSize(areas)) {
					for (Area area : areas) {
						if (null != provObj) {
							if (area.getPid() == provObj.getId() ) {
								return area;
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	

	/**
	 * 通过区域名获取区域id
	 * 
	 * @param sname
	 * @return
	 */
	public static Long findSectionIdByName(String cityName, String sname) {
		if (null != cityName) {
			try {
				List<Area> areas = areaService.getAreaByName(cityName);
				if (DataUtil.checkListNullAndSize(areas)) {
					for (Area area : areas) {
						List<Area> citys = areaService.getAreaByPID(area.getId());
						if (DataUtil.checkListNullAndSize(citys)) {
							for (Area area2 : citys) {
								if (null != sname) {
									if (sname.equals(area2.getAreaName())) {
										return area2.getId();
									}
								}
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	/**
	 * 通过城市id获取城市名
	 * 
	 * @param id
	 * @return
	 */
	public static String findCityNameById(Long cityid) {
		if (cityid != null) {
			try {
				return areaService.findObjectById(cityid).getAreaName();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	
	
	/**
	 * 通过城市名获取区域集合
	 * 
	 * @param cityName
	 * @return
	 */
	public List<String> get(String cityName) {
		
		initCitySectionMap();
		
		return CITY_SECTION_MAP.get(cityName);
	}
	
	/**
	 * 获取城市名集合
	 * 
	 * @return
	 */
	public void init() {

		initCitySectionMap();

		//return PROVINCE_CITY_SECTION_MAP;
	}
	
	
	
	/**
	 * 为PROVINCE_CITY_SECTION_MAP集合设置值
	 */
	private static void initCitySectionMap() {
		if(PROVINCE_CITY_SECTION_MAP.size() > 0){
			
			PROVINCE_CITY_SECTION_MAP.clear();
		}
		
		try {
			//获取所有省份
			List<Area> provinces = areaService.getAreaByPID(0l);
			if (DataUtil.checkListNullAndSize(provinces)) {
				for (Area areaProvince : provinces) {
					//根据省份ID获取  所属省份下的城市
					List<Area> citys = areaService.getAreaByPID(areaProvince.getId());
					//创建城市、区域集合
					Map<String, List<Area>> citySectionMap = new HashMap<String, List<Area>>();
					if (DataUtil.checkListNullAndSize(citys)) {
						for (Area areaCity : citys) {
							String cityName = areaCity.getAreaName();
							//根据城市ID 获取所属城市下的区县
							List<Area> countys = areaService.getAreaByPID(areaCity.getId());
							// 将城市名(键)与区域集合(值)加入map
							citySectionMap.put(cityName, countys);
						}
					}
					// 将省份名(键)与城市区域集合(值)加入map
					PROVINCE_CITY_SECTION_MAP.put(areaProvince.getAreaName(), citySectionMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取当前选中城市如果没有则取默认城市
	 * @return
	 */
	public static String getCurrentCity(){
		
		String city  = (String)ActionContext.getContext().getSession().get("city");
		
		if(DataUtil.isNotNullAndEmpty(city)){
			return city;
		}
		
		return DEFAULT_CITY_NAME;
	}
	
	
	public static Map<String, Map<String, List<Area>>> getAreaDataMap(){
		if (null != PROVINCE_CITY_SECTION_MAP && PROVINCE_CITY_SECTION_MAP.size() > 0) {
			return PROVINCE_CITY_SECTION_MAP;
		}
		
		CitySection.CITY_SECTION.initSecond();
		
		return PROVINCE_CITY_SECTION_MAP;
	}
	/**
	 * 
	* 描述  : 第二次初始化
	* 方法名: initSecond
	* 创建人:孙刚   
	* 创建时间:2014-2-24 下午05:01:56  
	* @return :void
	 */
	private Map<String, Map<String, List<Area>>> initSecond() {

		initCitySectionMap();

		return PROVINCE_CITY_SECTION_MAP;
	}
}

//=======================

package com.supinfo.jieneng.domains;

import java.io.Serializable;

import com.supinfo.core.base.BaseDomain;
/**
* @Description:TODO(行政区域实体) 
* 项目名称:jnschool   
* 类名称:Area   
* 创建人:孙刚   
* 创建时间:2013-12-9 上午09:24:00   
* 修改人1:xxx     
* 修改时间1:xxxx-xx-xx 
* 修改备注:   
* @version  1.0
 */
@SuppressWarnings("serial")
public class Area extends BaseDomain implements Serializable {
	/**
	 * 区域名称
	 */
    private String areaName;
    /**
     * pid
     */
    private Long pid;
    /**
     * 区域编号
     */
    private String code;


    public String getAreaName() {
		return areaName;
	}

	public void setAreaName(String areaName) {
		this.areaName = areaName;
	}

	public Long getPid() {
        return pid;
    }

    public void setPid(Long pid) {
        this.pid = pid;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}


//=====================================
package com.supinfo.jieneng.domains;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

/**
 * 区域
 * @author 
 *
 */
@XStreamAlias("coun")
public class County {
	
	@XStreamAsAttribute
    @XStreamAlias("id")
	private Long id;
	
	@XStreamAsAttribute
    @XStreamAlias("tie")
	private String tie;
	
	@XStreamAsAttribute
    @XStreamAlias("code")
	private String code;
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getTie() {
		return tie;
	}

	public void setTie(String tie) {
		this.tie = tie;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
	
	
}
//================================
package com.supinfo.jieneng.domains;

import java.util.List;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;

@XStreamAlias("city")
public class City {

	@XStreamAsAttribute
    @XStreamAlias("id")
	private Long id;
	
	@XStreamAsAttribute
    @XStreamAlias("tie")
	private String tie;
	@XStreamAsAttribute
    @XStreamAlias("code")
	private String code;
	
	@XStreamImplicit
	private List<County> couns;
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getTie() {
		return tie;
	}

	public void setTie(String tie) {
		this.tie = tie;
	}

	public List<County> getCouns() {
		return couns;
	}

	public void setCouns(List<County> couns) {
		this.couns = couns;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}
	
}


自定义JAVA 动态代理实现 java
http://my.oschina.net/feichexia/blog/201907


//======================InvocationHandler =======================

package org.sung.java.custom.dynamicProxy;

import java.lang.reflect.Method;

public interface InvocationHandler {
	
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;
	
}


//======================Proxy =======================

package org.sung.java.custom.dynamicProxy;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;

import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class Proxy implements Serializable {
	
	private final static Class[] constructorParams = { InvocationHandler.class };
	private static Map<Class<?>, Void> proxyClasses = Collections.synchronizedMap(new WeakHashMap<Class<?>, Void>());
	
	public static Object newProxyInstance(ClassLoader loader, Class<?> inface,
			InvocationHandler handler) throws IllegalArgumentException {

		if (null == handler) {
			throw new NullPointerException("handler is not null...");
		}
		// 获取代理对象
		Class<?> $proxyClass = getProxyClass(inface, loader);
		try {
			final Constructor<?> cons = $proxyClass.getConstructor(constructorParams);
			final InvocationHandler ih = handler;
			return newInstance(cons, ih);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return null;

	}

	private static Class<?> getProxyClass(Class<?> inface, ClassLoader loader) {
		String methodStr = "";
		String rt = "\r\n";
		// 过去接口中 所有的方法
		Method[] methods = inface.getMethods();
		// 判断接口中 是否有方法
		if (null != methods) {
			// 遍历所有方法
			for (Method method : methods) {
				// 获取方法所有的的参数类型
				Class<?>[] paramTypes = method.getParameterTypes();
				// 获取方法的返回类型
				Class<?> returnType = method.getReturnType();
				methodStr += "	public " + returnType.getSimpleName() + " " + method.getName();
				// 判断参数类型
				if (paramTypes.length > 0) {
					//保存临时参数
					String tempParamNames = "";
					//保存临时的参数类型
					String tempParamTypes = "";
					String tempparamName ="";
					// 遍历 参数类型
					for (int i = 0; i < paramTypes.length; i++) {
						// 获取参数类型名
						String paramTypeSimpleName = paramTypes[i].getSimpleName();
						// 制定一个 参数名 
						String paramName = "param"+(i+1);
						tempparamName += paramName + ",";
						tempParamNames += paramTypeSimpleName + " " + paramName + ",";
						tempParamTypes += paramTypeSimpleName + ".class" + ",";
					}
					
					tempParamNames = tempParamNames.substring(0,tempParamNames.length()-1) ;
					tempParamTypes = tempParamTypes.substring(0,tempParamTypes.length()-1);
					tempparamName = tempparamName.substring(0, tempparamName.length()-1);
					
					methodStr += "("+tempParamNames+"){" + rt
							+ "		try{" +  rt
							+ "			Method m = " + inface.getName()+".class.getMethod(\"" + method.getName() + "\",new Class[]{"+tempParamTypes+"});" + rt
							+ "			handler.invoke(this,m,new Object[]{"+tempparamName+"});" + rt
							+ "		}catch(Exception e) {" + rt 
							+ "			e.printStackTrace();" + rt
							+ "		}catch(Throwable e){" + rt
							+ "			e.printStackTrace();" + rt
							+ "		}" + rt
							+ "	}" + rt + "" + rt;
					
				} else {
					methodStr += "(){" + rt 
							+ "		try{" + rt 
							+ "			Method m = " + inface.getName() + ".class.getMethod(\"" + method.getName() + "\");" + rt 
							+ "			return (" + returnType.getSimpleName() + ")handler.invoke(this,m,new Object[]{});" + rt
							+ "		}catch(Exception e) {" + rt
							+ "			e.printStackTrace();" + rt 
							+ "		}catch(Throwable e){" + rt
							+ "			e.printStackTrace();" + rt 
							+ "		}" + rt
							+ "			return null;" + rt 
							+ "	}" + rt + "" + rt;
				}
			}
		} else {
			// 没有方法
		}
		
		
		// 获取当前接口的包名
		Package pack = inface.getPackage();
		String packageName = pack.getName();

		String score = "package " + packageName + ";" + rt + "" + rt
				+ "import java.lang.reflect.Method;" + rt + "" + rt
				+ "public class $ProxyClass implements "
				+ inface.getSimpleName() + " { " + rt + "" + rt + "	"
				+ packageName + ".InvocationHandler handler;" + rt + "" + rt
				+ "	public $ProxyClass(InvocationHandler handler) {" + rt
				+ "		this.handler = handler;" + rt + "	}" + rt + "" + rt +
				methodStr + rt +
				"}";
		
		
		//System.out.println(score);
		// 写入内存中

		Class<?> $proxyClass = writeClassToLoad(inface, score, packageName);

		return $proxyClass;
	}

	private static Class<?> writeClassToLoad(Class<?> inface, String score,
			String packageName) {

		String fileSeparator = File.separator;

		// 生成 源代码 目录
		String fileName = System.getProperty("user.dir") + fileSeparator
				+ "src" + fileSeparator + "main" + fileSeparator + "java"
				+ fileSeparator + packageName.replace(".", fileSeparator);

		// 生成到 本地
		File parentFile = new File(fileName);
		if (!parentFile.exists()) {
			parentFile.mkdir();
		}

		FileWriter fileWriter;
		try {
			fileWriter = new FileWriter(new File(parentFile, fileSeparator + "$ProxyClass.java"));
			fileWriter.write(score);
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 编译 本地 JAVA文件
		Class<?> $proxyClass = compilerClassToLoad(fileName, fileSeparator,packageName);
		
		
		return $proxyClass;
	}

	@SuppressWarnings("restriction")
	private static Class<?> compilerClassToLoad(String fileName,String fileSeparator,String packageName) {
		// 编译 compile

		// 1,拿到 API 编译器
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

		// System.out.println("compiler : " + compiler);

		// 2,获取 JAVA file 管理器
		// 参数 null 意味都是用 默认的
		StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

		// 3,根据文件名字,获取一系列 JAVAFileObject 可使用多个
		// 通过 fileManager找到 fileName
		Iterable untis = fileManager.getJavaFileObjects(fileName + fileSeparator + ".$ProxyClass.java");

		// 4,获取编译任务
		CompilationTask task = compiler.getTask(null, fileManager, null, null,null, untis);

		// 5,实行任务
		task.call();

		try {
			// 6,关掉
			fileManager.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// load 到 内存 和 生成新对象
		try {
			URL[] urls = new URL[] { new URL("file:" + fileSeparator + System.getProperty("user.dir") + fileSeparator + "src"
					+ fileSeparator + "main" + fileSeparator + "java") };

			URLClassLoader classLoader = new URLClassLoader(urls);
			Class<?> clazz = classLoader.loadClass(packageName + ".$ProxyClass");

			return clazz;
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
    public static boolean isProxyClass(Class<?> cl) {
        if (cl == null) {
            throw new NullPointerException();
        }
        return proxyClasses.containsKey(cl);
    }
    
    
    private static Object newInstance(Constructor<?> cons, InvocationHandler h) {
    	 try {
			return cons.newInstance(new Object[] {h} );
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
    	 
    	 return null;
    }
}


//======================User =======================

package org.sung.java.custom.dynamicProxy;

public class User {
	
	private int id;
	private String name;
	private String pwd;
	
	
	public User() {
		super();
	}

	public User(int id, String name, String pwd) {
		super();
		this.id = id;
		this.name = name;
		this.pwd = pwd;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
	}
}


//======================HelloWord =======================
package org.sung.java.custom.dynamicProxy;

public interface HelloWord {
	void setMsg(String msg,String name);
	String getMsg();
	
	void setUser(User user);
	
	User getUser();
}

//======================HelloWordImpl =======================
package org.sung.java.custom.dynamicProxy;

public class HelloWordImpl implements HelloWord{

	public void setMsg(String msg,String name) {
		System.out.println(msg + ": " + name);
	}

	public String getMsg() {
		return "hello : sungang";
	}

	public void setUser(User user) {
		System.out.println(user.toString());
	}

	public User getUser() {
		User user = new User(1, "sungang", "12346");
		return user;
	}
}	

//======================LogHandler =======================

package org.sung.java.custom.dynamicProxy;

import java.lang.reflect.Method;

public class LogHandler implements InvocationHandler{
	
	private Object target;
	
	
	public LogHandler(Object target) {
		super();
		this.target = target;
	}

	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("log start ............");
		return method.invoke(target, args);
	}

}


//======================Client =======================
package org.sung.java.custom.dynamicProxy;

import java.io.IOException;

public class Client {

	public static void main(String[] args) throws IOException {

		HelloWord iHelloWord = new HelloWordImpl();
		LogHandler handler = new LogHandler(iHelloWord);
		HelloWord helloWord = (HelloWord) Proxy.newProxyInstance(null,
				HelloWord.class, handler);

		helloWord.setMsg("hello ", "sungang");

		String msg = helloWord.getMsg();
		System.out.println(msg);
		
		helloWord.setUser(new User(1, "sungang", "123465"));
		
		User user = helloWord.getUser();
		System.out.println(user.toString());
	}
}

//======================运行结果 =======================
//log start ............
//hello : sungang
//log start ............
//hello : sungang
//log start ............
//User [id=1, name=sungang, pwd=123465]
//log start ............
//User [id=1, name=sungang, pwd=12346]
nginx nginx.conf配置主要内容 linux
//nginx.conf


#运行用户
#user  nginx nginx;

#启动进程,通常设置成和cpu的数量相等
worker_processes  2;

#全局错误日志及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid of nginx master process
#pid        logs/nginx.pid;


#工作模式及连接数上限
events {
    #use   epoll;             #epoll是多路复用IO(I/O Multiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
    worker_connections  1024;#单个后台worker process进程的最大并发链接数
    # multi_accept on; 
}


#设定http服务器,利用它的反向代理功能提供负载均衡支持
http {
	#设定mime类型,类型由mime.type文件定义
    include       mime.types;
    default_type  application/octet-stream;
	#编码格式
	charset  utf-8;
	
	#设定日志格式 include logs.conf
    include logs.conf;
	
	#sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,对于普通应用,
	#必须设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    sendfile        on;
   
	# These are good default values.
	tcp_nopush        on;
	tcp_nodelay       off;

	#连接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
	
	#设定请求缓冲
	server_names_hash_bucket_size 128;
    client_header_buffer_size 512k;
	large_client_header_buffers 4 32k;
	client_max_body_size 300m;
	client_body_buffer_size  512k;
	proxy_connect_timeout    5;
	proxy_read_timeout       600;
	proxy_send_timeout       5;
	proxy_buffer_size        16k;
	proxy_buffers            4 64k;
	proxy_busy_buffers_size 128k;
	proxy_temp_file_write_size 128k;
  
	#开启gzip压缩 include gzip.conf;
    include gzip.conf;

   

    #这里为后端服务器应用集群配置,根据后端实际情况修改即可,sung_test1为负载均衡名称,可以任意指定
	#但必须跟vhosts.conf虚拟主机的pass段一致,否则不能转发后端的请求。
	upstream tdt_sung {
		server   192.168.2.100:8088 weight=1 max_fails=2 fail_timeout=30s;
		#server   192.168.2.106:8080 weight=1 max_fails=2 fail_timeout=30s;
		#server   10.10.141.30:8081 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.31:8080 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.31:8081 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.32:8080 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.32:8081 weight=1max_fails=2fail_timeout=30s;
	}
	
	
	#这里为后端APP应用负载均衡配置,根据后端实际情况修改即可。tdt_app为负载均衡名称,可以任意指定
	#upstream tdt_app {
		#server   10.10.141.40:8080 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.40:8081 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.41:8080 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.41:8081 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.42:8080 weight=1max_fails=2fail_timeout=30s;
		#server   10.10.141.42:8081 weight=1max_fails=2fail_timeout=30s;
	#}
   
	#include引用vhosts.conf,该文件主要用于配置Nginx 虚拟主机
	include vhosts.conf;
}



//logs.conf

log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status  $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';
		
# 访问输入日志
access_log  logs/access.log  main;

# 错误输出日志
error_log  logs/error.log notice;


//gzip.conf

gzip on;
gzip_http_version 1.1;
gzip_buffers     4 16k;
gzip_comp_level 2;
gzip_proxied any;
gzip_types      text/plain text/css application/x-javascript application/xml application/xml+rss text/javascript;
gzip_vary on;

//vhosts.conf

server{
	#侦听80端口
    listen       80;
    server_name  www.sunggang.cn;
    index index.jsp;
	#设定本虚拟主机的访问日志
    access_log  logs/www.sung.cn.access.log  main;
	
	#配置发布目录为/
	#定义服务器的默认网站根目录位置
    root  /root;
	
	 #默认请求
    location / {
         proxy_next_upstream http_502 http_504 error timeout invalid_header;
         proxy_set_header Host  $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_pass http://tdt_sung;
         expires      3d;
    }
	
	#动态页面交给http://tdt_sung,也即我们之前在nginx.conf定义的upstream tdt_sung 均衡
    location ~ .*\.(do|jsp)?$ {
         proxy_set_header Host  $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_pass http://tdt_sung;
    }
	#配置Nginx动静分离,定义的静态页面直接从Nginx发布目录读取。
   location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
    {
		root data;
		#expires定义用户浏览器缓存的时间为3天,如果静态页面不常更新,可以设置更长,这样可以节省带宽和缓解服务器的压力
		expires      3d;
    }
	#定义Nginx输出日志的路径
	access_log  logs/nginx_sung/access.log main;
    error_log   logs/nginx_sung/error.log  crit;
	
}

  #server {
    #listen       80;
    #server_name  chinaapp.sinaapp.com;
    #index index.html index.htm;
    #root  /data/www;
    #location / {
       #  proxy_next_upstream http_502 http_504 error timeout invalid_header;
       #  proxy_set_header Host  $host;
       #  proxy_set_header X-Real-IP $remote_addr;
	   #  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       #  proxy_pass http://tdt_app;
       #  expires      3d;
    #}
    #location ~ .*\.(php|jsp|cgi)?$ {
     #    proxy_set_header Host  $host;
     #    proxy_set_header X-Real-IP $remote_addr;
     #    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     #    proxy_pass http://tdt_app;
   # }
   # location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$
   # {
   # root /data/www/app;
   # expires      3d;
   # }
   # access_log  /data/logs/nginx_app/access.log main;
   # error_log   /data/logs/nginx_app/error.log  crit;
#}
Linux 安装 oracle 11g linux
//检查软件需求,没有的yum install安装 
rpm -q binutils compat-libstdc++-33 elfutils-libelf elfutils-libelf-devel glibc glibc-common glibc-devel gcc- gcc-c++ libaio-devel libaio libgcc libstdc++ libstdc++-devel make sysstat unixODBC unixODBC-devel pdksh
Global site tag (gtag.js) - Google Analytics