import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
public class DESFile {
private static String type = "DES";
/**
* 加密文件
* @param encryptBeforeFile 加密前的文件
* @param encryptAfterFile 加密后的文件
* @param secret 加密密钥
* @throws Exception
*/
public static void encryptFile(String encryptBeforeFile, String encryptAfterFile,String secret) throws Exception {
Cipher cipher = Cipher.getInstance(type);
cipher.init(Cipher.ENCRYPT_MODE, getKey( secret));
InputStream is = new BufferedInputStream( new FileInputStream( encryptBeforeFile));
OutputStream out = null;
if(encryptAfterFile.isEmpty()){
out = new BufferedOutputStream(new FileOutputStream(new File(encryptAfterFile).getPath()));
}else{
out = new BufferedOutputStream( new FileOutputStream( encryptAfterFile));
}
CipherInputStream cis = new CipherInputStream(is, cipher);
byte[] buffer = new byte[10240];
int r = 0;
while ((r = cis.read(buffer)) != -1) {
out.write(buffer, 0, r);
}
cis.close();
is.close();
out.close();
}
/**
* 解密文件
* @param decryptBeforeFile 解密前的文件
* @param decryptAfterFile 解密后的文件
* @param secret 解密密钥
* @throws Exception
*/
public static void decryptFile(String decryptBeforeFile, String decryptAfterFile,String secret) throws Exception {
Cipher cipher = Cipher.getInstance(type);
cipher.init(Cipher.DECRYPT_MODE, getKey( secret));
InputStream is = new BufferedInputStream( new FileInputStream( decryptBeforeFile));
OutputStream out = null;
if(decryptAfterFile.isEmpty()){
out = new BufferedOutputStream(new FileOutputStream(new File(decryptAfterFile).getPath()));
}else{
out = new BufferedOutputStream( new FileOutputStream( decryptAfterFile));
}
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[10240];
int r = 0;
while ((r = is.read(buffer)) != -1) {
cos.write(buffer, 0, r);
}
cos.close();
out.close();
is.close();
}
/**
* 生成指定字符串的密钥
* @param secret
* @return
* @throws Exception
*/
private static Key getKey(String secret) throws Exception{
KeyGenerator generator = KeyGenerator.getInstance(type);
generator.init(new SecureRandom(secret.getBytes()));
Key key = generator.generateKey();
generator = null;
return key;
}
public static void main(String[] args) throws Exception {
long l1 = System.currentTimeMillis();
DESFile.encryptFile("D:\\ibm-jrule sdk\\jrules_JBoss.jar","d:\\excel\\jrules_JBoss.jar.des","123456789"); //加密
// DESFile.decryptFile("d:\\excel\\jrules_JBoss.jar.des", "d:\\excel\\jrules_JBoss_0.jar","123456789"); //解密
long l2 = System.currentTimeMillis();
System.out.println((l2 - l1) + "毫秒." );
System.out.println(((l2 - l1) / 1000) + "秒." );
}
}
|
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @param <T>
* 应用泛型,代表任意一个符合javabean风格的类
*/
public class ExportXlsx<T> {
public void exportExcel( Collection<T> dataset, OutputStream out) {
exportExcel( "测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");
}
public void exportExcel( String[] headers, Collection<T> dataset, OutputStream out) {
exportExcel( "测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
}
public void exportExcel( String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
exportExcel( "测试POI导出EXCEL文档", headers, dataset, out, pattern);
}
/**
* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
*
* @param title
* 表格标题名
* @param headers
* 表格属性列名数组
* @param dataset
* 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
*/
@SuppressWarnings("unchecked")
public void exportExcel( String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
SimpleDateFormat sdf= new SimpleDateFormat( pattern);
Pattern p= Pattern.compile( "^//d+(//.//d+)?$");
// 声明一个工作薄
XSSFWorkbook workbook= new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet= workbook.createSheet( title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth( (short)15);
// 生成一个样式
XSSFCellStyle style= workbook.createCellStyle();
// 生成一个字体
XSSFFont font= workbook.createFont();
font.setFontHeightInPoints( (short)15);
font.setBoldweight( XSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
style.setFont( font);
// 产生表格标题行
XSSFRow row= sheet.createRow( 0);
for( short i= 0; i < headers.length; i++) {
XSSFCell cell= row.createCell( i);
cell.setCellStyle( style);
XSSFRichTextString text= new XSSFRichTextString( headers[i]);
cell.setCellValue( text);
}
// 遍历集合数据,产生数据行
Iterator<T> it= dataset.iterator();
int index= 0;
while( it.hasNext() ) {
index++;
row= sheet.createRow( index);
T t= (T)it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields= t.getClass().getDeclaredFields();
for( short i= 0; i < fields.length; i++) {
XSSFCell cell= row.createCell( i);
Field field= fields[i];
String fieldName= field.getName();
String getMethodName= "get" + fieldName.substring( 0, 1).toUpperCase() + fieldName.substring( 1);
try {
Class tCls= t.getClass();
Method getMethod= tCls.getMethod( getMethodName, new Class[]{});
Object value= getMethod.invoke( t, new Object[]{});
// 判断值的类型后进行强制类型转换
String textValue= null;
if( value instanceof Date) {
Date date= (Date)value;
textValue= sdf.format( date);
}else {
// 其它数据类型都当作字符串简单处理
if(!"".equals((value+"")) && value != null){
textValue= value.toString();
}
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if( textValue != null) {
Matcher matcher= p.matcher( textValue);
if( matcher.matches()) {
// 是数字当作double处理
cell.setCellValue( Double.parseDouble( textValue));
}else {
XSSFRichTextString richString= new XSSFRichTextString( textValue);
cell.setCellValue( richString);
}
}
}
catch ( Exception e) {
}
}
}
try {
workbook.write( out);
}
catch ( IOException e) {
}finally{
workbook = null;
sheet = null;
sdf = null;
}
}
}
|
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private static String type = "AES";
private AES(){}
/**
* 加密byte数组
*
* @param arrB
* 需加密的字节数组
* @param secret
* 加密密钥
* @return 加密后的字节数组
* @throws Exception
*/
public static byte[] encrypt(byte[] arrB, String secret) throws Exception {
Key key = getKey(secret);
Cipher cipher = Cipher.getInstance(type);// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化加密
byte[] result = cipher.doFinal(arrB);
return result;
}
/**
* 加密字符串
*
* @param strIn
* 需加密的字符串
* @param secret
* 加密密钥
* @return 加密后的字符串
* @throws Exception
*/
public static String encrypt(String strIn, String secret) throws Exception {
return parseByte2HexStr(encrypt(strIn.getBytes(), secret));
}
/**
* 解密byte数组
*
* @param arrB
* 需解密的字节数组
* @param secret
* 解密密钥
* @return 解密后的字节数组
* @throws Exception
*/
public static byte[] decrypt(byte[] arrB, String secret) throws Exception {
Key key = getKey(secret);
Cipher cipher = Cipher.getInstance(type);// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化解密
byte[] result = cipher.doFinal(arrB);
return result;
}
/**
* 解密字符串
*
* @param strIn
* 需解密的字符串
* @param secret
* 解密密钥
* @return 解密后的字符串
* @throws Exception
*/
public static String decrypt(String strIn, String secret) throws Exception {
return new String(decrypt(parseHexStr2Byte(strIn), secret));
}
/**
* 将byte数组转换成16进制
*
* @param buf
* 需要转换的byte数组
* @return 转换后的字符串
*/
private static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toLowerCase());
}
return sb.toString();
}
/**
* 将16进制转换为byte数组
*
* @param hexStr
* 需要转换的字符串
* @return 转换后的byte数组
*/
private static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* 生成指定字符串的密钥
*
* @param secret
* 字符串
* @return key 生成后密钥
* @throws Exception
*/
private static Key getKey(String secret) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance(type);
kgen.init(128, new SecureRandom(secret.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
// 生成密钥
Key key = new SecretKeySpec(enCodeFormat, type);
return key;
}
}
|
mail.properties:
# 电子邮箱设置
# 电子邮箱服务设置
mail.host=smtp.163.com
mail.username=chenghao2432@163.com
mail.password=13158460430
# 电子邮箱的基本设置
mail.from=chenghao2432@163.com
## 当有多个时,用";" 分隔
mail.to=ch_343308590@qq.com;1064858377@qq.com;
## 当有多个时,用";" 分隔
mail.cc=
mail.bcc=
mail.subject=spring\u53D1\u9001\u7684html\u548C\u5185\u8054\u8D44\u6E90\u4F8B\u5B50
mail.text=\u4F60\u597D,\u70B9\u51FB\u56FE\u7247\u8DF3\u8F6C\:<a href\="http\://www.baidu.com"><img src\="cid\:logo" /></a>
# 添加HTML和内联资源
# 这里的logo要与cid:logo一致,不然无法显示图片
inline.key=logo
inline.value=mail/baidu.gif
# 添加附件
attachment.key=
attachment.value=
#####################################################
mailMessage.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 加载Properties文件 -->
<context:property-placeholder location="classpath:/mail.properties"/>
<!-- 申明JavaMailSenderImpl对象 -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="defaultEncoding" value="UTF-8" />
<property name="host" value="${mail.host}" />
<property name="username" value="${mail.username}" />
<property name="password" value="${mail.password}" />
<property name="javaMailProperties">
<props>
<!-- 设置认证开关 -->
<prop key="mail.smtp.auth">true</prop>
<!-- 启动调试开关 -->
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
<!-- 申明SimpleMailMessage对象 -->
<bean id="mailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from">
<!-- 设置发送方,Jack是发送者的名字 -->
<value><![CDATA[Jack<${mail.from}>]]></value>
</property>
<!-- 设置接收方 -->
<property name="to" value="${mail.to}" />
<!-- 设置抄送 -->
<property name="cc" value="${mail.cc}"></property>
<!-- 设置标题 -->
<property name="subject" value="${mail.subject}"></property>
<!-- 设置内容 -->
<property name="text" value="${mail.text}"></property>
</bean>
</beans>
###################################################
ReadConfiguration.java:
package configuration;
import java.io.IOException;
import java.util.Properties;
public class ReadConfiguration {
private static ReadConfiguration instance = new ReadConfiguration();
private static Properties properties = new Properties();
static{
try {
properties.load(ReadConfiguration.class.getResourceAsStream("/mail.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("static-access")
public static Properties getInstance(){
if(instance == null){
instance = new ReadConfiguration();
}
return instance.properties;
}
private ReadConfiguration(){
}
}
###########################################
SpringMailTest.java:
package mail;
import java.io.File;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import configuration.ReadConfiguration;
public class SpringMailTest {
public static void main(String[] args) {
// SpringMailTest.sendSimpleMail();
SpringMailTest.sendHtmlMail();
// SpringMailTest.sendFileMail();
}
/**
* 简单的邮件
*/
public static void sendSimpleMail(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/mailMessage.xml");
MailSender mailSender = (MailSender) context.getBean("mailSender");
SimpleMailMessage simpleMailMessage = (SimpleMailMessage) context.getBean("mailMessage");
mailSender.send(simpleMailMessage);
}
/**
* 含有HTML和内嵌资源的邮件
*/
public static void sendHtmlMail(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/mailMessage.xml");
JavaMailSender javaMailSender = (JavaMailSender) context.getBean("mailSender");
javaMailSender.send(new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
// 发送人,收件人,抄送人,暗抄人,主题,内容
String from = ReadConfiguration.getInstance().getProperty("mail.from");
String to = ReadConfiguration.getInstance().getProperty("mail.to");
String cc = ReadConfiguration.getInstance().getProperty("mail.cc");
String bcc = ReadConfiguration.getInstance().getProperty("mail.bcc");
String subject = ReadConfiguration.getInstance().getProperty("mail.subject");
setMail(from, to, cc, bcc, subject, "", mimeMessageHelper);
mimeMessageHelper.setText("你好,点击图片跳转:<a href='http://www.baidu.com'><img src='cid:logo' /></a>",true);
// 添加HTML和内嵌资源
mimeMessageHelper.addInline("logo",new ClassPathResource("mail/baidu.gif"));
}
});
}
/**
* 带附件的邮件
*/
public static void sendFileMail(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("/mailMessage.xml");
JavaMailSender javaMailSender = (JavaMailSender) context.getBean("mailSender");
javaMailSender.send(new MimeMessagePreparator() {
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
// 发送人,收件人,抄送人,暗抄人,主题,内容
String from = ReadConfiguration.getInstance().getProperty("mail.from");
String to = ReadConfiguration.getInstance().getProperty("mail.to");
String cc = ReadConfiguration.getInstance().getProperty("mail.cc");
String bcc = ReadConfiguration.getInstance().getProperty("mail.bcc");
String subject = ReadConfiguration.getInstance().getProperty("mail.subject");
String text = ReadConfiguration.getInstance().getProperty("mail.text");
setMail(from, to, cc, bcc, subject, text, mimeMessageHelper);
// 添加附件,加载文件方式有多样,可以通过源码进行查看
mimeMessageHelper.addAttachment("111.jpg", new File("D:/图片/111.jpg")); // D盘文件
}
});
}
/**
* 设置Mail的基本信息
* @param from 发件人
* @param to 收件人
* @param cc 抄送人
* @param bcc 暗抄人
* @param subject 主题
* @param text 内容
* @param mimeMessageHelper
*/
private static void setMail(String from,String to,String cc,String bcc,String subject,String text,MimeMessageHelper mimeMessageHelper){
try {
if(!"".equals(from)){
mimeMessageHelper.setFrom(from);
}
if(!"".equals(to)){
mimeMessageHelper.setTo(to.split(";"));
}
if(!"".equals(cc)){
mimeMessageHelper.setCc(cc.split(";"));
}
if(!"".equals(bcc)){
mimeMessageHelper.setBcc(bcc.split(";"));
}
if(!"".equals(subject)){
mimeMessageHelper.setSubject(subject);
}
if(!"".equals(text)){
mimeMessageHelper.setText(text);
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
|
build.properties:
#項目名稱
project.name=UserManager
#項目根目錄
project.root=.
#主文件存放目錄
main.dir=${project.root}/src/main
#JAVA源碼存放目錄
java.dir=${main.dir}/java
#測試源碼存放目錄
test.dir=${main.dir}/test
#配置文件存放目錄
config.dir=${main.dir}/config
#項目文檔存放目錄
doc.dir=${project.root}/doc
#此目录存放编译过程中产生的classes文件, 以及其他编译输出
build.dir=${project.root}/build
#此目录存放编译过程中产生的classes文件
build.classes.dir=${build.dir}/classes
#Web根目錄
src.webroot.dir=${project.root}/WebRoot
#Web信息目錄
src.webinf.dir=${src.webroot.dir}/WEB-INF
#第三方包存放目录
src.lib.dir=${src.webinf.dir}/lib
#Web Class目錄
src.classes.dir=${src.webinf.dir}/classes
#tomcat路經
deploy.tomcat.path=D:/platform/apache-tomcat-6.0.32/webapps
build.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project name="UserManager" basedir="." default="usage">
<property environment="env" />
<property file="build.properties" />
<!-- master classpath for the main compile. -->
<path id="master-classpath">
<fileset dir="${src.lib.dir}" />
</path>
<!-- clean the project. -->
<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${src.classes.dir}" />
</target>
<!-- Initialize the env, making directories for compiling. -->
<target name="init">
<mkdir dir="${doc.dir}"/>
<mkdir dir="${build.dir}" />
<mkdir dir="${build.classes.dir}" />
<mkdir dir="${config.dir}/biz" />
<mkdir dir="${config.dir}/core" />
<mkdir dir="${config.dir}/web" />
<mkdir dir="${config.dir}/web/tomcat" />
</target>
<!-- The main compile process. -->
<target name="compile" description="compile the java source files." depends="init">
<javac destdir="${build.classes.dir}" debug="on" deprecation="false" failonerror="true" includeantruntime="fales">
<src path="${java.dir}" />
<classpath refid="master-classpath" />
</javac>
</target>
<!-- Build exploded ear for packing. -->
<target name="exploded-ear" depends="init, compile">
<mkdir dir="${src.webroot.dir}/META-INF" />
<mkdir dir="${src.webroot.dir}"/>
<mkdir dir="${src.webinf.dir}"/>
<mkdir dir="${src.lib.dir}" />
<mkdir dir="${src.classes.dir}" />
<!-- MessageBundle编码转换-->
<native2ascii src="${config.dir}/web" dest="${src.classes.dir}" includes="*.properties" />
<!--
<copy todir="${deploy.exploded.dir}/${project.name}.war">
<fileset dir="${src.webroot.dir}/" />
</copy>
-->
</target>
<!-- =================================================================== -->
<!-- Build the test application ( For tomcat). -->
<!-- =================================================================== -->
<target name="deploy-tomcat" depends="exploded-ear">
<copy todir="${src.webinf.dir}" overwrite="true">
<fileset dir="${config.dir}/web/tomcat">
<include name="web.xml" />
</fileset>
</copy>
<copy todir="${src.classes.dir}" preservelastmodified="true" flatten="true" includeEmptyDirs="false">
<fileset dir="${config.dir}/biz/" />
<fileset dir="${config.dir}/core/" />
<fileset dir="${config.dir}/web/" />
<fileset dir="${config.dir}/web/tomcat/">
<exclude name="**/web.xml" />
</fileset>
</copy>
<copy todir="${src.classes.dir}" preservelastmodified="true" flatten="false" includeEmptyDirs="false">
<fileset dir="${build.classes.dir}/">
<include name="**/com/**" />
<include name="**/test/**" />
</fileset>
</copy>
<copy todir="${deploy.tomcat.path}/${project.name}" preservelastmodified="true" flatten="false">
<fileset dir="${src.webroot.dir}/">
<include name="**/*" />
</fileset>
</copy>
</target>
<!-- =================================================================== -->
<!-- delete the test application ( For tomcat). -->
<!-- =================================================================== -->
<target name="delete-tomcat">
<delete dir="${deploy.tomcat.path}/${project.name}"></delete>
</target>
<target name="usage">
<echo message="" />
<echo message="${project.name} build file" />
<echo message="-----------------------------------" />
<echo message="" />
<echo message="Available targets are:" />
<echo message="" />
<echo message="clean --> Clean the output dir, include build dir and dist dir" />
<echo message="deploy-tomcat --> Compile the project and deploy it on Tomcat(copy exploded-war dir to tomcat webapps folder)." />
<echo message="" />
<echo message="Please choose the target, and enjoy the build." />
</target>
</project>
|