`
cheneyph
  • 浏览: 292651 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
java常用收集 java

WindowBuilder:
http://www.eclipse.org/windowbuilder/download.php
获取本机ip等信息 java
InetAddress ia = null;
ia = InetAddress.getLocalHost();
String localname = ia.getHostName();
String localip = ia.getHostAddress();
System.out.println("本机名称是:" + localname);
System.out.println("本机的ip是 :" + localip);

【POI】excel操作 java
/*
maven 依赖:
	<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi</artifactId>
		<version>3.11</version>
	</dependency>
	<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi-ooxml</artifactId>
		<version>3.11</version>
	</dependency>

http://lxneliu.iteye.com/blog/1614148
http://my.oschina.net/zhanglikun/blog/130147
*/
【zxing】条形码、二维码 java
/**
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.2.1</version>
</dependency>
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>javase</artifactId>
	<version>3.2.1</version>
</dependency>
*/

/**
 * http://www.cnblogs.com/hongten/archive/2012/10/26/java_qrcode.html
 * http://blog.csdn.net/yiluoak_47/article/details/22808915
 * @author cheney
 */
public class QRCodeTest extends TestCase {
	
	private static final int BLACK = 0xff000000;
	private static final int WHITE = 0xFFFFFFFF;

	@Test
	public void testBarCode() {
		// bar code
		String imgPath = "e:/123.jpg";
		String contents = "6943620593115";
		int width = 105, height = 50;
		encodeBarCode(contents, width, height, imgPath);

		String decodeContent = decodeBarCode(imgPath);
		System.out.println("解码内容如下:");
		System.out.println(decodeContent);
	}
	
	private void encodeBarCode(String contents, int width, int height, String imgPath) {
		int codeWidth = 3 + // start guard
				(7 * 6) + // left bars
				5 + // middle guard
				(7 * 6) + // right bars
				3; // end guard
		codeWidth = Math.max(codeWidth, width);
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
					BarcodeFormat.EAN_13, codeWidth, height, null);

			Path path = new File(imgPath).toPath();
			MatrixToImageWriter.writeToPath(bitMatrix, "png", path);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String decodeBarCode(String imgPath) {
		BufferedImage image = null;
		Result result = null;
		try {
			image = ImageIO.read(new File(imgPath));
			if (image == null) {
				System.out.println("the decode image may be not exit.");
			}
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

			result = new MultiFormatReader().decode(bitmap, null);
			return result.getText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@Test
	public void testQRCode() {
		// QRCode
		String content = "helloworld. Welcome to my zone:http://www.cnblogs.com/my";
		File file = new File("e://test.png");
		this.encodeQRCode(content, file, BarcodeFormat.QR_CODE, 200, 200, null);
		this.decodeQRCode(file);
	}
	
	/**
	 * 生成QRCode二维码<br>
	 * 在编码时需要将com.google.zxing.qrcode.encoder.Encoder.java中的<br>
	 * static final String DEFAULT_BYTE_MODE_ENCODING = "ISO8859-1";<br>
	 * 修改为UTF-8,否则中文编译后解析不了<br>
	 */
	private void encodeQRCode(String contents, File file, BarcodeFormat format,
			int width, int height, Map<EncodeHintType, ?> hints) {
		try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
					format, width, height);
			writeToFile(bitMatrix, "png", file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	     
	/**
	 * 生成二维码图片<br>
	 * 
	 * @param matrix
	 * @param format
	 *            图片格式
	 * @param file
	 *            生成二维码图片位置
	 * @throws IOException
	 */
	private void writeToFile(BitMatrix matrix, String format, File file)
			throws IOException {
		BufferedImage image = toBufferedImage(matrix);
		ImageIO.write(image, format, file);
	}
	      
	/**
	 * 生成二维码内容<br>
	 * @param matrix
	 * @return
	 */
	private BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_ARGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
			}
		}
		return image;
	}
	          
	/**
	 * 解析QRCode二维码
	 */
	@SuppressWarnings("unchecked")
	private void decodeQRCode(File file) {
		try {
			BufferedImage image;
			try {
				image = ImageIO.read(file);
				if (image == null) {
					System.out.println("Could not decode image");
				}
				LuminanceSource source = new BufferedImageLuminanceSource(image);
				BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
						source));
				Result result;
				@SuppressWarnings("rawtypes")
				Hashtable hints = new Hashtable();
				// 解码设置编码方式为:utf-8
				hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
				result = new MultiFormatReader().decode(bitmap, hints);
				String resultStr = result.getText();
				System.out.println("解析后内容:" + resultStr);
			} catch (IOException ioe) {
				System.out.println(ioe.toString());
			} catch (ReaderException re) {
				System.out.println(re.toString());
			}
		} catch (Exception ex) {
			System.out.println(ex.toString());
		}
	}
}
txt大文件读写 java
/**
 * 
 */
package com.cignacmb.test.txt;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import junit.framework.TestCase;

import org.junit.Test;

/**
 * @author cheney
 *
 */
public class TxtUtilsTest extends TestCase{

	private String filePath = "D:\\temp\\big-file-test.txt";
	
	private String line = "通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可";

	private long Times = 10000 * 1000;
	private String encoding = "UTF-8";
	
	/**
	 * 		testWrite 		 testWriteByFileOutputStream
	 * CPU: 占用很小,1~10%		  占用很大,45%
	 * 内存:  占用很大,可能上百M	 占用很小,可能不到10M
	 * 效率: 是10倍			 很慢
	 * 
	 * 此方式性能可超过testWriteByFileOutputStream的10倍;
	 * 如百万数据写及:
	 * testWrite:1759 ms
	 * testWriteByFileOutputStream: 23802 ms
	 */
	@Test
	public void testWrite() {
		this.checkFile();
		long startTime = System.currentTimeMillis();
		BufferedWriter fw = null;
		try {
			File file = new File(filePath);
			fw = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file, true), encoding)); // 指定编码格式,以免读取时中文字符异常
//			fw.append("我写入的内容");
			for (int i = 0; i < Times; i++) {
				fw.append(i + " >> ");
				fw.append(line);
				fw.newLine();
			}
			fw.append("我又写入的内容");
			fw.flush(); // 全部写入缓存中的内容
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + " ms");
		}
	}
	
	@Test
	public void testWriteByFileOutputStream() {
		this.checkFile();
		long startTime = System.currentTimeMillis();
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(filePath);
			for (int i = 0; i < Times; i++) {
				fos.write(new String(i + " >> ").getBytes(encoding));
				fos.write(line.getBytes(encoding));
				fos.write(new String("\r\n").getBytes(encoding));
			}
			fos.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(null != fos){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + " ms");
		}
	}
	
	private void checkFile(){
		File file1 = new File(filePath);
		if (file1.exists()) {
			file1.deleteOnExit();
		}
		if (file1.exists() == false) {
			File parentFile = file1.getParentFile();
			if (parentFile.exists() == false) {
				parentFile.mkdirs();
			}
		}
	}
	
	@Test
	public void testReadByLine() {
		long startTime = System.currentTimeMillis();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(filePath), encoding)); // 指定读取文件的编码格式,要和写入的格式一致,以免出现中文乱码,
			String str = null;
			while ((str = reader.readLine()) != null) {
				// 日志输出很影响性能
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + " ms");
		}
	}
}
【TAG】自定义标签与spring mvc java 自定义标签与spring注入
maven 依赖
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>${spring.version}</version>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>servlet-api</artifactId>
	<version>2.4</version>
	<scope>provided</scope>
</dependency>
<dependency>
	<groupId>javax.servlet.jsp</groupId>
	<artifactId>jsp-api</artifactId>
	<version>2.2</version>
	<scope>provided</scope>
</dependency>


/**
 * 自定义标签基础类
 * @author cheney
 */
public abstract class BaseTag extends RequestContextAwareTag {

	private static final long serialVersionUID = 1L;
	
	protected Logger logger = Logger.getLogger(getClass());

	/**
	 * 根据ID获取指定的spring bean
	 * @param beanId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected <T> T getBean(String beanId) {
		WebApplicationContext context = this.getRequestContext()
				.getWebApplicationContext();
		T bean = null;
		if (null != context && context.containsBean(beanId)) {
			bean = (T) context.getBean(beanId);
		}
		return bean;
	}
}


public class PolicySeekTag extends BaseTag {

	private static final long serialVersionUID = 1L;

	@Override
	protected int doStartTagInternal() throws Exception {
		logger.info("session ID: " + pageContext.getSession().getId());
		
		TagsService tagsService = super.getBean("tagsService");
		tagsService.log();
		
		JspWriter out = null;
		try {
			out = pageContext.getOut();
			out.print("测试");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		
		return EVAL_PAGE; // 表示处理完标签后继续执行以下的JSP网页    
        // return SKIP_PAGE; //表示不处理接下来的JSP网页   
	}
}




// 在Web-Inf创建标签库描述文件self.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
	<tlib-version>1.0</tlib-version>
	<jsp-version>2.2</jsp-version>
	<short-name>self</short-name>
	<uri>/selftaglib</uri>
	<tag>
		<name>policySeek</name>
		<tag-class>com.cignacmb.liscont.tags.PolicySeekTag</tag-class>
		<body-content>empty</body-content>
	</tag>
</taglib>

// web.xml
	<jsp-config>
		<taglib>
			<taglib-uri>/selftaglib</taglib-uri>
			<taglib-location>/WEB-INF/self.tld</taglib-location>
		</taglib>
	</jsp-config>

// jsp
<%@ taglib uri="/selftaglib" prefix="self"%>
<td><self:policySeek></self:policySeek></td>
【DFA】敏感词过滤 - demo2 java
/**
 * 
 */
package com.cignacmb.jdk8.features.dfa;

import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;
import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;

import com.sun.istack.internal.logging.Logger;

/**
 * 参考:http://blog.csdn.net/chenssy/article/details/26961957 
 * 也可考虑使用:if (text.toLowerCase().contains(key))
 * @author cheney
 * @date 2015年8月8日 下午1:12:21
 */
public class DFATest2 extends TestCase {
	
	private Logger logger = Logger.getLogger(getClass());
	
	public void test2(){
		List<String> keyWordList = this.getKeyWordList();
		
		long start1 = System.currentTimeMillis();
		Node sensitiveWordNode = this.addSensitiveWordToHashMap(keyWordList);
		long end1 = System.currentTimeMillis();
		logger.info("生成敏感词库耗时:" + (end1 - start1));
		
//		logger.info(JSONObject.fromObject(sensitiveWordNode).toString());
		
		long start2, end2;
		List<String> checkSensitiveWordList = this.getCheckSensitiveWordList();
		for (String text : checkSensitiveWordList) {
			start2 = System.currentTimeMillis();
			List<String> sensitiveWordContains = this.checkSensitiveWord(text.toLowerCase(), sensitiveWordNode);
			end2 = System.currentTimeMillis();
			logger.info("deal word: " + text);
			logger.info("包含的敏感词条: " + JSONArray.fromObject(sensitiveWordContains));
			logger.info("匹配耗时:" + (end2 - start2));
		}
	}

	public void test3(){
		List<String> keyWordList = this.getKeyWordList();
		List<String> checkSensitiveWordList = this.getCheckSensitiveWordList();
		
		List<String> sensitiveWordContains = null;
		long start, end, start1, end1;
		start = System.currentTimeMillis();
		for (String text : checkSensitiveWordList) {
			start1 = System.currentTimeMillis();
			sensitiveWordContains = new ArrayList<String>();
			for (String key : keyWordList) {
				if (text.toLowerCase().contains(key)) {
					sensitiveWordContains.add(key);
				}
			}
			end1 = System.currentTimeMillis();
			logger.info("deal word: " + text);
			logger.info("包含的敏感词条: " + JSONArray.fromObject(sensitiveWordContains));
			logger.info("匹配耗时:" + (end1 - start1));
		}
		end = System.currentTimeMillis();
		logger.info("匹配总耗时:" + (end - start));
	}
	
	/**
	 * 从数据库中提取配置的敏感词条
	 * @return
	 */
	private List<String> getKeyWordList(){
		List<String> keyWordList = new ArrayList<String>();
		keyWordList.add("中国");
		keyWordList.add("中间人");
		keyWordList.add("中国人民");
		keyWordList.add("中国男人");
		keyWordList.add("五星红旗");
		keyWordList.add("?");
		keyWordList.add("test");
		keyWordList.add("?");
		keyWordList.add("ces");
		return keyWordList;
	}
	
	/**
	 * 需判断是否包含第三词条的文本
	 * @return
	 */
	private List<String> getCheckSensitiveWordList(){
		List<String> keyWordList = new ArrayList<String>();
		keyWordList.add("中国政府网是政府面向社会的窗口是公众与政府互动的渠道,是中国国务院和国务院各部门,以及各省、自治区、直辖市人民政府在国际互联网上发布政府信息和提供在线服务的综");
		keyWordList.add("地fd?sf");
		keyWordList.add("wdfTESTsdf");
		keyWordList.add("df?不舒服");
		return keyWordList;
	}
	
	/**
	 * 构建敏感词库
	 * @param keyWordList 从数据库中提取配置的敏感词条
	 * @return
	 */
	private Node addSensitiveWordToHashMap(List<String> keyWordList) {
		if (null == keyWordList) {
			return null;
		}
		// 虚拟敏感词库空节点
		Node rootNode = new Node();
		
		Node curNode = null;
		String nodeValue = null;
		Node tempNode = null;
		for (String key : keyWordList) {
			if (StringUtils.isBlank(key)) {
				continue;
			}
			curNode = rootNode;
			for (int i = 0; i < key.length(); i++) {
				nodeValue = String.valueOf(key.charAt(i));
				tempNode = null;
				if (i == key.length() - 1) {
					tempNode = new Node(String.valueOf(nodeValue), true);
				} else {
					tempNode = new Node(String.valueOf(nodeValue));
				}
				curNode = curNode.addChild(tempNode);
			}
		}
		return rootNode;
	}
	
	/**
	 * 检查文字中是否包含敏感词条
	 * @param text
	 * @param sensitiveWordMap
	 * @return
	 *   返回文本中包含的所有第三词条
	 */
	private List<String> checkSensitiveWord(String text, Node node){
		if (StringUtils.isBlank(text)) {
			return null;
		}
		List<String> sensitiveWordContains = new ArrayList<String>();
		for (int i = 0; i < text.length(); i++) {
			for (Node node2 : node.getChildren()) {
				if (String.valueOf(text.charAt(i)).equals(node2.getValue())) {
					if (node2.isEnd()) {
						sensitiveWordContains.add(node2.getWord());
					} else if(text.length() > 1) {
						sensitiveWordContains.addAll(this.check(text.substring(i + 1), node.getChildren()));
					}
				}
			}
		}
		return sensitiveWordContains;
	}
	
	private List<String> check(String text, List<Node> list){
		List<String> sensitiveWordContains = new ArrayList<String>();
		List<Node> tempNodeList = list;
		for (Node node : tempNodeList) {
			logger.info(String.format("char/node value = %s/ %s", String.valueOf(text.charAt(0)), node.getValue()));
			if (String.valueOf(text.charAt(0)).equals(node.getValue())) {
				if (node.isEnd()) {
					sensitiveWordContains.add(node.getWord());
				} else {
					if (text.length() > 1) {
						sensitiveWordContains.addAll(check(text.substring(1), node.getChildren()));
					}
				}
			}
		}
		return sensitiveWordContains;
	}
}
【DFA】敏感词过滤 - demo1 java
/**
 * 
 */
package com.cignacmb.jdk8.features.dfa;

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

import junit.framework.TestCase;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;

import com.sun.istack.internal.logging.Logger;

/**
 * 参考:http://blog.csdn.net/chenssy/article/details/26961957
 * @author cheney
 * @date 2015年8月8日 上午10:37:33
 */
public class DFATest extends TestCase {
	
	private Logger logger = Logger.getLogger(getClass());
	
	public void test1(){
		List<String> keyWordList = this.getKeyWordList();
		
		long start1 = System.currentTimeMillis();
		Map<String, Node> sensitiveWordMap = this.addSensitiveWordToHashMap(keyWordList);
		long end1 = System.currentTimeMillis();
		logger.info("生成敏感词库耗时:" + (end1 - start1));
		
		logger.info(JSONObject.fromObject(sensitiveWordMap).toString());
		
		List<String> checkSensitiveWordList = this.getCheckSensitiveWordList();
		
		long start2, end2;
		for (String text : checkSensitiveWordList) {
			start2 = System.currentTimeMillis();
			List<String> sensitiveWordContains = this.checkSensitiveWord(text.toLowerCase(), sensitiveWordMap);
			end2 = System.currentTimeMillis();
			logger.info("deal word: " + text);
			logger.info("包含的敏感词条: " + JSONArray.fromObject(sensitiveWordContains));
			logger.info("匹配耗时:" + (end2 - start2));
		}
	}
	
	/**
	 * 从数据库中提取配置的敏感词条
	 * @return
	 */
	private List<String> getKeyWordList(){
		List<String> keyWordList = new ArrayList<String>();
		keyWordList.add("中国");
		keyWordList.add("中间人");
		keyWordList.add("中国人民");
		keyWordList.add("中国男人");
		keyWordList.add("五星红旗");
		keyWordList.add("?");
		keyWordList.add("test");
		keyWordList.add("?");
		keyWordList.add("ces");
		return keyWordList;
	}
	
	/**
	 * 需判断是否包含第三词条的文本
	 * @return
	 */
	private List<String> getCheckSensitiveWordList(){
		List<String> keyWordList = new ArrayList<String>();
		keyWordList.add("中国政府网是政府面向社会的窗口是公众与政府互动的渠道,是中fs国国务院和国务院各部门,以及各省、自治区、直辖市人民政府在国际互联网上发布政府信息和提供在线服务的综");
		keyWordList.add("地fd?sf");
		keyWordList.add("wdfTESTsdf");
		keyWordList.add("df?不舒服");
		return keyWordList;
	}
	
	/**
	 * 构建敏感词库
	 * @param keyWordList 从数据库中提取配置的敏感词条
	 * @return
	 */
	private Map<String, Node> addSensitiveWordToHashMap(List<String> keyWordList) {
		if (null == keyWordList) {
			return null;
		}
		// 初始化敏感词容器,减少扩容操作
		Map<String, Node> sensitiveWordMap = new HashMap<String, Node>(keyWordList.size());
		
		Node firstFloorNode = null;
		for (String key : keyWordList) {
			if (StringUtils.isBlank(key)) {
				continue;
			}
			char firstFloorKeyChar = key.charAt(0);
			String firstFloorKey = String.valueOf(firstFloorKeyChar);
			firstFloorNode = sensitiveWordMap.get(firstFloorKey);
			if(null == firstFloorNode){
				firstFloorNode = new Node(firstFloorKey);
			}
			
			if (key.length() == 1) {
				firstFloorNode.setEnd(true);
			} else {
				Node curNode = firstFloorNode;
				for (int i = 1; i < key.length(); i++) {
					Node node = null;
					if (i == key.length() - 1) {
						node = new Node(String.valueOf(key.charAt(i)), true);
					} else {
						node = new Node(String.valueOf(key.charAt(i)));
					}
					curNode = curNode.addChild(node);
				}
			}
			sensitiveWordMap.put(firstFloorKey, firstFloorNode);
		}
		return sensitiveWordMap;
	}
	
	/**
	 * 检查文字中是否包含敏感词条
	 * @param text
	 * @param sensitiveWordMap
	 * @return
	 *   返回文本中包含的所有第三词条
	 */
	private List<String> checkSensitiveWord(String text, Map<String, Node> sensitiveWordMap){
		List<String> sensitiveWordContains = null;
		if (StringUtils.isBlank(text)) {
			return sensitiveWordContains;
		}
		sensitiveWordContains = new ArrayList<String>();
		for (int i = 0; i < text.length(); i++) {
			String key = String.valueOf(text.charAt(i));
			Node node = sensitiveWordMap.get(key);
			if (null == node) {
				continue;
			}
			if(node.isEnd()){
				// 已匹配上
//				logger.info("1-已匹配上敏感词条: " + node.getWord());
				sensitiveWordContains.add(node.getWord());
				break;
			}
			sensitiveWordContains.addAll(this.check(text.substring(i+1), node.getChildren()));
		}
		return sensitiveWordContains;
	}
	
	private List<String> check(String text, List<Node> list){
		List<String> sensitiveWordContains = new ArrayList<String>();
		List<Node> tempNodeList = list;
		for (Node node : tempNodeList) {
			if (String.valueOf(text.charAt(0)).equals(node.getValue())) {
				if (node.isEnd()) {
					sensitiveWordContains.add(node.getWord());
					// return sensitiveWordContains;
				} else {
					if (text.length() > 1) {
						sensitiveWordContains.addAll(check(text.substring(1), node.getChildren()));
					}
				}
			}
		}
		return sensitiveWordContains;
	}
}



/******************************************************************************************/

/**
 * 
 */
package com.cignacmb.jdk8.features.dfa;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * @author cheney
 * @date 2015年8月8日 上午11:41:02
 */
public class Node {

	private String value = null;
	private boolean end = false;
	private List<Node> children = new ArrayList<Node>();
	/**
	 * 到当前节点时,敏感词条内容
	 */
	private StringBuffer buffer = new StringBuffer();

	public Node() {
	}

	public Node(String value) {
		this.value = value;
	}

	public Node(String value, boolean end) {
		this.value = value;
		this.end = end;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public boolean isEnd() {
		return end;
	}

	public void setEnd(boolean end) {
		this.end = end;
	}

	public List<Node> getChildren() {
		return children;
	}

	public StringBuffer getBuffer() {
		if (StringUtils.isBlank(this.buffer.toString())) {
			if (StringUtils.isNotBlank(this.getValue())) {
				buffer.append(this.getValue());
			}
		}
		return buffer;
	}

	public void setBuffer(StringBuffer buffer) {
		this.buffer = buffer;
	}
	
	public String getWord() {
		if (StringUtils.isBlank(this.buffer.toString())) {
			if (StringUtils.isNotBlank(this.getValue())) {
				buffer.append(this.getValue());
			}
		}
		return this.buffer.toString();
	}

	/**
	 * @param child
	 * @return
	 *  返回当前添加的节点
	 */
	public Node addChild(Node child) {
		for (int i = 0; i < children.size(); i++) {
			if (children.get(i).getValue().equals(child.getValue())) {
				if (child.isEnd()) {
					children.get(i).setEnd(true);
				}
				return children.get(i);
			}
		}
		StringBuffer bufferTemp = new StringBuffer();
		bufferTemp.append(this.getBuffer());
		bufferTemp.append(child.getValue());
		child.setBuffer(bufferTemp);
		this.children.add(child);
		return child;
	}

}
Bean Validation java
Bean Validation技术实现对Javabean的校验
http://henu-zhangyang.iteye.com/blog/2231893

Spring3.1 对Bean Validation规范的新支持(方法级别验证)
http://jinnianshilongnian.iteye.com/blog/1495594

Spring4新特性——集成Bean Validation 1.1(JSR-349)到SpringMVC
http://jinnianshilongnian.iteye.com/blog/1990081
【excel】xssf and sax (event api) java The New Halloween Document
public class POITest extends TestCase {

	String path = "D:\\code\\cigna\\lis\\sorcecode\\ui\\banktest\\PMLE001(招商信诺永享康健两全保险)\\RATE_PMLE001_PMLE001298_1.xlsx";
	
	public void testXSSFSaxAPI() throws IOException, OpenXML4JException,
			SAXException {
		OPCPackage pkg = OPCPackage.open(path);
		XSSFReader r = new XSSFReader(pkg);
		SharedStringsTable sst = r.getSharedStringsTable();

		XMLReader parser = XMLReaderFactory
				.createXMLReader("org.apache.xerces.parsers.SAXParser");
		RateCVDataHandler handler = new RateCVDataHandler(sst);
		parser.setContentHandler(handler);

		Iterator<InputStream> sheets = r.getSheetsData();
		while (sheets.hasNext()) {
			System.out.println("Processing new sheet:\n");
			InputStream sheet = sheets.next();
			InputSource sheetSource = new InputSource(sheet);
			parser.parse(sheetSource);
			sheet.close();
//			System.out.println("");
			break;
		}
		List<List<String>> rows = handler.getRows();
		if (null == rows) {
			System.out.println("null ....");
		} else {
			for (List<String> list : rows) {
				for (String string : list) {
					System.out.print(string + "\t");
				}
				System.out.println();
			}
		}
	}

}


/*********************************************************************/
/*********************************************************************/
/*********************************************************************/
/**
 * 
 */
package com.cignacmb.productdef.converter;

import java.util.LinkedList;
import java.util.List;

import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 参考:<br>
 * 解决POI读取Excel内存溢出的问题<br>
 * http://blog.csdn.net/lishengbo/article/details/40711769<br>
 * <br>
 * The New Halloween Document<br>
 * http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api<br>
 * @author c1panx
 * @ 2015年6月25日  下午4:43:33
 */
public class RateCVDataHandler extends DefaultHandler {

	private SharedStringsTable sst;
	private boolean nextIsString;
	private String lastContents;
	
	/** 临时保留行记录 */
	private List<String> record = null;
	/** 所有记录 */
	private List<List<String>> rows = null;

	public RateCVDataHandler(SharedStringsTable sst){
		this.sst = sst;
		record = new LinkedList<String>();
		rows = new LinkedList<List<String>>();
	}

	public void startElement(String uri, String localName, String name,
			Attributes attributes) throws SAXException {
		// c => cell
		if (name.equals("c")) {
			String cellType = attributes.getValue("t");
			if ("s".equals(cellType)) {
				nextIsString = true;
			} else {
				nextIsString = false;
			}
		}
		// Clear contents cache
		lastContents = "";
	}
	
	public void endElement(String uri, String localName, String name)
			throws SAXException {
		if(nextIsString) {
			int idx = Integer.parseInt(lastContents);
			lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
			nextIsString = false;
		}
		// v => contents of a cell
		// Output after we've seen the string contents
		if(name.equals("v")) {
//			System.out.print(lastContents + "\t");
			record.add(lastContents);
		}
		if ("row".equals(name)) {
			rows.add(record);
			record = new LinkedList<String>();
//			System.out.println();
		}
	}
	
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		lastContents += new String(ch, start, length);
	}
	
	public List<List<String>> getRows() {
		return rows;
	}
}
【xstream】属性及注解 java
	public void testXStreamDBTypeMapContext(){
		DBTypeMapContext typeMapContext = new DBTypeMapContext();
		typeMapContext.setDbtype("oracle");
		
		List<DBTypeMapModel> list = new ArrayList<DBTypeMapModel>();
		for (int i = 0; i < 4; i++) {
			DBTypeMapModel dbTypeMapModel = new DBTypeMapModel();
			dbTypeMapModel.setJdbcType("CHAR");
			dbTypeMapModel.setJavaType("java.lang.String");
			dbTypeMapModel.setPattern("fdafd");
			list.add(dbTypeMapModel);
		}
		typeMapContext.setList(list);
		
		List<DBTypeMapContext> contextList = new ArrayList<DBTypeMapContext>();
		contextList.add(typeMapContext);
		
		XStream xStream = new XStream();
		xStream.registerConverter(new DBTypeMapContextConverter());
		xStream.alias("typemap", List.class);
		xStream.alias("context", DBTypeMapContext.class);
		
		System.out.println(xStream.toXML(contextList));

		Object obj = xStream.fromXML(getClass().getResourceAsStream("/system-config/dbtype-map.xml"));
		System.out.println(obj);
		
		@SuppressWarnings("unchecked")
		List<DBTypeMapContext> contextList2 = (List<DBTypeMapContext>) obj;
		System.out.println(xStream.toXML(contextList2));
	}


/***********************************************************************************
 * 
 **********************************************************************************/
package com.cignacmb.productdef.converter;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.cignacmb.productdef.model.DBTypeMapContext;
import com.cignacmb.productdef.model.DBTypeMapModel;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * XStream  DBTypeMapContext自定义转换器
 * @author c1panx
 * @ 2015年6月19日  下午5:33:32
 */
public class DBTypeMapContextConverter implements Converter {
	
	private Logger logger = Logger.getLogger(getClass());

	@Override
	@SuppressWarnings("rawtypes")
	public boolean canConvert(Class clazz) {
		return clazz.equals(DBTypeMapContext.class);
	}

	@Override
	public void marshal(Object obj, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		logger.debug("Object obj: " + obj);
		if (obj instanceof DBTypeMapContext == false) {
			return;
		}
		DBTypeMapContext typeMapContext = (DBTypeMapContext) obj;
		writer.addAttribute("dbtype", typeMapContext.getDbtype());
		
		List<DBTypeMapModel> list = typeMapContext.getList();
		if (null != list) {
			for (DBTypeMapModel dbTypeMapModel : list) {
				writer.startNode("item");
				writer.addAttribute("jdbcType", dbTypeMapModel.getJdbcType());
				writer.addAttribute("javaType", dbTypeMapModel.getJavaType());
				if (StringUtils.isNotBlank(dbTypeMapModel.getPattern())) {
					writer.addAttribute("pattern", dbTypeMapModel.getPattern());
				}
				writer.endNode();
			}
		}
	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		logger.debug("start unmarshal ... ");
		DBTypeMapContext typeMapContext = new DBTypeMapContext();
		typeMapContext.setDbtype(trim(reader.getAttribute("dbtype")));

		List<DBTypeMapModel> list = new ArrayList<DBTypeMapModel>();
		while (reader.hasMoreChildren()) {
			reader.moveDown();
			DBTypeMapModel typeMapModel = new DBTypeMapModel();
			typeMapModel.setJdbcType(trim(reader.getAttribute("jdbcType")));
			typeMapModel.setJavaType(trim(reader.getAttribute("javaType")));
			typeMapModel.setPattern(trim(reader.getAttribute("pattern")));
			list.add(typeMapModel);
			reader.moveUp();
		}
		typeMapContext.setList(list);
		logger.debug("end unmarshal ... ");
		return typeMapContext;
	}
	
	private String trim(String value) {
		return null == value ? null : value.trim();
	}
	
}




/***********************************************************************************
 * 
 **********************************************************************************/
package com.cignacmb.productdef.model;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * jdbcType && javaType映射关系上下文件,针对特定类型的数据库
 * @author c1panx
 * @ 2015年6月19日  下午5:20:17
 */
public class DBTypeMapContext {

	private String dbtype;
	private List<DBTypeMapModel> list;

	public String getDbtype() {
		return dbtype;
	}

	public void setDbtype(String dbtype) {
		this.dbtype = dbtype;
	}

	public List<DBTypeMapModel> getList() {
		return list;
	}

	public void setList(List<DBTypeMapModel> list) {
		this.list = list;
	}
	
	public DBTypeMapModel getTypeMap(String jdbcType) {
		if (StringUtils.isBlank(jdbcType) || null == list) {
			return null;
		}
		for (DBTypeMapModel dbTypeMapModel : list) {
			if (jdbcType.equalsIgnoreCase(dbTypeMapModel.getJdbcType())) {
				return dbTypeMapModel;
			}
		}
		return null;
	}

}


/***********************************************************************************
 * 
 **********************************************************************************/
package com.cignacmb.productdef.model;


/**
 * jdbcType && javaType映射关系
 * @author c1panx
 * @ 2015年6月19日  下午5:12:37
 */
public class DBTypeMapModel {

	private String jdbcType;
	private String javaType;
	private String pattern;

	public String getJdbcType() {
		return jdbcType;
	}

	public void setJdbcType(String jdbcType) {
		this.jdbcType = jdbcType;
	}

	public String getJavaType() {
		return javaType;
	}

	public void setJavaType(String javaType) {
		this.javaType = javaType;
	}

	public String getPattern() {
		return pattern;
	}

	public void setPattern(String pattern) {
		this.pattern = pattern;
	}

}


/***********************************************************************************
 * dbtype-map.xml
 **********************************************************************************/
<?xml version="1.0" encoding="UTF-8"?>
<typemap>
	<context dbtype="oracle">
		<item jdbcType="CHAR" javaType="java.lang.String" pattern="123"/>
		<item jdbcType="VARCHAR2" javaType="java.lang.String" pattern="dfaf"/>
	</context>
</typemap>
【BeanUtils】 java
<dependency>
	<groupId>commons-beanutils</groupId>
	<artifactId>commons-beanutils</artifactId>
	<version>1.8.3</version>
</dependency>


BeanUtils包的使用
http://www.cnblogs.com/H_Razor/archive/2011/03/01/1967620.html



spring的BeanUtils.copyProperties用法
http://blog.csdn.net/shimiso/article/details/5644584
BeanUtils所花费的时间要超过取数 据、将其复制到对应的 value对象(通过手动调用get和set方法),以及通过串行化将其返回到远程的客户机的时间总和。所以要小心使用这种威力!
【Dozer】 java
DozerBeanMapper + 对象转Map方法
http://uule.iteye.com/blog/2084016


/**
dozer与maven的集成
<dependency>  
    <groupId>net.sf.dozer</groupId>  
    <artifactId>dozer</artifactId>  
    <version>5.0</version>  
</dependency> 

dozer spring
<bean id="beanMapper" class="org.dozer.spring.DozerBeanMapperFactoryBean">
    <property name="mappingFiles" value="classpath*:com/cignacmb/dozer/dozer-*.xml" />
</bean>

dozer-bean-mappings.xml
<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://dozer.sourceforge.net  
          http://dozer.sourceforge.net/schema/beanmapping.xsd">
	<mapping>
		<class-a>com.cignacmb.productdef.dozer.User</class-a>
		<class-b>com.cignacmb.productdef.dozer.Customer</class-b>
		<field>
			<a>userId</a>
			<b>customerId</b>
		</field>
		<field>
			<a>userName</a>
			<b>customerName</b>
		</field>
	</mapping>
</mappings>  
 */

public class DozerTest extends AbstractJUnit4Test {

	@Resource
	private DozerBeanMapper beanMapper;
	
	@Test
	public void testMap() {
		User user = new User(1, "user1");
		Customer customer = beanMapper.map(user, Customer.class);
		System.out.println("@> CustomerId = " + customer.getCustomerId());
		System.out.println("@> CustomerName = " + customer.getCustomerName());
		Assert.assertEquals(customer.getCustomerId(), 1);
		Assert.assertEquals(customer.getCustomerName(), "user1");
	}
}
【TODO】XML Schema校验XML java
Java 语言的 XML 验证 API
http://www.ibm.com/developerworks/cn/xml/x-javaxmlvalidapi.html

Java通过XML Schema校验XML
http://lavasoft.blog.51cto.com/62575/97597/
【JSON】 JsonConfig java
JSONObject tJSON = JSONObject.fromObject(model, getJsonConfig());

public static JsonConfig getJsonConfig(){
	JsonConfig jsonConfig = new JsonConfig();  
	jsonConfig.registerJsonValueProcessor(java.sql.Date.class, new JsonSQLDateValueProcessor());
	jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsonUtilDateValueProcessor());
	return jsonConfig;
}

/**************************************************************************************/ 

/**
 * 
 */
package com.cignacmb.productdef.converter;

import java.text.SimpleDateFormat;
import java.util.Locale;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import com.cignacmb.productdef.util.Tools;

/**
 * java.sql.Date转JSON对象时日期转换<br>
 * 如将Date转换为“yyyy-MM-dd”格式
 * @author c1panx
 * @ 2015年5月28日  下午5:56:25
 */
public class JsonSQLDateValueProcessor implements JsonValueProcessor {

	private String format = "yyyy-MM-dd";

	public JsonSQLDateValueProcessor() {
		super();
	}

	public JsonSQLDateValueProcessor(String format) {
		super();
		this.format = format;
	}

	@Override
	public Object processArrayValue(Object paramObject,
			JsonConfig paramJsonConfig) {
		return process(paramObject);
	}

	@Override
	public Object processObjectValue(String paramString, Object paramObject,
			JsonConfig paramJsonConfig) {
		return process(paramObject);
	}

	private Object process(Object value) {
		if (null == value) {
			return "";
		}
		if (value instanceof java.sql.Date) {
			java.sql.Date sqlDate = (java.sql.Date) value;
			java.util.Date date = Tools.sqlDateToUtilDate(sqlDate);

			SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
			return sdf.format(date);
		}
		return value;
	}
}

/**************************************************************************************/ 

/**
 * 
 */
package com.cignacmb.productdef.converter;

import java.text.SimpleDateFormat;
import java.util.Locale;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

/**
 * java.util.Date转JSON对象时日期转换<br>
 * 如将Date转换为“yyyy-MM-dd ”格式
 * @author c1panx
 * @ 2015年5月28日  下午5:56:25
 */
public class JsonUtilDateValueProcessor implements JsonValueProcessor {

	private String format = "yyyy-MM-dd HH:mm:ss";

	public JsonUtilDateValueProcessor() {
		super();
	}

	public JsonUtilDateValueProcessor(String format) {
		super();
		this.format = format;
	}

	@Override
	public Object processArrayValue(Object paramObject,
			JsonConfig paramJsonConfig) {
		return process(paramObject);
	}

	@Override
	public Object processObjectValue(String paramString, Object paramObject,
			JsonConfig paramJsonConfig) {
		return process(paramObject);
	}

	private Object process(Object value) {
		if (null == value) {
			return null;
		}
		if (value instanceof java.util.Date) {
			java.util.Date date = (java.util.Date) value;
			SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
			return sdf.format(date);
		}
		return value;
	}
}
【MVEL】model属性操作 java
/**
<dependency>
	<groupId>org.mvel</groupId>
	<artifactId>mvel2</artifactId>
	<version>2.2.4.Final</version>
</dependency>
 */

import java.lang.reflect.Field;
import java.text.ParseException;
import java.util.Date;

import junit.framework.TestCase;

import org.apache.commons.lang3.time.DateUtils;
import org.mvel2.MVEL;

/**
 * @author c1panx
 * @ 2015年5月19日  上午11:46:38
 */
public class MVELTest extends TestCase {

	// 常用日期格式
	private final String[] pattern = new String[] { "yyyy-MM", "yyyyMM",
			"yyyy/MM", "yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd",
			"yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss",
			"yyyy-MM-dd HH:mm:ss.SSS" };
	
	public void testEval(){
		/**
		 *  1. MVEL属性区分大小写
		 *  2. 不存在的属性会抛异常
		 *  3. String可强制转换成数字
		 */
		MVELTestBean bean = new MVELTestBean();
		this.setFiledValue(bean, "id", "123");
		this.setFiledValue(bean, "name", "法是基");
//		this.setFiledValue(bean, "makedate", new Date());
		this.setFiledValue(bean, "makedate", "2015-05-19");
		this.setFiledValue(bean, "modifyDate", "法是基");

		System.out.println("result name: " + MVEL.eval("name", bean));
		System.out.println("result: " + MVEL.eval("name == null", bean));
		System.out.println("result id: " + this.getFiledValue(bean, "ID"));
		System.out.println("result makedate: " + this.getFiledValue(bean, "makedate"));
		System.out.println("@>> " + bean.toString());
	}
	
	/**
	 * 1. property与属性大小写不一致问题;
	 * 2. 日期字符串自动换成Date;
	 * @param obj  对象
	 * @param property 属性名
	 * @param value 设置成的值
	 */
	private void setFiledValue(Object obj, String property, Object value){
		if (null == obj) {
			return;
		}
		Field[] fields= obj.getClass().getDeclaredFields();
		if (null == fields) {
			return;
		}
		for (Field field : fields) {
			String fieldName = field.getName();
			if (fieldName.equalsIgnoreCase(property)) {
				// 日期字符串处理
				if (field.getType() == Date.class && null != value
						&& value.getClass() == String.class) {
					// 字符串转日期
					try {
						value = DateUtils.parseDate((String)value, pattern);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				MVEL.setProperty(obj, fieldName, value);
				break;
			}
		}
	}
	
	/**
	 * 获取属性值
	 * @param obj 对象
	 * @param property 属性名,不区分大小写
	 * @return
	 */
	private Object getFiledValue(Object obj, String property) {
		if (null == obj) {
			return null;
		}
		// 需考虑父类属性
		Field[] fields = obj.getClass().getDeclaredFields();
		if (null == fields) {
			return null;
		}
		for (Field field : fields) {
			String fieldName = field.getName();
			if (fieldName.equalsIgnoreCase(property)) {
				return MVEL.eval(fieldName, obj);
			}
		}
		return null;
	}
}



/**
 * @author c1panx
 * @ 2015年5月19日  上午11:46:54
 */
class MVELTestBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	private Integer id;
	private String name;
	private Date makeDate;

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Date getMakeDate() {
		return makeDate;
	}

	public void setMakeDate(Date makeDate) {
		this.makeDate = makeDate;
	}

	public String toString(){
		StringBuffer buffer = new StringBuffer();
		buffer.append(this.getClass().getSimpleName());
		buffer.append("{");
		buffer.append("id=" + this.id);
		buffer.append(", name=" + this.name);
		if(null == this.makeDate){
			buffer.append(", makeDate=" + null);
		} else {
			buffer.append(", makeDate=" + sdf.format(this.makeDate));	
		}
		buffer.append("}");
		return buffer.toString();
	}
}
【jsch】sftp 文件上传 java
/**
 * sftp 文件上传
 * 依赖:
 *		<dependency>
 *			<groupId>com.jcraft</groupId>
 *			<artifactId>jsch</artifactId>
 *			<version>0.1.50</version>
 *		</dependency>
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Properties;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

/**
 * @author c1panx
 * @ 2015年5月8日  下午4:12:28
 */
public class SFTPUtil {
	
	private static final Logger logger = Logger.getLogger(SFTPUtil.class);
	
	private static final String host = "10.140.130.50";
	private static final String username = "uat";
	private static final String password = "Aa123456";
	private static final String cdPath = "/home/uat/backup/temp";
	private static final String localPath = "D:\\LG\\jacob\\";
	
	private static final String separator = "/";

	public static void upload(){
		long startTime = System.currentTimeMillis();
		ChannelSftp sftp = null;
		Channel channel = null;
		try {
			JSch jsch = new JSch();
			Session sshSession = jsch.getSession(username, host);
			logger.debug("Session created.");
			
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			logger.debug("Session connected.");
			
			logger.debug("Opening Channel....");
			channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
			
			// 遍历上传
			File file = new File(localPath);
			logger.info("start cleart remote folder .....");
			clearRemoteFolder(sftp, cdPath, file);
			
			logger.info("==========================================");
			logger.info("start upload files .....");
			uploadFile(sftp, cdPath, file);
			
			channel.disconnect();
		} catch (JSchException e) {
			logger.error(e.getMessage(), e);
		} catch (SftpException e) {
			logger.error(e.getMessage(), e);
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (null != channel) {
				channel.disconnect();
			}
			if (null != sftp) {
				sftp.disconnect();
			}
			long endTime = System.currentTimeMillis();
			logger.info("diff time: " + (endTime - startTime));
		}
	}
	
	@SuppressWarnings("unchecked")
	private static void clearRemoteFolder(ChannelSftp sftp, String pwd,
			File file) throws SftpException {
		String childPwd = pwd + separator + file.getName();
		logger.debug("start rm remote file ...[" + childPwd + "]");

		boolean exists = false;
		Vector<LsEntry> v = sftp.ls(pwd);
		for (LsEntry lsEntry : v) {
			String fileName = lsEntry.getFilename();
			if (fileName.equalsIgnoreCase(file.getName())) {
				exists = true;
				break;
			}
		}
		
		if (exists == false) {
			logger.debug("[" + childPwd + "] does not exist.");
			return;
		}
		deleteFile(sftp, pwd, file.getName());
	}
	
	@SuppressWarnings("unchecked")
	private static void deleteFile(ChannelSftp sftp, String pwd, String delName)
			throws SftpException {
		String filePath = pwd + separator + delName;
		try {
			sftp.cd(filePath);
			Vector<LsEntry> v = sftp.ls(filePath);
			for (LsEntry lsEntry : v) {
				String fileName = lsEntry.getFilename();
				if (fileName.equals(".") || fileName.equals("..")) {
					continue;
				}
				deleteFile(sftp, filePath, fileName);
			}
			logger.debug("rm dir: " + filePath);
			sftp.rmdir(pwd + separator + delName);
		} catch (SftpException e) {
			// 删除文件
			logger.debug("rm file: " + filePath);
			sftp.rm(filePath);
		}
	}
	
	private static void uploadFile(ChannelSftp sftp, String pwd, File file)
			throws SftpException, FileNotFoundException {
		sftp.cd(pwd);
		if (file.isDirectory()) {
			String childPwd = pwd + separator + file.getName();
			logger.debug("mkdir: " + childPwd);
			sftp.mkdir(file.getName());
			
			sftp.cd(childPwd);
			File[] files = file.listFiles();
			for (File file2 : files) {
				uploadFile(sftp, childPwd, file2);
			}
		} else {
			logger.debug("upload file: " + file.getName());
			sftp.put(new FileInputStream(file), file.getName());
		}
	}
}
DES加密解密 java
源码:
/**
 * DES加密解密
 * 2014-12-9  下午1:29:01
 */
public class DESUtils {
	
	private static Logger logger = Logger.getLogger(DESUtils.class);

	private static final String DES_KEY = "badc";
	
	private static Key key = null;
	private static Cipher cipher;
	
	static {
		try {
			KeyGenerator _generator = KeyGenerator.getInstance("DES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
			secureRandom.setSeed(DES_KEY.getBytes());
			_generator.init(secureRandom);
			
			key = _generator.generateKey();  
	        
	        cipher = Cipher.getInstance("DES");  
		} catch (NoSuchAlgorithmException e) {
			logger.error("DESUtils NoSuchAlgorithmException", e);
		} catch (NoSuchPaddingException e) {
			logger.error("DESUtils NoSuchPaddingException", e);
		}
	}
	
	/**
	 * @param text
	 * @return
	 * @throws BusinessException  
	 */
	public static String encrypt(String text) throws BusinessException {
		try {
			cipher.init(Cipher.ENCRYPT_MODE,key);
			byte[] byteFina = cipher.doFinal(text.getBytes());
			
			return null == byteFina ? null : new Base64().encodeAsString(byteFina);
		} catch (InvalidKeyException e) {
			throw new BusinessException(e);
		} catch (IllegalBlockSizeException e) {
			throw new BusinessException(e);
		} catch (BadPaddingException e) {
			throw new BusinessException(e);
		}
	}
	
	/**
	 * @param text
	 * @return
	 * @throws BusinessException
	  */
	public static String decrypt(String text) throws BusinessException {
		try {
			cipher.init(Cipher.DECRYPT_MODE,key);
			byte[] byteMi = new Base64().decode(text);
			byte[] byteMing = cipher.doFinal(byteMi);
			return null == byteMing ? null : new String(byteMing);
		} catch (InvalidKeyException e) {
			throw new BusinessException(e);
		} catch (IllegalBlockSizeException e) {
			throw new BusinessException(e);
		} catch (BadPaddingException e) {
			throw new BusinessException(e);
		}
	}

}

maven依赖(用apache的Base64替换sun jdk里的):
		 <dependency>
		 	<groupId>commons-codec</groupId>
		 	<artifactId>commons-codec</artifactId>
		 	<version>1.10</version>
		 </dependency>

测试代码:
public class DESUtilsTest extends TestCase {

	public void testEncrypt() throws BusinessException {
		String str = "fdaeaf554629";

		long start = System.currentTimeMillis();
		String mi = DESUtils.encrypt(str);
		System.out.println("mi = " + mi);
		long end = System.currentTimeMillis();
		System.out.println("@> dif = " + (end - start));
		
		System.out.println("ming = " + DESUtils.decrypt(mi));
		System.out.println("@> dif = " + (System.currentTimeMillis() - end));
	}
}
Global site tag (gtag.js) - Google Analytics