提交 6f457418 编写于 作者: 武汉红喜's avatar 武汉红喜

update package name

上级 c5af1522
package com.itlong.whatsmars.common;
/**
* Created by liuguanqing on 15/4/16.
*/
public class CommonConstants {
public static final String FS_SECURITY_KEY = "ELO7hccMHrZr3D6NrgwSOEwFycWh1Y9u";
}
package com.itlong.whatsmars.common.mail;
import org.apache.commons.mail.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* Created by liuguanqing on 15/4/11.
*/
public class EmailSenderClient {
private String hostName;//发送端Host
private int smtpPort;//发送端口
private String username;
private String password;
private String fromAddress;//发送邮件的发送地址
private boolean sslOn = true;
private static final String DEFAULT_CHARSET = "utf-8";
public void setHostName(String hostName) {
this.hostName = hostName;
}
public void setSmtpPort(int smtpPort) {
this.smtpPort = smtpPort;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public void setSslOn(boolean sslOn) {
this.sslOn = sslOn;
}
public void sendEmail(Email email) throws Exception {
email.setAuthentication(username, password);
email.setCharset(DEFAULT_CHARSET);
email.setFrom(fromAddress);
email.setSSLOnConnect(sslOn);
email.setHostName(hostName);
email.setSmtpPort(smtpPort);
email.send();
}
public void sendTextEmail(String targetAddress,String title,String content) throws Exception {
Email email = new SimpleEmail();
email.setMsg(content);
email.setSubject(title);
email.addTo(targetAddress);
sendEmail(email);
}
/**
* content为html,此方法将会对html进行转义。
* @param targetAddress
* @param title
* @param content
* @throws Exception
*/
public void sendHtmlEmail(String targetAddress,String title,String content) throws Exception {
HtmlEmail email = new HtmlEmail();
email.setSubject(title);
email.setHtmlMsg(content);
email.addTo(targetAddress);
sendEmail(email);
}
/**
* 发送多媒体邮件,可以携带附件信息
* @param urls 附件的URL,key为附件的名称
*/
public void sendMultipartEmail(String targetAddress,String title,String content,Map<String,URL> urls) throws Exception {
MultiPartEmail email = new MultiPartEmail();
for(Map.Entry<String,URL> entry : urls.entrySet()) {
email.attach(entry.getValue(),entry.getKey(),EmailAttachment.ATTACHMENT);
}
email.setSubject(title);
email.addTo(targetAddress);
email.setMsg(content);
sendEmail(email);
}
public static void main(String[] args) throws Exception{
EmailSenderClient client = new EmailSenderClient();
client.setSmtpPort(25);
client.setHostName("smtp.qq.com");
client.setUsername("service@whatsmars.com");
client.setPassword("whatsmars99");//您的邮箱密码
client.setSslOn(true);
client.setFromAddress("service@whatsmars.com");
String targetAddress = "javahongxi@163.com";
//client.sendTextEmail("javahongxi@163.com","测试邮件","是否可以收到邮件!");
Map<String,URL> attaches = new HashMap<String, URL>();
attaches.put("logo",new URL("http://www.baidu.com/img/bd_logo1.png"));
attaches.put("logo2",new URL("http://commons.apache.org/proper/commons-email/images/commons-logo.png"));
client.sendMultipartEmail(targetAddress, "测试邮件", "test", attaches);
System.out.println("发送成功!");
}
}
package com.itlong.whatsmars.common.mongo;
import com.itlong.whatsmars.common.mongo.object.MongoDBConfig;
import com.itlong.whatsmars.common.mongo.object.MongoDBCredential;
import com.itlong.whatsmars.common.mongo.object.MongoDBDriver;
import com.mongodb.client.ListCollectionsIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
/**
* Author: qing
* Date: 14-10-11
*/
public class MongoDBClient {
protected MongoDBDriver mongoDBDriver;
protected String databaseName;
public void setMongoDBDriver(MongoDBDriver mongoDBDriver) {
this.mongoDBDriver = mongoDBDriver;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public MongoCollection<Document> getCollection(String collectionName) {
MongoDatabase db = mongoDBDriver.getDatabase(this.databaseName);
return db.getCollection(collectionName);
}
public MongoDatabase getDatabase() {
return mongoDBDriver.getDatabase(this.databaseName);
}
public static void main(String[] args) throws Exception{
MongoDBDriver mongoDBDriver = new MongoDBDriver();
try{
MongoDBConfig mongoDBConfig = new MongoDBConfig();
//mongoDBConfig.setAddresses("61.171.123.234:27017");
mongoDBConfig.setAddresses("61.171.123.234:27017");
List<MongoDBCredential> credentials = new ArrayList<MongoDBCredential>();
MongoDBCredential credential = new MongoDBCredential();
credential.setDatabaseName("whatsmars-common");
credential.setUsername("whatsmars");
//credential.setPassword("haodai.com");
credential.setPassword("passwordiscommon");
credentials.add(credential);
mongoDBConfig.setCredentials(credentials);
mongoDBDriver.setConfiguration(mongoDBConfig);
mongoDBDriver.init();
MongoDBClient client = new MongoDBClient();
client.setDatabaseName("whatsmars-common");
client.setMongoDBDriver(mongoDBDriver);
ListCollectionsIterable<Document> documents = client.getDatabase().listCollections();
MongoCursor<Document> it = documents.iterator();
while (it.hasNext()) {
Document item = it.next();
System.out.println(item.toJson());
}
it.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
mongoDBDriver.close();
}
}
}
package com.itlong.whatsmars.common.mongo.object;
/**
* Author: qing
* Date: 14-10-15
*/
public class MongoDBCredential {
private String databaseName;
private String username;
private String password;
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.itlong.whatsmars.common.mongo.object;
import org.bson.types.ObjectId;
public class ObjectIdCreator{
public static String creator(){
return new ObjectId().toString();
}
}
package com.itlong.whatsmars.common.pojo;
import java.util.HashMap;
import java.util.Map;
public class Result {
private boolean success = false;
private String message;
private ResultCode resultCode = ResultCode.SYSTEM_ERROR;
private Map<String,Object> model = new HashMap<String,Object>(32);
private String responseUrl;//响应的URL,需要跳转的URL;
public void setResponseUrl(String responseUrl) {
this.responseUrl = responseUrl;
}
public String getResponseUrl() {
return responseUrl;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
if(success){
resultCode = ResultCode.SUCCESS;
}
}
public ResultCode getResultCode() {
return resultCode;
}
public void setResultCode(ResultCode resultCode) {
this.resultCode = resultCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Result(){}
public Result(boolean success){
this.success = success;
}
public Result addModel(String key,Object value){
this.model.put(key, value);
return this;
}
public Result addModel(Map<String,Object> kv){
if(kv != null)
this.model.putAll(kv);
return this;
}
public Object getModel(String key) {
return this.model.get(key);
}
public Map<String,Object> getAll(){
return this.model;
}
}
package com.itlong.whatsmars.common.pojo;
public class ResultCode {
public String code;
public String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
private ResultCode(String code,String message){
this.code = code;
this.message = message;
}
public static final ResultCode SUCCESS = new ResultCode("S00000", "成功");
public static final ResultCode SYSTEM_ERROR = new ResultCode("E00001","系统错误");
public static final ResultCode PARAMETER_ERROR = new ResultCode("E00004","请求参数错误");
public static final ResultCode IMAGE_FORMAT_ERROR = new ResultCode("E00002","图片格式不合法");
public static final ResultCode FILE_EXISTS_ERROR = new ResultCode("E00003","文件已经存在");
public static final ResultCode FILE_NOT_EXISTS_ERROR = new ResultCode("E00005","文件不存在");
public static final ResultCode VALIDATE_FAILURE = new ResultCode("E00006","验证失败");//验证失败
public static final ResultCode NOT_LOGIN = new ResultCode("E00007","您还未登陆");
public static final ResultCode EXPIRED = new ResultCode("E00008","表单过期,请刷新");//token过期
public static final ResultCode PERMISSION_DENIED = new ResultCode("E00009","权限不足");
public static final ResultCode SMS_TIMES_LIMIT = new ResultCode("E00010","短信发送次数超过限制");
public static final ResultCode SMS_SENDING_INTERVAL_LIMIT = new ResultCode("E00011","短信发送时间间隔过短");
}
package com.itlong.whatsmars.common.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* Created by shenhongxi on 15/5/27.
*/
public class AESUtils {
private static final String PADDING = "AES/ECB/PKCS5Padding";
private static final String DEFAULT_ENCODING = "utf-8";
/**
* 加密
*
* @param data
* 需要加密的内容
* @param key
* 加密密码
* @return
*/
public static byte[] encrypt(byte[] data, byte[] key) {
if(key.length!=16){
throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
}
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat,"AES");
Cipher cipher = Cipher.getInstance(PADDING);// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, seckey);// 初始化
byte[] result = cipher.doFinal(data);
return result; // 加密
} catch (Exception e){
throw new RuntimeException("encrypt fail!", e);
}
}
/**
* 解密
*
* @param data
* 待解密内容
* @param key
* 解密密钥
* @return
*/
public static byte[] decrypt(byte[] data, byte[] key) {
if(key.length!=16){
throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
}
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance(PADDING);// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, seckey);// 初始化
byte[] result = cipher.doFinal(data);
return result; // 加密
} catch (Exception e){
throw new RuntimeException("decrypt fail!", e);
}
}
public static String encryptToBase64(String data, String key){
try {
byte[] valueByte = encrypt(data.getBytes(DEFAULT_ENCODING), key.getBytes(DEFAULT_ENCODING));
return new Base64().encodeToString(valueByte);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("encrypt fail!", e);
}
}
public static String decryptFromBase64(String data, String key){
try {
byte[] originalData = new Base64().decode(data.getBytes());
byte[] valueByte = decrypt(originalData, key.getBytes(DEFAULT_ENCODING));
return new String(valueByte, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("decrypt fail!", e);
}
}
public static String encryptWithKeyBase64(String data, String key){
try {
byte[] valueByte = encrypt(data.getBytes(DEFAULT_ENCODING), new Base64().decode(key.getBytes()));
return new String(new Base64().encode(valueByte));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("encrypt fail!", e);
}
}
public static String decryptWithKeyBase64(String data, String key){
try {
byte[] originalData = new Base64().decode(data.getBytes());
byte[] valueByte = decrypt(originalData, new Base64().decode(key.getBytes()));
return new String(valueByte, DEFAULT_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("decrypt fail!", e);
}
}
public static byte[] genarateRandomKey(){
KeyGenerator keygen = null;
try {
keygen = KeyGenerator.getInstance(PADDING);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(" genarateRandomKey fail!", e);
}
SecureRandom random = new SecureRandom();
keygen.init(random);
Key key = keygen.generateKey();
return key.getEncoded();
}
public static String genarateRandomKeyWithBase64(){
return new String(new Base64().encode(genarateRandomKey()));
}
}
package com.itlong.whatsmars.common.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
public class DESUtils {
private static final String DES = "DES";
private static final String PADDING = "DES/ECB/PKCS5Padding";
private static final String DEFAULT_ENCODING = "utf-8";
public final static String encrypt(String code, String key) {
try {
return Base64.encodeBase64String(encrypt(code.getBytes(DEFAULT_ENCODING), key
.getBytes(DEFAULT_ENCODING)));
} catch (Exception e) {
//
}
return null;
}
public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(PADDING);
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(src);
}
public final static String decrypt(String data, String key) {
try {
//base64,default-charset is UTF-8
return new String(decrypt(Base64.decodeBase64(data),
key.getBytes(DEFAULT_ENCODING)), DEFAULT_ENCODING);
} catch (Exception e) {
//
}
return null;
}
public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
SecureRandom sr = new SecureRandom();
DESKeySpec dks = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
Cipher cipher = Cipher.getInstance(PADDING);
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(src);
}
}
package com.itlong.whatsmars.common.util;
import org.apache.commons.lang.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtils {
/**
* 日期格式 yyyy-MM-dd
*/
public final static String DATEFORMAT = "yyyy-MM-dd";
/**
* 日期格式 yyyyMMdd
*/
public final static String DATEFORMAT2 = "yyyyMMdd";
/**
* 日期格式 yyyy/MM/dd
*/
public final static String DATEFORMAT3 = "yyyy/MM/dd";
/**
* 时间格式 HH:mm:ss
*/
public final static String TIMEFORMAT = "HH:mm:ss";
/**
* 日期时间格式 yyyy-MM-dd HH:mm:ss
*/
public final static String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* yyyy-MM
*/
public final static String DATE_SHORT_FORMAT = "yyyy-MM";
/**
* yyyyMM
*/
public final static String DATE_SHORT_FORMAT2 = "yyyyMM";
public static String DATETIME_FORMAT_REGEX = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";//yyyy-MM-dd HH:mm:ss
public static String DATE_FORMAT_REGEX = "\\d{4}-\\d{2}-\\d{2}";//yyyy-MM-dd
public static String SHORTDATE_FORMAT_REGEX = "\\d{4}-\\d{2}";//yyyy-MM
public static String DATE_FORMAT2_REGEX = "\\d{4}\\d{2}\\d{2}";//yyyyMMdd
public static String SHORTDATE_FORMAT2_REGEX = "\\d{4}\\d{2}";//yyyyMM
/**
* 获取时间日期格式化dateformat
*
* @param pattern 格式
* @return
*/
public static DateFormat getFormat(String pattern) {
if (StringUtils.isEmpty(pattern)) {
return null;
}
return new SimpleDateFormat(pattern);
}
/**
* 将string类型date格式化为date类型
*
* @param dateString string类型date
* @param pattern 格式
* @return
*/
public static Date getDateFormat(String dateString, String pattern) {
if (StringUtils.isEmpty(dateString)) {
return null;
}
try {
return getFormat(pattern).parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static String getStringFormat(Date date, String pattern) {
if (null == date) {
return null;
}
return getFormat(pattern).format(date);
}
/**
* 将string类型date重新格式化为string类型
*
* @param dateString
* @param srcPattern
* @param targetPattern
* @return
*/
public static String getStringReformat(String dateString, String srcPattern, String targetPattern) {
Date date = getDateFormat(dateString, srcPattern);
return getStringFormat(date, targetPattern);
}
/**
* 获取当前时间的前一天
*
* @return
*/
public static Date getYesterday() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 获取本月的第一天
*
* @return
*/
public static Date getFirstDayByMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 获取上一个月的第一天
*
* @return
*/
public static Date getFirstDayByLastMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 根据月份获取当月第一天
*
* @param month
* @return
*/
public static Date getFirstDayByMonth(int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 获取某个月份的第一天
*
* @param month
* @return
*/
public static Date getFirstDayByMonth(Date date, int month) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
/**
* 计算两个日期之间相隔的月份
*
* @param startDate
* @param endDate
* @return
*/
public static List<String> intervalMonths(Date startDate, Date endDate) {
List<String> monthList = new ArrayList<String>();
Calendar tmp = Calendar.getInstance();
tmp.setTime(startDate);
tmp.set(Calendar.DAY_OF_MONTH, tmp.getActualMaximum(Calendar.DAY_OF_MONTH) - 1);
Calendar start = Calendar.getInstance();
start.setTime(startDate);
start.set(Calendar.DAY_OF_MONTH, 1);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
end.set(Calendar.DAY_OF_MONTH, end.getActualMaximum(Calendar.DAY_OF_MONTH));
SimpleDateFormat sdf = new SimpleDateFormat(DATE_SHORT_FORMAT);
for (; tmp.after(start) && tmp.before(end); tmp.add(Calendar.MONTH, 1), tmp.set(Calendar.DAY_OF_MONTH, tmp.getActualMaximum(Calendar.DAY_OF_MONTH) - 1)) {
monthList.add(sdf.format(tmp.getTime()));
}
return monthList;
}
/**
* 传入时间和当前时间比较最大获取上个月,返回虽然Date,实际时间是yyyyMM01 00:00:00.0
*
* @param date
* @return
*/
public static Date maxLastMonth(Date date) {
Date thisMonth = DateUtils.getDateFormat(DateUtils.getStringFormat(new Date(), DateUtils.DATE_SHORT_FORMAT), DateUtils.DATE_SHORT_FORMAT);
if (thisMonth.compareTo(date) <= 0) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(thisMonth);
calendar.add(Calendar.MONTH, -1);
return calendar.getTime();
}
return date;
}
public static Date getMonth(Date date, int month) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + month);
return calendar.getTime();
}
public static Date getFirstDayByMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return calendar.getTime();
}
public static int betweenDays(Date beforeDate, Date afterDate) {
if (null == beforeDate || null == afterDate) {
throw new NullPointerException("date can't be null");
}
if (beforeDate.after(afterDate)) {
return 0;
}
return (int) ((afterDate.getTime() - beforeDate.getTime()) / (1000 * 3600 * 24));
}
}
package com.itlong.whatsmars.common.util;
import java.text.NumberFormat;
import java.util.HashMap;
public class MoneyFormatUtils {
public static final String EMPTY = "";
public static final String ZERO = "零";
public static final String ONE = "壹";
public static final String TWO = "贰";
public static final String THREE = "叁";
public static final String FOUR = "肆";
public static final String FIVE = "伍";
public static final String SIX = "陆";
public static final String SEVEN = "柒";
public static final String EIGHT = "捌";
public static final String NINE = "玖";
public static final String TEN = "拾";
public static final String HUNDRED = "佰";
public static final String THOUSAND = "仟";
public static final String TEN_THOUSAND = "万";
public static final String HUNDRED_MILLION = "亿";
public static final String YUAN = "元";
public static final String JIAO = "角";
public static final String FEN = "分";
public static final String DOT = ".";
private static MoneyFormatUtils formatter = null;
private HashMap chineseNumberMap = new HashMap();
private HashMap chineseMoneyPattern = new HashMap();
private NumberFormat numberFormat = NumberFormat.getInstance();
private MoneyFormatUtils() {
numberFormat.setMaximumFractionDigits(4);
numberFormat.setMinimumFractionDigits(2);
numberFormat.setGroupingUsed(false);
chineseNumberMap.put("0", ZERO);
chineseNumberMap.put("1", ONE);
chineseNumberMap.put("2", TWO);
chineseNumberMap.put("3", THREE);
chineseNumberMap.put("4", FOUR);
chineseNumberMap.put("5", FIVE);
chineseNumberMap.put("6", SIX);
chineseNumberMap.put("7", SEVEN);
chineseNumberMap.put("8", EIGHT);
chineseNumberMap.put("9", NINE);
chineseNumberMap.put(DOT, DOT);
chineseMoneyPattern.put("1", TEN);
chineseMoneyPattern.put("2", HUNDRED);
chineseMoneyPattern.put("3", THOUSAND);
chineseMoneyPattern.put("4", TEN_THOUSAND);
chineseMoneyPattern.put("5", TEN);
chineseMoneyPattern.put("6", HUNDRED);
chineseMoneyPattern.put("7", THOUSAND);
chineseMoneyPattern.put("8", HUNDRED_MILLION);
}
public static MoneyFormatUtils getInstance() {
if (formatter == null)
formatter = new MoneyFormatUtils();
return formatter;
}
public String format(String moneyStr) {
checkPrecision(moneyStr);
String result;
result = convertToChineseNumber(moneyStr);
result = addUnitsToChineseMoneyString(result);
return result;
}
public String format(double moneyDouble) {
return format(numberFormat.format(moneyDouble));
}
public String format(int moneyInt) {
return format(numberFormat.format(moneyInt));
}
public String format(long moneyLong) {
return format(numberFormat.format(moneyLong));
}
public String format(Number moneyNum) {
return format(numberFormat.format(moneyNum));
}
private String convertToChineseNumber(String moneyStr) {
String result;
StringBuffer cMoneyStringBuffer = new StringBuffer();
for (int i = 0; i < moneyStr.length(); i++) {
cMoneyStringBuffer.append(chineseNumberMap.get(moneyStr.substring(i, i + 1)));
}
// 拾佰仟万亿等都是汉字里面才有的单位,加上它们
int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
int moneyPatternCursor = 1;
for (int i = indexOfDot - 1; i > 0; i--) {
cMoneyStringBuffer.insert(i, chineseMoneyPattern.get(EMPTY + moneyPatternCursor));
moneyPatternCursor = moneyPatternCursor == 8 ? 1 : moneyPatternCursor + 1;
}
String fractionPart = cMoneyStringBuffer.substring(cMoneyStringBuffer.indexOf("."));
cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("."), cMoneyStringBuffer.length());
while (cMoneyStringBuffer.indexOf("零拾") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零拾"), cMoneyStringBuffer.indexOf("零拾") + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零佰") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零佰"), cMoneyStringBuffer.indexOf("零佰") + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零仟") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零仟"), cMoneyStringBuffer.indexOf("零仟") + 2, ZERO);
}
while (cMoneyStringBuffer.indexOf("零万") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零万"), cMoneyStringBuffer.indexOf("零万") + 2, TEN_THOUSAND);
}
while (cMoneyStringBuffer.indexOf("零亿") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零亿"), cMoneyStringBuffer.indexOf("零亿") + 2, HUNDRED_MILLION);
}
while (cMoneyStringBuffer.indexOf("零零") != -1) {
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零零"), cMoneyStringBuffer.indexOf("零零") + 2, ZERO);
}
if (cMoneyStringBuffer.lastIndexOf(ZERO) == cMoneyStringBuffer.length() - 1)
cMoneyStringBuffer.delete(cMoneyStringBuffer.length() - 1, cMoneyStringBuffer.length());
cMoneyStringBuffer.append(fractionPart);
result = cMoneyStringBuffer.toString();
return result;
}
private String addUnitsToChineseMoneyString(String moneyStr) {
String result;
StringBuffer cMoneyStringBuffer = new StringBuffer(moneyStr);
int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
cMoneyStringBuffer.replace(indexOfDot, indexOfDot + 1, YUAN);
cMoneyStringBuffer.insert(cMoneyStringBuffer.length() - 1, JIAO);
cMoneyStringBuffer.insert(cMoneyStringBuffer.length(), FEN);
if (cMoneyStringBuffer.indexOf("零角零分") != -1){
// 没有零头,加整
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零角零分"), cMoneyStringBuffer.length(), "整");
}else if(cMoneyStringBuffer.indexOf("零分") != -1){
// 没有零分,加整
cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零分"), cMoneyStringBuffer.length(), "整");
}else {
if (cMoneyStringBuffer.indexOf("零角") != -1)
cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("零角"), cMoneyStringBuffer.indexOf("零角") + 2);
// tmpBuffer.append("整");
}
result = cMoneyStringBuffer.toString();
return result;
}
private void checkPrecision(String moneyStr) {
int fractionDigits = moneyStr.length() - moneyStr.indexOf(DOT) - 1;
if (fractionDigits > 2)
throw new RuntimeException("金额" + moneyStr + "的小数位多于两位。"); //精度不能比分低
}
public static void main(String args[]) {
System.out.println(getInstance().format(new Double(15000.26)));
}
}
\ No newline at end of file
package com.itlong.whatsmars.common.util;
import java.math.BigDecimal;
/**
* Created by jenny on 6/4/15.
*/
public class NumberFormatUtils {
/**
* double类型的数据保留num位小数
* @param value
* @param num
* @return
*/
public static double format(Double value,int num){
if (value == Double.valueOf(value).intValue()){
return Double.valueOf(value).intValue();
}else {
BigDecimal bigDecimal = new BigDecimal(Double.toString(value));
return bigDecimal.setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
}
package com.whatsmars.common.mongo;
import com.whatsmars.common.mongo.object.MongoDBConfig;
import com.whatsmars.common.ImageSizeEnum;
import com.whatsmars.common.mongo.object.MongoDBCredential;
import com.whatsmars.common.mongo.object.MongoDBDriver;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.imgscalr.Scalr;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.Adler32;
/**
* Author: qing
* Date: 14-10-11
*/
public class GridFSClient extends MongoDBClient{
private GridFS _gridFS = null;
private Object lock = new Object();
protected static final String[] IMAGE_FORMAT = {"jpg","jpeg","png"};
public void setMongoDBDriver(MongoDBDriver mongoDBDriver) {
this.mongoDBDriver = mongoDBDriver;
}
public GridFS getInstance() {
if(_gridFS != null) {
return _gridFS;
}
synchronized (lock) {
if(_gridFS != null) {
return _gridFS;
}
_gridFS = new GridFS(mongoDBDriver.getDB(this.databaseName));
return _gridFS;
}
}
public void close() {
mongoDBDriver.close();
}
/**
*
* @param inputStream 文件流
* @param format 文件格式,“pdf”,“png”等,不包含后缀符号“.”
* @return
*/
public String saveFile(InputStream inputStream,String format,String uid) {
try {
GridFS gridFS = getInstance();
//随机生成文件名称,多次重试
String filename = this.randomFileName();
//如果有文件重复,则重新生成filename
while (true) {
GridFSDBFile _current = gridFS.findOne(filename);
//如果文件不存在,则保存操作
if (_current == null) {
break;
}
filename = this.randomFileName();
}
GridFSInputFile file = gridFS.createFile(inputStream, filename);
if(format != null) {
file.put("format", format);
}
if(uid != null) {
file.put("uid",uid);
}
file.put("content-type","application/octet-stream");
file.save();
return concat(filename,format);
}catch (Exception e) {
throw new RuntimeException(e);
} finally {
try{
inputStream.close();
}catch (Exception ex) {
//
}
}
}
private String concat(String filename,String format) {
if(format == null) {
return filename;
}
if(format.startsWith(".")) {
return filename + format;
}
return filename + "." + format;
}
private String randomFileName() {
return RandomStringUtils.random(32, true, true).toLowerCase();
}
public void delete(String filename) {
GridFS gridFS = getInstance();
gridFS.remove(filename);
}
public InputStream getFile(String filename) {
GridFS gridFS = getInstance();
GridFSDBFile _current = gridFS.findOne(filename);
if(_current == null) {
return null;
}
return _current.getInputStream();
}
public InputStream getImage(String filename,String path) throws Exception{
//获取最大边,等比缩放
if(ImageSizeEnum.valueOfPath(path) == null) {
return null;
}
GridFS gridFS = getInstance();
GridFSDBFile _current = gridFS.findOne(filename);
if(_current == null) {
return null;
}
int size = ImageSizeEnum.valueOfPath(path).size;
int max = (Integer)_current.get("max");//图片的实际尺寸
InputStream result = null;
//裁剪
if(size < max) {
InputStream inputStream = _current.getInputStream();
BufferedImage image = ImageIO.read(inputStream);
inputStream.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedImage thumbnail = Scalr.resize(image, size);//保留最大尺寸
String format = (String) _current.get("format");
ImageIO.write(thumbnail, format, bos);
result = new ByteArrayInputStream(bos.toByteArray());
} else {
result = _current.getInputStream();
}
return result;
}
/**
*
* @param inputStream 输入流
* @return
* @throws Exception
*/
public String saveImage(InputStream inputStream,String uid) throws Exception{
BundleEntry bundleEntry = this.drain(inputStream);
if(bundleEntry == null) {
throw new RuntimeException("file isn't a image!");
}
ByteArrayInputStream bis = bundleEntry.inputStream;
String _currentFileName = this.isExistedImage(bundleEntry);
//如果文件md5已存在
if(_currentFileName != null) {
return _currentFileName;
}
String format = bundleEntry.format;
GridFS gridFS = getInstance();
String filename = this.randomFileName();
//检测文件名称
while(true){
GridFSDBFile _current = gridFS.findOne(filename);
//如果文件不存在,则保存操作
if (_current == null) {
break;
}
//否则,重新生成文件名称
filename = randomFileName();
}
//图片处理
bis.reset();
//保存原图
GridFSInputFile _inputFile = gridFS.createFile(bis, filename);
if(uid != null) {
_inputFile.put("uid", uid);
}
_inputFile.put("max",bundleEntry.max);
_inputFile.put("crc",bundleEntry.crc);
_inputFile.put("format",format);
_inputFile.put("md5_source",bundleEntry.md5);
_inputFile.save();
return concat(filename,format);
}
private String isExistedImage(BundleEntry entry) {
GridFS gridFS = getInstance();
DBObject query = new BasicDBObject();
query.put("crc",entry.crc);
query.put("md5_source",entry.md5);
GridFSDBFile _current = gridFS.findOne(query);
//根据MD5值查询,检测是否存在
if(_current == null) {
return null;
}
String format = (String)_current.get("format");
if(format.startsWith(".")) {
return _current.getFilename() + format;
}
return _current.getFilename() + "." + format;
}
/**
* 因为图片的stream需要reset,所以需要将流全部汲取
* @param inputStream
* @return
* @throws Exception
*/
protected BundleEntry drain(InputStream inputStream) throws Exception{
//
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//计算源文件的md5、crc,以防止图片的重复上传
Adler32 crc = new Adler32();
try{
while(true) {
int _c = inputStream.read();
if(_c == -1) {
break;
}
bos.write(_c);
crc.update(_c);
}
}catch (Exception e) {
throw new RuntimeException(e);
} finally {
inputStream.close();
}
//第一步:图片格式
List<String> formats = new ArrayList<String>();//
ImageInputStream imageInputStream = ImageIO.createImageInputStream(new ByteArrayInputStream(bos.toByteArray()));
imageInputStream.mark();
try {
Iterator<ImageReader> it = ImageIO.getImageReaders(imageInputStream);
while (it.hasNext()) {
ImageReader reader = it.next();
String format = reader.getFormatName().toLowerCase();
if(ArrayUtils.contains(IMAGE_FORMAT, format)) {
formats.add(format);
}
}
}catch (Exception ex) {
//
}
//如果格式不合法,则直接返回
if(formats.isEmpty()) {
try {
imageInputStream.close();
} catch (Exception e) {
//
}
return null;
}
String md5 = DigestUtils.md5Hex(bos.toByteArray());//求原始图片的MD5,和crc
System.out.println("md5:" + md5);
imageInputStream.reset();
BufferedImage image = ImageIO.read(imageInputStream);
//获取最大边,等比缩放
int max = Math.max(image.getHeight(), image.getWidth());
bos = new ByteArrayOutputStream();
//如果尺寸超过最大值,则resize
if(max > ImageSizeEnum.PIXELS_MAX.size) {
max = ImageSizeEnum.PIXELS_MAX.size;
}
String format = formats.get(0);
BufferedImage thumbnail = Scalr.resize(image, max);//保留最大尺寸
ImageIO.write(thumbnail, format, bos);
return new BundleEntry(new ByteArrayInputStream(bos.toByteArray()),md5,crc.getValue(),format,max);
}
protected class BundleEntry {
String md5;
long crc;
String format;
int max;
ByteArrayInputStream inputStream;
BundleEntry(ByteArrayInputStream inputStream,String md5,long crc,String format,int max) {
this.md5 = md5;
this.crc = crc;
this.inputStream = inputStream;
this.format = format;
this.max = max;
}
}
public static void main(String[] args) throws Exception{
MongoDBDriver mongoDBDriver = new MongoDBDriver();
try {
GridFSClient client = new GridFSClient();
MongoDBConfig mongoDBConfig = new MongoDBConfig();
//mongoDBConfig.setAddresses("61.172.238.149:27017");
mongoDBConfig.setAddresses("61.172.240.58:27017");
List<MongoDBCredential> credentials = new ArrayList<MongoDBCredential>();
MongoDBCredential credential = new MongoDBCredential();
credential.setDatabaseName("whatsmars-fs");
credential.setUsername("whatsmars");
//credential.setPassword("haodai.com");
credential.setPassword("passwordisfs");
credentials.add(credential);
mongoDBConfig.setCredentials(credentials);
mongoDBDriver.setConfiguration(mongoDBConfig);
mongoDBDriver.init();
client.setDatabaseName("whatsmars-fs");
client.setMongoDBDriver(mongoDBDriver);
testUpload(client);
//testClear(client.getInstance());
//testGetImage(client.getInstance(),"xhgcguccxumuyl9hzdombgfvzgriv7rf",null);
} catch (Exception e) {
e.printStackTrace();
} finally {
mongoDBDriver.close();
}
}
protected static void testClear(GridFS gridFS) {
DBCursor cursor = gridFS.getFileList();
while (cursor.hasNext()) {
DBObject dbObject = cursor.next();
String filename = (String)cursor.next().get("filename");
System.out.println(filename);
System.out.println(dbObject.toString());
gridFS.remove(filename);
}
cursor.close();
}
protected static void testUpload(GridFSClient client) throws Exception{
FileInputStream inputStream = new FileInputStream(new File("/data/tmp/222222222.jpg"));
try {
String filename = client.saveImage(inputStream, null);
System.out.println(filename);
String source = filename.substring(0,filename.lastIndexOf("."));
System.out.println(source);
InputStream result = client.getImage(source, "x4");
if(result == null) {
System.out.println("not found!");
}
//vejibw36famkscjyksgke7bugzonnyan
FileOutputStream outputStream = new FileOutputStream("/data/tmp/" + filename);
while (true) {
int i = result.read();
if( i == -1) {
break;
}
outputStream.write(i);
}
outputStream.flush();
outputStream.close();
result.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
inputStream.close();
}
}
protected static void testGetImage(GridFS gridFS,String filename,String path) {
DBObject query = new BasicDBObject();
query.put("md5_source","9e131ae4ed7337d4712650229b827725");
GridFSDBFile file = gridFS.findOne(query);
if(file != null) {
System.out.println(file.getFilename());
}
}
}
package com.whatsmars.common.mongo.object;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.client.MongoDatabase;
import org.apache.commons.lang.StringUtils;
import java.util.Properties;
/**
* Author: qing
* Date: 14-10-10
*/
public class MongoDBDriver {
private Properties properties;
/**
*/
private MongoClient mongo = null;
/**
*/
private Integer connectionsPerHost = 32;
private Integer threadsAllowedToBlockForConnectionMultiplier = 5;
private Integer maxWaitTime = 30000;
private Integer connectTimeout = 30000;
private Integer socketTimeout = 30000;
private Integer maxConnectionIdle = 6000;
private MongoDBConfig configuration;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setConfiguration(MongoDBConfig configuration) {
this.configuration = configuration;
}
public void init() throws Exception{
if(properties != null){
String perHost = properties.getProperty("mongodb.driver.connectionsPerHost");
////////////
if(StringUtils.isNotBlank(perHost)){
connectionsPerHost = Integer.valueOf(perHost);
}
////////////
String multiplier = properties.getProperty("mongodb.driver.threadsAllowedToBlockForConnectionMultiplier");
if(StringUtils.isNotBlank(multiplier)){
threadsAllowedToBlockForConnectionMultiplier = Integer.valueOf(multiplier);
}
/////////////
String waitTime = properties.getProperty("mongodb.driver.maxWaitTime");
if(StringUtils.isNotBlank(waitTime)){
maxWaitTime = Integer.valueOf(waitTime);
}
////////////
String ctimeout = properties.getProperty("mongodb.driver.connectTimeout");
if(StringUtils.isNotBlank(ctimeout)){
connectTimeout = Integer.valueOf(ctimeout);
}
////////////
String stimeout = properties.getProperty("mongodb.driver.socketTimeout");
if(StringUtils.isNotBlank(stimeout)){
socketTimeout = Integer.valueOf(stimeout);
}
////////////
String mci = properties.getProperty("mongodb.driver.maxConnectionIdle");
if(StringUtils.isNotBlank(mci)){
maxConnectionIdle = Integer.valueOf(mci);
}
}
////init,db check and connected.
execute();
}
private void execute() throws Exception{
MongoClientOptions.Builder builder = MongoClientOptions.builder();
builder.connectionsPerHost(this.connectionsPerHost);
builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
builder.socketKeepAlive(true);
builder.maxWaitTime(this.maxWaitTime);
builder.connectTimeout(this.connectTimeout);
builder.socketTimeout(this.socketTimeout);
builder.maxConnectionIdleTime(maxConnectionIdle);
MongoClientOptions options = builder.build();
this.mongo = new MongoClient(configuration.buildAddresses(), configuration.buildCredentials(),options);
}
public void close() {
mongo.close();
}
public Mongo getMongo() {
return mongo;
}
public MongoDatabase getDatabase(String dbName) {
return mongo.getDatabase(dbName);
}
/**
* old api
* @param dbName
* @return
*/
public DB getDB(String dbName) {
return mongo.getDB(dbName);
}
}
\ No newline at end of file
package com.itlong.whatsmars.common.util;
package com.whatsmars.common.util;
import javax.mail.PasswordAuthentication;
......
package com.whatsmars.common.util;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by jenny on 4/15/15.
*/
public class ValidateCodeUtils {
private static final int WIDTH = 85;
private static final int HEIGHT = 40;
/**
* 生成验证码图片
* @return key为code字符串,value位图片
*/
public static Map.Entry<String,BufferedImage> generate() {
BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); //在内存中创建图象
Graphics2D g = image.createGraphics(); //获取图形上下文
//设定背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18)); //设定字体
//随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
Random random = new Random(); //生成随机类
for (int i = 0; i < 155; i++) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
StringBuffer sb = new StringBuffer(); //取随机产生的认证码(4位数字)
for (int i = 0; i < 4; i++) {
String code = String.valueOf(random.nextInt(10));
sb.append(code);
//将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(code, 13 * i + 18, 27);
}
Map<String,BufferedImage> map = new HashMap<String, BufferedImage>();
map.put(sb.toString(),image);
return map.entrySet().iterator().next();
}
/*
* 给定范围获得随机颜色
*/
private static Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
package com.itlong.whatsmars.dbrouter;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* Created by shenhongxi on 16/7/16.
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
public DynamicDataSource() {
}
protected Object determineCurrentLookupKey() {
return DbContext.getDbKey(); // ThreadLocal
}
}
package com.itlong.whatsmars.dbrouter.demo;
/**
* Created by shenhongxi on 16/7/16.
*/
public class BaseReq {
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
package com.itlong.whatsmars.dbrouter.demo;
import java.math.BigDecimal;
/**
* Created by shenhongxi on 16/7/16.
*/
public class OrderDO extends BaseDO {
private String orderId;
private BigDecimal amount;
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}
package com.itlong.whatsmars.dbrouter.demo;
import com.itlong.whatsmars.dbrouter.DbRoute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by shenhongxi on 16/7/16.
*/
@Service("orderService")
public class OrderServiceImpl {
@Autowired
private OrderDao orderDao;
@DbRoute(field = "userId", tableStyle = "0000")
public void addOrder(AddOrderReq req) {
OrderDO order = new OrderDO();
order.setUserId(req.getUserId());
order.setOrderId(order.getUserId() + System.currentTimeMillis());
order.setAmount(req.getAmount());
orderDao.insert(order);
}
}
package com.whatsmars.dbrouter;
import org.springframework.util.StringUtils;
/**
* Created by shenhongxi on 16/7/16.
*/
public class DbRouter {
public void route(String fieldId) {
if(StringUtils.isEmpty(fieldId)) {
throw new IllegalArgumentException("dbsCount and tablesCount must be both positive!");
} else {
// base64编码得到的字符串取hashcode
int routeFieldInt = RouteUtils.getResourceCode(fieldId);
// 分库又分表
int dbs = 6;
int tbs = 200;
int mode = dbs * tbs;
Integer dbIndex = routeFieldInt % mode / tbs;
Integer tableIndex = routeFieldInt % tbs;
// tableIndex格式化
// dbIndex -> dbKey;
DbContext.setTableIndex(tableIndex.toString());
DbContext.setDbKey(dbIndex.toString());
}
}
}
package com.whatsmars.dbrouter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RouteUtils {
private static final Logger log = LoggerFactory.getLogger(RouteUtils.class);
private static final String encode = "utf-8";
private static final int resourceMax = 10000;
public RouteUtils() {
}
public static int getHashCodeBase64(String routeValue) {
int hashCode = 0;
try {
//String e = Base64Binrary.encodeBase64Binrary(routeValue.getBytes("utf-8"));
//hashCode = Math.abs(e.hashCode());
} catch (Exception var3) {
log.error("hashCode 失败", var3);
}
return hashCode;
}
public static int getResourceCode(String routeValue) {
int hashCode = getHashCodeBase64(routeValue);
int resourceCode = hashCode % 10000;
return resourceCode;
}
public static void main(String[] args) {
String payid = "140331160123935469773";
String resource = payid.substring(payid.length() - 4);
int routeFieldInt = Integer.valueOf(resource).intValue();
short mode = 1200;
int dbIndex = routeFieldInt % mode / 200;
int tbIndex = routeFieldInt % 200;
System.out.println(dbIndex + "-->" + tbIndex);
}
}
\ No newline at end of file
package com.itlong.whatsmars.dbrouter.demo;
package com.whatsmars.dbrouter.demo;
import org.apache.ibatis.session.SqlSession;
......
package com.whatsmars.dbrouter.demo;
/**
* Created by shenhongxi on 16/7/16.
*/
public interface OrderDao {
void insert(OrderDO order);
}
......@@ -37,7 +37,7 @@
<property name="minEvictableIdleTimeMillis" value="${dbcp.minEvictableIdleTimeMillis}"></property>
</bean>
<bean id="dynamicDataSource" class="com.itlong.bjxizhan.support.web.service.dbrouter.DynamicDataSource">
<bean id="dynamicDataSource" class="com.whatsmars.dbrouter.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="db1" value-ref="dataSource1"/>
......
package com.itlong.whatsmars.earth.dao.impl;
import com.itlong.whatsmars.earth.dao.AccountDao;
/**
* Created by shenhongxi on 2016/4/1.
*/
public class AccountDaoImpl extends BaseDao implements AccountDao {
public String hello(String name) {
return "Hello, " + name;
}
}
package com.itlong.whatsmars.earth.dao.impl;
import org.apache.ibatis.session.SqlSession;
/**
* Author: qing
* Date: 14-10-12
*/
public abstract class BaseDao {
protected SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
}
package com.itlong.whatsmars.earth.domain.enums;
/**
* Created by jenny on 6/11/15.
*/
public enum AdminFlowTypeEnum {
RECHARGE(0, "充值"),
WITHDRAW(1, "提现"),
//借款人还款,学好贷收到服务费
RECEIVE_FEE(9, "收到服务费"),
//投资人充值,学好贷支付充值费用
RECHARGE_FEE(10, "支付充值费用"),
//借款人逾期且机构保证金不足,平台垫付本息
ADMIN_ADVANCE_AMOUNT(13, "平台垫付本息"),
//平台或机构垫付后借款人还款,平台收到逾期罚金
RECEIVE_FINE(14, "收到逾期罚金"),
//平台垫付后借款人还款
RECEIVE_AFTER_ADVANCE(16, "平台垫付后收款");
public Integer code;
public String meaning;
public int getCode() {
return code;
}
public String getMeaning() {
return meaning;
}
AdminFlowTypeEnum(int code, String meaning) {
this.code = code;
this.meaning = meaning;
}
public static AdminFlowTypeEnum value(int code){
for(AdminFlowTypeEnum e:values()){
if(e.code==code){
return e;
}
}
return null;
}
}
package com.itlong.whatsmars.earth.domain.permission;
import com.itlong.whatsmars.earth.domain.enums.UserTypeEnum;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by liuguanqing on 15/4/18.
* 系统后台权限控制
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface Permission {
public UserTypeEnum[] roles();//用户类型
public String[] operations() default {};//用户需要具备的操作
}
package com.itlong.whatsmars.earth.domain.query;
import java.util.Map;
/**
* Created by shenhongxi on 15/4/16.
*/
public class OrganizationQuery extends BaseQuery {
private String name;
private String code;
private String email;
private Integer status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<String, Object> build() {
Map<String,Object> params = super.build();
params.put("name",this.name);
params.put("code", this.code);
params.put("email", this.email);
params.put("status",status);
return params;
}
public String queryString() {
StringBuilder sb = new StringBuilder();
sb.append("name=");
sb.append(this.name == null ? "" : this.name);
sb.append("&code=");
sb.append(this.code == null ? "" : this.code);
sb.append("&email=");
sb.append(this.email == null ? "" : this.email);
sb.append("&status=");
sb.append(this.status == null ? "" : this.status);
return sb.toString();
}
}
package com.itlong.whatsmars.earth.domain.query;
import java.io.Serializable;
import java.util.*;
/**
* 分页查询结果
* @param <T>
*/
public class QueryResult<T> implements Serializable {
private Integer totalPage;//总页数
private Integer amount;//总条数
private Collection<T> resultList = new ArrayList<T>();//当前页数据集合
private BaseQuery query;
public Integer getTotalPage() {
return totalPage;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
if (amount == null) {
return;
}
if (query == null) {
return;
}
int pageSize = query.getPageSize();
int mod = amount % pageSize;
int page = amount / pageSize;
totalPage = (mod == 0 ? page : page + 1);
this.amount = amount;
}
public Collection<T> getResultList() {
return resultList;
}
public void setResultList(Collection<T> resultList) {
this.resultList = resultList;
}
public BaseQuery getQuery() {
return query;
}
public void setQuery(BaseQuery query) {
this.query = query;
}
public Integer getNextPage() {
Integer nextPage = query.getCurrentPage() + 1;
return nextPage > totalPage ? -1 : nextPage;
}
public List<Integer> pageNumbers() {
if(totalPage == 0) {
return Collections.EMPTY_LIST;
}
List<Integer> pages = new ArrayList<Integer>();
for(int i = 1; i<= totalPage; i++) {
pages.add(i);
}
return pages;
}
//***************************utils*****************************//
public Map<String, Object> propertyMap() {
Map<String, Object> pm = new HashMap<String, Object>(5);
pm.put("amount", this.amount);
pm.put("totalPage", this.totalPage);
pm.put("resultList", this.resultList);
if (query != null) {
pm.putAll(query.build());
}
return pm;
}
}
package com.whatsmars.earth.domain.enums;
/**
* Created by liuguanqing on 15/4/3.
*/
public enum UserTypeEnum {
INVESTOR(1,"投资人"),
STUDENT(2,"借款人"),
ORGANIZATION(3,"机构"),
TEACHER(4,"教师"),
ADMIN(5,"管理员");
public int code;
public String meaning;//意义
public int getCode() {
return code;
}
public String getMeaning() {
return meaning;
}
UserTypeEnum(int code,String meaning) {
this.code = code;
this.meaning = meaning;
}
public static UserTypeEnum value(int code) {
for(UserTypeEnum e : values()) {
if(e.code == code) {
return e;
}
}
return null;
}
}
package com.whatsmars.earth.domain.misc;
import com.whatsmars.earth.domain.pojo.User;
/**
* Author: qing
* Date: 14-10-29
*/
public class LoginContextHolder {
private static final ThreadLocal<LoginContext> holder = new ThreadLocal<LoginContext>();
public static LoginContext get() {
return holder.get();
}
public static void set(LoginContext context) {
holder.set(context);
}
public static void clear() {
holder.remove();
}
public static User getLoginUser() {
LoginContext context = holder.get();
return context == null ? null : context.getUser();
}
}
package com.whatsmars.earth.domain.pojo;
import java.io.Serializable;
import java.util.Date;
import java.util.Set;
/**
* Created by shenhongxi on 2016/4/29.
*/
public class User implements Serializable {
private Integer id;
private String name;
private Integer gender;
private Integer organizationId;//如果是机构,此处为机构ID
private Integer teacherId;//如果用户位教师,此处位教师ID
private Integer adminId;//如果是管理员,此处位管理员ID
private Integer studentId;//如果是学生,此处为学生ID;
private int type;
private Date created;
private Date modified;
private Set<String> operations;//此用户允许的操作
private Date loginTime;
private String phone;
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 int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public Set<String> getOperations() {
return operations;
}
public void setOperations(Set<String> operations) {
this.operations = operations;
}
public Integer getOrganizationId() {
return organizationId;
}
public void setOrganizationId(Integer organizationId) {
this.organizationId = organizationId;
}
public Integer getTeacherId() {
return teacherId;
}
public void setTeacherId(Integer teacherId) {
this.teacherId = teacherId;
}
public Integer getAdminId() {
return adminId;
}
public void setAdminId(Integer adminId) {
this.adminId = adminId;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
package com.whatsmars.earth.domain.query;
import java.util.Date;
import java.util.Map;
/**
* Created by chenguang on 2015/6/3 0003.
*/
public class AccountFlowQuery extends BaseQuery {
private Date beginDate;
private String queryBeginDate;
private Date endDate;
private String queryEndDate;
private Integer type; //交易类型
private String phone;
public Map<String, Object> build() {
Map<String, Object> params = super.build();
params.put("beginDate", beginDate);
params.put("endDate", endDate);
params.put("type", type);
params.put("phone", phone);
return params;
}
public String queryString() {
StringBuffer sb = new StringBuffer();
sb.append("begin_date=");
sb.append(queryBeginDate == null ? "" : this.queryBeginDate);
sb.append("&end_date=");
sb.append(queryEndDate == null ? "" : this.queryEndDate);
sb.append("&type=");
sb.append(type == null ? "" : this.type);
sb.append("&phone=");
sb.append(phone == null ? "" : this.phone);
return sb.toString();
}
public Date getBeginDate() {
return beginDate;
}
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
}
public String getQueryBeginDate() {
return queryBeginDate;
}
public void setQueryBeginDate(String queryBeginDate) {
this.queryBeginDate = queryBeginDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getQueryEndDate() {
return queryEndDate;
}
public void setQueryEndDate(String queryEndDate) {
this.queryEndDate = queryEndDate;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
package com.whatsmars.earth.domain.util;
import java.math.BigDecimal;
/**
* Created by gongzaifei on 15/7/3.
*/
public class ArithUtils {
//默认除法运算精度
private static final int DEF_DIV_SCALE = 10;
//这个类不能实例化
private ArithUtils(){
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1,double v2){
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到
* 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1,double v2){
return div(v1,v2,DEF_DIV_SCALE);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指
* 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1,double v2,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v,int scale){
if(scale<0){
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one,scale,BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String [] args )throws Exception{
System.out.println(sub(2, 1));
System.out.println(div(100, 3));
System.out.println(mul(div(100, 3),3));
}
}
package com.itlong.whatsmars.earth.service.impl;
import com.itlong.whatsmars.common.pojo.Result;
import com.itlong.whatsmars.earth.dao.AccountDao;
import com.itlong.whatsmars.earth.service.AccountService;
import org.springframework.stereotype.Service;
/**
* Created by shenhongxi on 2016/4/1.
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
//@Autowired
//private TransactionTemplate transactionTemplate;
public Result hello(String name) {
Result result = new Result();
String hello = accountDao.hello(name);
result.addModel("hello", hello);
result.setSuccess(true);
//事务操作
// boolean isSuccess = transactionTemplate.execute(new TransactionCallback<Boolean>() {
// @Override
// public Boolean doInTransaction(TransactionStatus transactionStatus) {
//
// return false;
// }
// });
return result;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
}
@Override
public Result withdraw(final Double withdraw, String clientIp, String dealPassword, String phoneCode) {
final Result result = new Result();
Integer lenderId = LoginContextHolder.getLoginUser().getId();
try {
final LenderAccountDO account = this.lenderAccountManager.validateDealPassword(lenderId, dealPassword);
if (account == null) {
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("交易密码不正确");
return result;
}
if (StringUtils.isBlank(account.getBankName()) || StringUtils.isBlank(account.getBankCardId())){
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("您还未绑定银行卡");
return result;
}
if(account.getBalance() <= 0 || account.getBalanceFrozen() < 0) {
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("账户余额不足,无法提现");
return result;
}
//校验手机校验码是否正确
final LenderDO lender = lenderManager.getById(lenderId);
MongoCollection<Document> dbCollection = mongoDBClient.getCollection(Constants.MONGO_SMS_SEND_OPERATION_COLLECTION);
Bson parentFilter = Filters.and(Filters.eq("phone", lender.getPhone()), Filters.eq("type", withdrawPhoneCode));
Document document = dbCollection.find(parentFilter).limit(1).first();
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.addModel("flag", "code_error");
if (document == null) {
result.setMessage("验证码非法");
return result;
}
Long created = document.getLong("created");
if (created + 20 * 60000L <= System.currentTimeMillis()) {
result.setMessage("验证码已经过期");
return result;
}
if (!phoneCode.equals(document.get("checkCode"))) {
result.setMessage("验证码错误");
return result;
}
// 提现金额+手续费=交易总额
final Double amount = CalculatorUtils.format(withdraw + 2);
if (amount.compareTo(account.getBalance()) > 0){
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("账户余额不足");
return result;
}
final long time = System.currentTimeMillis();
//计算出商家订单号
final String orderId = "LW" + lenderId + "-" + time;
/**
* 发送提现请求
*/
String bankCardId = account.getBankCardId();
String top = bankCardId.substring(0, 6);
String last = bankCardId.substring(bankCardId.length() - 4, bankCardId.length());
final WithdrawRequestEntity requestEntity = new WithdrawRequestEntity();
requestEntity.setRequestId(orderId);
requestEntity.setIdentityId(lender.getCardId());
requestEntity.setCardTop(top);
requestEntity.setCardLast(last);
requestEntity.setAmount(((Double) (withdraw * 100)).intValue());
requestEntity.setClientIp(clientIp);
//事务操作
boolean isSuccess = transactionTemplate.execute(new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(TransactionStatus transactionStatus) {
try {
//修改投资人账户
Double balanceBefore = account.getBalance();
Double balanceAfter = CalculatorUtils.format(balanceBefore - amount);
Double frozenBefore = account.getBalanceFrozen();
Double frozenAfter = CalculatorUtils.format(frozenBefore + amount);
account.setBalance(balanceAfter);
account.setBalanceFrozen(frozenAfter);
lenderAccountManager.updateBalance(account);
//新建一条投资人流水
final LenderAccountFlowDO flow = new LenderAccountFlowDO();
flow.setLenderId(lender.getId());
flow.setLenderName(lender.getName());
flow.setLenderRealName(lender.getRealName());
flow.setPhone(lender.getPhone());
flow.setType(LenderFlowTypeEnum.WITHDRAW.code);
flow.setOrderId(orderId);
flow.setAmount(amount);
flow.setWithdraw(withdraw);
flow.setFee(2.0D);
flow.setDescription("提现金额:" + withdraw + "元;手续费2元。");
flow.setBalanceBefore(balanceBefore);
flow.setBalanceAfter(balanceAfter);
flow.setFrozenBefore(frozenBefore);
flow.setFrozenAfter(frozenAfter);
//将流水状态设为提现处理中
flow.setStatus(FlowStatusEnum.ONGOING.code);
lenderAccountFlowManager.insert(flow);
JSONObject responseJson = null;
try {
responseJson = TZTUtils.withdraw(requestEntity);
withdrawLogger.error(responseJson.toString());
} catch (Exception e) {
logger.error("lender withdraw request error, lenderId:" + lender.getId(), e);
result.setMessage("第三方支付系统繁忙,请稍后再试");
throw new RuntimeException(e);
}
if (responseJson.containsKey("error_code")) {
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("{" + responseJson.getString("error_code") + ":" + responseJson.getString("error_msg") + "}");
throw new RuntimeException("{" + responseJson.getString("error_code") + ":" + responseJson.getString("error_msg") + "}");
}
if (responseJson.containsKey("clientSignError")) {
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage(responseJson.getString("clientSignError"));
throw new RuntimeException(responseJson.getString("clientSignError"));
}
//提现请求状态:FAILURE:请求失败 SUCCESS:请求成功 UNKNOW:未知
String withdrawStatus = responseJson.getString("status");
if (withdrawStatus.equals("FAILURE")) {
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("提现请求失败,请稍后重试!");
throw new RuntimeException("提现请求失败,状态:" + withdrawStatus);
}
//易宝返回的商家订单号
String requestId = responseJson.getString("requestid");
if (!orderId.equals(requestId)) {
result.setResultCode(ResultCode.VALIDATE_FAILURE);
result.setMessage("订单号不一致,订单号:" + orderId);
throw new RuntimeException("订单号不一致,订单号:" + orderId);
}
//提现流水日志
buildFlowLog(flow, time);
return true;
} catch (Exception e) {
transactionStatus.setRollbackOnly();
}
return false;
}
});
result.setSuccess(isSuccess);
} catch (Exception e) {
logger.error("withdraw error, lenderId:" + lenderId, e);
result.setResultCode(ResultCode.SYSTEM_ERROR);
result.setMessage("系统错误,请稍后再试!");
}
return result;
}
\ No newline at end of file
package com.itlong.whatsmars.earth.service;
package com.whatsmars.earth.service;
import com.itlong.whatsmars.common.pojo.Result;
import com.itlong.whatsmars.earth.domain.query.OrganizationQuery;
import com.whatsmars.common.pojo.Result;
import com.whatsmars.earth.domain.query.OrganizationQuery;
/**
* Created by shenhongxi on 15/4/13.
......
package com.itlong.whatsmars.earth.support.web.listener;
import net.sf.json.JSONObject;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.stereotype.Service;
import javax.jms.*;
/**
* Created by liuguanqing on 15/5/18.
*/
@Service
public class TestListener implements MessageListener {
@Override
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage)message;
try {
JSONObject json = JSONObject.fromObject(textMessage.getText());
if(!json.has("flowId")) {
return;
}
int flowId = json.getInt("flowId");
String from = json.getString("from");
//......
//执行成功后,确认消息
message.acknowledge();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception{
sender();
Thread.sleep(3000);
receive();
}
public static void sender() throws Exception{
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://61.172.238.149:61616");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("_XHD_MQ_BIDDING.QUEUE");
MessageProducer producer = session.createProducer(queue);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
producer.send(session.createTextMessage("hello world!"));
producer.close();
}
public static void receive() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://61.172.238.149:61616");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("_XHD_MQ_RECHARGE.QUEUE");
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
System.out.println(message.toString());
}
});
connection.start();
}
}
package com.itlong.whatsmars.earth.support.web.service.uuid;
/**
* Created by shenhongxi on 2016/8/12.
*/
public class Config {
/**
* 业务名称
*/
private String name;
/**
* 内存运算个数
*/
private int cacheSize;
/**
* 生成自增数长度
*/
private int length;
/**
* 填充字符
*/
private String fillChar;
/**
* 前缀
*/
private String prefix;
/**
* 后缀
*/
private String suffix;
/**
* 自增预警数
*/
private long warnNum;
/**
* 重置数
*/
private long resetNum;
/**
* 1 uuid=前缀+自增数+后缀
*/
private int strategy;
public int getCacheSize() {
return cacheSize;
}
public void setCacheSize(int cacheSize) {
this.cacheSize = cacheSize;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public String getFillChar() {
return fillChar;
}
public void setFillChar(String fillChar) {
this.fillChar = fillChar;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public long getWarnNum() {
return warnNum;
}
public void setWarnNum(long warnNum) {
this.warnNum = warnNum;
}
public long getResetNum() {
return resetNum;
}
public void setResetNum(long resetNum) {
this.resetNum = resetNum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStrategy() {
return strategy;
}
public void setStrategy(int strategy) {
this.strategy = strategy;
}
}
package com.itlong.whatsmars.earth.support.web.service.uuid;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by shenhongxi on 2016/8/12.
*/
public class Main {
static ApplicationContext context;
public static void init() {
context = new ClassPathXmlApplicationContext("classpath*:spring-config.xml");
}
public static void main(String[] args) {
init();
UuidContext.init();
UuidServiceImpl uuidService = (UuidServiceImpl) context.getBean("uuidService");
Thread t = new TestThread("TESTPSBC", uuidService);
Thread t1 = new TestThread("TESTPSBC", uuidService);
Thread t2 = new TestThread("TESTPSBC", uuidService);
Thread t3 = new TestThread("TESTPSBC", uuidService);
Thread t4 = new TestThread("TEST5CMB", uuidService);
Thread t5 = new TestThread("TEST5CMB", uuidService);
Thread t6 = new TestThread("TEST5CMB", uuidService);
Thread t7 = new TestThread("TEST5CMB", uuidService);
t.start();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
}
}
package com.itlong.whatsmars.earth.support.web.service.uuid;
public class TestThread extends Thread{
String name;
UuidServiceImpl us;
public TestThread(String name, UuidServiceImpl us) {
this.name = name;
this.us = us;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + ":" + us.nextUuid(name));
}
}
}
package com.itlong.whatsmars.earth.support.web.service.uuid;
/**
* Created by shenhongxi on 2016/8/12.
*/
public interface UuidService {
/**
* 获取自增id,从1开始
* @param name
* @return
*/
String nextUuid(String name);
}
package com.whatsmars.earth.support.web;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
/**
* Author: qing
* Date: 14-11-7
*/
public class ExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mav = new ModelAndView();
try{
mav.setViewName("redirect:/error.jhtml?messages=" + URLEncoder.encode(ex.getMessage(),"utf-8"));
} catch (Exception e) {
mav.setViewName("redirect:/error.jhtml");
}
return mav;
}
}
package com.whatsmars.earth.support.web.service.uuid;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SpringHelper implements ServletContextListener {
private static ServletContext servletContext = null;
private static final String SPRING_XML_CLASS_PATH_STR = "classpath*:spring*.xml";
private static ApplicationContext noContainerCtxt = null;
public static ApplicationContext getContext(){
if(servletContext != null)
return WebApplicationContextUtils.getWebApplicationContext(servletContext);
if(noContainerCtxt != null)
return noContainerCtxt;
synchronized (SPRING_XML_CLASS_PATH_STR) {
if(noContainerCtxt == null){
noContainerCtxt = new ClassPathXmlApplicationContext(new String[]{SPRING_XML_CLASS_PATH_STR});
}
}
return noContainerCtxt;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name, Class<T> clazz) {
return (T)getContext().getBean(name, clazz);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
;
}
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
UuidContext.init();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.whatsmars.earth.support.web.service.uuid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Created by shenhongxi on 2016/8/12.
*/
public class UuidContext {
private static final Logger log = LoggerFactory.getLogger(UuidContext.class);
// 缓存DB中的截止数
public static ConcurrentMap<String, Long> endCache = new ConcurrentHashMap<String,Long>();
// 缓存当前增加到的数值
public static ConcurrentMap<String, Long> nowCache = new ConcurrentHashMap<String,Long>();
// 缓存共享对象
public static ConcurrentMap<String, UuidModel> uuidCache = new ConcurrentHashMap<String, UuidModel>();
// 缓存配置
public static ConcurrentMap<String, Config> configCache = new ConcurrentHashMap<String, Config>();
static UuidDao uuidDao;
public static void init(){
loadConfig();
uuidDao = SpringHelper.getBean("uuidDao", UuidDao.class);
List<UuidModel> list = uuidDao.getAll();
for (UuidModel um : list) {
Config cm = getConfig(um.getName());
updateUuid(um, cm.getLength());
loadMemory(um);
}
}
/**
* 根据名称更新号段 直至成功
* @param um
* @return
*/
public static UuidModel updateUuid(UuidModel um, int length){
boolean updated = false;
do{
UuidModel _um = uuidDao.findByName(um.getName());
int cacheSize = 1000;
Config config = getConfig(um.getName());
if (config != null) {
cacheSize = config.getCacheSize();
}
// 判断是否需要重置 条件为:1.配置的重置数<新段的截止数 则需要重置
// 2.新段的截止数大于需要获取的位数 则需要重置
long resetNum = config.getResetNum();
// 取得新段的截止数
long newEnd = _um.getEnd() + cacheSize;
um.setOldEnd(_um.getEnd());
um.setOldStart(_um.getStart());
if ((resetNum < newEnd) || (String.valueOf(newEnd).length() > length)) {
// 需要重置为0开始段
um.setStart(0);
um.setEnd(cacheSize);
} else {
// 取新段
um.setStart(_um.getEnd());
um.setEnd(_um.getEnd() + cacheSize);
}
// 最终的更新成功保证了多实例部署时,各实例持有的号段不同
updated = uuidDao.update(um);
} while (!updated);
return um;
}
/**
* 载入内存
* @param um
*/
public static void loadMemory(UuidModel um){
endCache.put(um.getName(), um.getEnd());
nowCache.put(um.getName(), um.getStart());
uuidCache.put(um.getName(), um);
}
public static Config getConfig(String name) {
Config config = configCache.get(name);
if (config == null) {
config = configCache.get("default");
}
return config;
}
private static void loadConfig(){
try {
String businesses = AppConfig.getValue("businesses");
for(String biz : businesses.split(",")){
String bizConfig = AppConfig.getValue(biz);
String[] configs = bizConfig.split(",");
int cacheSize = Integer.valueOf(configs[0]);
int length = Integer.valueOf(configs[1]);
String fillChar = configs[2];
long warnNum = Long.valueOf(configs[3]);
long resetNum = Long.valueOf(configs[4]);
int tactics = Integer.valueOf(configs[5]);
Config config = new Config();
config.setCacheSize(cacheSize);
config.setFillChar(fillChar);
config.setLength(length);
config.setPrefix("");
config.setSuffix("");
config.setStrategy(tactics);
config.setResetNum(resetNum);
config.setWarnNum(warnNum);
config.setName(biz);
configCache.put(biz, config);
}
log.info("load config success");
} catch (Exception e) {
log.error("load config error", e);
}
}
}
package com.whatsmars.earth.support.web.service.uuid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by shenhongxi on 2016/8/12.
*/
public class UuidServiceImpl implements UuidService {
private static final Logger log = LoggerFactory.getLogger(UuidServiceImpl.class);
private UuidDao uuidDao;
@Override
public String nextUuid(String name) {
Config config = UuidContext.getConfig(name);
String format = config.getPrefix() + "#" + config.getSuffix();
if (config.getStrategy() == 0) {
// 使用策略0 日期+自增
String formatDate = format(new Date(), "yyMMdd");
format = formatDate + config.getPrefix() + "#" + config.getSuffix();
} else { // 其他策略
}
long nextUuid = nextUuid(name, config.getCacheSize(), config.getLength());
String value = formatUuid(nextUuid, config.getLength(), config.getFillChar());
return format.replace("#", value);
}
private synchronized long nextUuid(String name, int cacheSize, int length) {
UuidModel um = UuidContext.uuidCache.get(name);
Long nowUuid = null;
try {
if (um != null) {
synchronized (um) {
nowUuid = UuidContext.nowCache.get(name);
Config cm = UuidContext.getConfig(name);
// 判断是否到达预警值
if (UuidContext.nowCache.get(name).intValue() == cm.getWarnNum()) {
log.warn("警告:" + name + "号段已达到预警值.");
}
log.info("dbNum:" + UuidContext.endCache.get(name)
+ ",nowNum:" + UuidContext.nowCache.get(name));
// 判断内存中号段是否用完
if (UuidContext.nowCache.get(name).compareTo(UuidContext.endCache.get(name)) >= 0) {
// 更新号段
UuidContext.updateUuid(um, length);
nowUuid = um.getStart() + 1;
UuidContext.endCache.put(name, um.getEnd());
UuidContext.nowCache.put(name, nowUuid);
} else {
nowUuid += 1;
// 是否需要重置 判断自增号位数是否大于length参数
if (String.valueOf(nowUuid).length() > length) {
// 更新号段,需要重置
nowUuid = 1l;
UuidContext.updateUuid(um, 0);
UuidContext.endCache.put(name, um.getEnd());
UuidContext.nowCache.put(name, nowUuid);
UuidContext.uuidCache.put(name, um);
} else {
// 直接修改缓存的值就可以了
UuidContext.nowCache.put(name, nowUuid);
}
}
}
} else {
synchronized (this) {
um = UuidContext.uuidCache.get(name);
if (um != null) {
return nextUuid(name, cacheSize, length);
}
nowUuid = 1l;
// 如果缓存不存在,那么就新增到数据库
UuidModel um2 = new UuidModel();
um2.setName(name);
um2.setStart(0);
um2.setEnd(cacheSize);
uuidDao.insert(um2);
// 还要同时在缓存的map中加入
UuidContext.endCache.put(name, um2.getEnd());
UuidContext.nowCache.put(name, nowUuid);
UuidContext.uuidCache.put(name, um2);
}
}
} catch (Exception e) {
log.error("生成uuid error", e);
if (e.getMessage() != null && (e.getMessage().indexOf("UNIQUE KEY") >= 0 ||
e.getMessage().indexOf("PRIMARY KEY") >= 0)) {
UuidModel _um = new UuidModel();
_um.setName(name);
// 更新号段
UuidContext.updateUuid(_um, length);
// 载入缓存
UuidContext.loadMemory(_um);
// 继续获取
return nextUuid(name, cacheSize, length);
}
throw new RuntimeException("生成uuid error");
}
return nowUuid;
}
private static String format(Date time, String fmt) {
SimpleDateFormat sdf = new SimpleDateFormat(fmt);
return sdf.format(time);
}
private String formatUuid(long nextUuid, int length, String fillChar) {
StringBuffer buffer = new StringBuffer("");
int len = length - ("" + nextUuid).length();
for (int i = 0; i < len; i++) {
buffer.append(fillChar);
}
buffer.append("" + nextUuid);
return buffer.toString();
}
}
......@@ -30,7 +30,7 @@
<property name="targetMethod" value="execute"/>
<property name="concurrent" value="false"/>
</bean>
<bean id="lenderWithdrawJob" class="com.itlong.whatsmars.earth.support.web.service.job.TestJob" />
<bean id="lenderWithdrawJob" class="com.whatsmars.earth.support.web.service.job.TestJob" />
</beans>
\ No newline at end of file
package com.itlong.whatsmars.earth.web.controller;
import com.itlong.whatsmars.common.util.DESUtils;
import com.itlong.whatsmars.earth.domain.constants.Constants;
import com.itlong.whatsmars.earth.domain.misc.SystemConfig;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by javahongxi on 15/4/10.
*/
public class BaseController {
@Autowired(required = false)
protected SystemConfig systemConfig;
protected static final String TOKEN_KEY = "_mars001_token_";
/**
* 创建CXRF Token,避免表单重复提交或者跨站操作
* @param response 生成token,path为当前页面的路径,比如:/teacher
* @return
*/
public String createToken(HttpServletRequest request,HttpServletResponse response) {
String token = RandomStringUtils.random(32,true,true);
Cookie cookie = new Cookie(TOKEN_KEY,DESUtils.encrypt(token,Constants.HTTP_ENCRYPT_KEY));
cookie.setDomain(systemConfig.getCookieDomain());
cookie.setPath(this.getRequestPath(request));
//cookie.setMaxAge(TOKEN_MAX_AGE);
response.addCookie(cookie);
return token;
}
/**
* 当表单提交,且后台处理成功后,移除Token
* @param response
* @return
*/
public void removeToken(HttpServletRequest request,HttpServletResponse response) {
Cookie cookie = new Cookie(TOKEN_KEY,null);
cookie.setDomain(systemConfig.getCookieDomain());
cookie.setMaxAge(0);//立即过期
cookie.setPath(this.getRequestPath(request));
response.addCookie(cookie);
}
/**
* 从cookie中获取token的值
* @param request
* @return
*/
public String getToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if(cookies == null) {
return null;
}
for(Cookie cookie : cookies) {
if(cookie.getName().equals(TOKEN_KEY)) {
return DESUtils.decrypt(cookie.getValue(), Constants.HTTP_ENCRYPT_KEY);
}
}
return null;
}
/**
* 获取客户端的实际IP
* @param request
* @return
*/
public String getClientIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 从cookie中获取当期path下的验证码信息
* @param request
* @return
*/
public String getCurrentValidateCode(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if(cookies == null) {
return null;
}
for(Cookie cookie : cookies) {
if(cookie.getName().equals(Constants.VALIDATE_CODE_COOKIE_KEY)) {
String source = cookie.getValue();
return DESUtils.decrypt(source,Constants.HTTP_ENCRYPT_KEY);
}
}
return null;
}
/**
* 获取请求的path路径:比如“/user/test.jhtml”返回“/user”.
* @param request
* @return
*/
protected String getRequestPath(HttpServletRequest request) {
String servletPath = request.getServletPath();
int index = servletPath.lastIndexOf("/");
if(index == 0) {
return "/";
}
return servletPath.substring(0,index);
}
}
package com.whatsmars.earth.web.controller;
import com.whatsmars.common.pojo.Result;
import com.whatsmars.common.util.ResultHelper;
import com.whatsmars.earth.service.AccountService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by shenhongxi on 2016/4/1...
*/
@Controller
@RequestMapping("/account")
public class MarsController extends BaseController {
private Logger accountLogger = Logger.getLogger("account-logger");
@Autowired
private AccountService accountService;
// ex. http://localhost:8080/account/hello.jhtml?name=lily
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestParam("name")String name,
//@RequestParam("token")String token,
HttpServletRequest request,
HttpServletResponse response) {
// String source = this.getToken(request);
// if(!source.equals(token)) {
// return ResultHelper.renderAsJson(ResultCode.VALIDATE_FAILURE, "表单过期,请重新刷新页面");
// }
Result result = accountService.hello(name);
if (!result.isSuccess()) {
return ResultHelper.renderAsJson(result);
}
// this.removeToken(request, response);
result.setResponseUrl("/account/hello_success.jhtml");
return ResultHelper.renderAsJson(result);
}
@RequestMapping("/hello_success")
public ModelAndView index() {
ModelAndView mav = new ModelAndView();
//mav.addAllObjects(result.getAll());
mav.addObject("title", "Welcome to Whatsmars!");
return mav;
}
}
......@@ -5,5 +5,5 @@
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
default-autowire="byName">
<bean id="accountDao" class="com.itlong.whatsmars.earth.dao.impl.AccountDaoImpl" />
<bean id="accountDao" class="com.whatsmars.earth.dao.impl.AccountDaoImpl" />
</beans>
\ No newline at end of file
package com.whatsmars.job;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by javahongxi on 2017/10/31.
*/
public class Main {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("classpath:META-INF/applicationContext.xml");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.whatsmars.job.dataflow;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.dataflow.DataflowJob;
import com.whatsmars.job.fixture.entity.Foo;
import com.whatsmars.job.fixture.repository.FooRepository;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class SpringDataflowJob implements DataflowJob<Foo> {
@Resource
private FooRepository fooRepository;
@Override
public List<Foo> fetchData(final ShardingContext shardingContext) {
System.out.println(String.format("Item: %s | Time: %s | Thread: %s | %s",
shardingContext.getShardingItem(), new SimpleDateFormat("HH:mm:ss").format(new Date()), Thread.currentThread().getId(), "DATAFLOW FETCH"));
return fooRepository.findTodoData(shardingContext.getShardingParameter(), 10);
}
@Override
public void processData(final ShardingContext shardingContext, final List<Foo> data) {
System.out.println(String.format("Item: %s | Time: %s | Thread: %s | %s",
shardingContext.getShardingItem(), new SimpleDateFormat("HH:mm:ss").format(new Date()), Thread.currentThread().getId(), "DATAFLOW PROCESS"));
for (Foo each : data) {
fooRepository.setCompleted(each.getId());
}
}
}
......@@ -15,12 +15,12 @@
* </p>
*/
package com.itlong.whatsmars.job.simple;
package com.whatsmars.job.simple;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.itlong.whatsmars.job.fixture.entity.Foo;
import com.itlong.whatsmars.job.fixture.repository.FooRepository;
import com.whatsmars.job.fixture.entity.Foo;
import com.whatsmars.job.fixture.repository.FooRepository;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
......
package com.itlong.whatsmars.fs.web.filter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SecurityFilter implements HandlerInterceptor {
private static final Log logger = LogFactory.getLog(SecurityFilter.class);
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
package com.itlong.whatsmars.fs.web;
package com.whatsmars.fs.web;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
......
package com.itlong.whatsmars.fs.web.service;
package com.whatsmars.fs.web.service;
import com.itlong.whatsmars.common.pojo.Result;
import com.whatsmars.common.pojo.Result;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
......
......@@ -23,7 +23,7 @@
</mvc:message-converters>
</mvc:annotation-driven>
<context:component-scan base-package="com.itlong.whatsmars.fs.web.controller" />
<context:component-scan base-package="com.whatsmars.fs.web.controller" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
......
package com.itlong.whatsmars.base;
/**
* Created by shenhongxi on 2017/11/17.
*/
public class CodeBlockTest {
int a = 110;
static int b = 112;
// static CodeBlockTest instance = new CodeBlockTest(); // 这种情况输出的是2 3 1 4
static {
System.out.println("1 b=" + b); // b=112
}
{
System.out.println("2 a=" + a + " b=" + b); // a=110 b=112
}
CodeBlockTest() {
System.out.println("3 a=" + a + " b=" + b); // a=110 b=112
}
public static void main(String[] args) { // 1 2 3 2 3 4
new CodeBlockTest();
new CodeBlockTest();
System.out.println("4");
}
}
package com.itlong.whatsmars.base;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by shenhongxi on 15/7/24.
*/
public class PropertiesUtils {
private static Properties properties = new Properties();
static {
try {
InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream("conf.properties");
properties.load(in);
} catch (Exception e) {}
}
public static void main(String[] args) {
System.out.print(properties.getProperty("max"));
}
}
package com.itlong.whatsmars.base.dp.factory;
public class CarFactory extends VehicleFactory {
@Override
Moveable create() {
return new Car();
}
}
package com.itlong.whatsmars.base.dp.factory;
public class Plane implements Moveable {
@Override
public void run() {
System.out.println("plane run...");
}
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
public abstract class AbstractFactory {
abstract Vehicle createVehicle();
abstract Weapon createWeapon();
abstract Food createFood();
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
public class Apple extends Food {
public void printName() {
System.out.println("Apple...");
}
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
public class Car extends Vehicle {
public Car() {}
public void run() {
System.out.println("car running...");
}
}
package com.itlong.whatsmars.base.dp.factory.abstractfac;
public abstract class Food {
abstract void printName();
}
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册