提交 9655f086 编写于 作者: 武汉红喜's avatar 武汉红喜

remove whatsmars-earth

上级 80f24353
......@@ -16,7 +16,6 @@ Module | Intro
whatsmars-common | Utils公共模块
whatsmars-dbrouter | 分库分表实现
whatsmars-dubbo | 高性能分布式RPC框架
whatsmars-earth | springmvc+velocity实战
whatsmars-elasticjob | 分布式调度
whatsmars-elasticsearch | Elasticsearch
whatsmars-mq | 消息中间件RocketMQ,Kafka等
......
......@@ -30,7 +30,6 @@
<module>whatsmars-redis</module>
<module>whatsmars-spring-cloud</module>
<module>whatsmars-sharding-jdbc</module>
<module>whatsmars-earth</module>
<module>whatsmars-spring-boot-samples</module>
<module>whatsmars-elasticsearch</module>
<module>whatsmars-zk</module>
......
### spring-mvc + velocity 实战
- mvn clean package -DskipTests -Ptest (因使用了profile, 运行前请先执行这条命令)
- 用tomcat运行whatsmars-earth-web (tomcat请使用8.0以上版本)
### Spring MVC
![DispatcherServlet初始化主线的过程](springmvc.png)
![http请求处理路线](springmvc2.jpg)
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>whatsmars-parent</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<artifactId>whatsmars-earth</artifactId>
<packaging>pom</packaging>
<name>${project.artifactId}</name>
<description>springmvc + velocity 实战</description>
<modules>
<module>whatsmars-earth-domain</module>
<module>whatsmars-earth-dao</module>
<module>whatsmars-earth-service</module>
<module>whatsmars-earth-web</module>
<module>whatsmars-earth-support-web</module>
<module>whatsmars-earth-manager</module>
<module>whatsmars-earth-common</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>whatsmars-earth</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>whatsmars-earth-common</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>Earth Utils 公共模块</description>
<dependencies>
<!-- 图片压缩工具 -->
<dependency>
<groupId>org.imgscalr</groupId>
<artifactId>imgscalr-lib</artifactId>
<version>4.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.6</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.hongxi.whatsmars.earth.common;
/**
* Created by liuguanqing on 15/4/16.
*/
public class CommonConstants {
public static final String FS_SECURITY_KEY = "ELO7hccMHrZr3D6NrgwSOEwFycWh1Y9u";
}
package org.hongxi.whatsmars.earth.common;
/**
* Created by liuguanqing on 15/4/20.
*/
public enum ImageSizeEnum {
PIXELS_200(200, "x2"),
PIXELS_400(400, "x4"),
PIXELS_600(600, "x6"),
PIXELS_800(800, "x8"),
PIXELS_MAX(1024, "xm");//最大1024
public int size;
public String path;
ImageSizeEnum(int size, String path) {
this.size = size;
this.path = path;
}
public static ImageSizeEnum valueOfPath(String path) {
if(path == null) {
return null;
}
for(ImageSizeEnum e : ImageSizeEnum.values()) {
if(e.path.equalsIgnoreCase(path)) {
return e;
}
}
return null;
}
}
package org.hongxi.whatsmars.earth.common.mongo;
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.hongxi.whatsmars.earth.common.ImageSizeEnum;
import org.hongxi.whatsmars.earth.common.mongo.object.MongoDBConfig;
import org.hongxi.whatsmars.earth.common.mongo.object.MongoDBCredential;
import org.hongxi.whatsmars.earth.common.mongo.object.MongoDBDriver;
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 org.hongxi.whatsmars.earth.common.mongo;
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 org.hongxi.whatsmars.earth.common.mongo.object.MongoDBConfig;
import org.hongxi.whatsmars.earth.common.mongo.object.MongoDBCredential;
import org.hongxi.whatsmars.earth.common.mongo.object.MongoDBDriver;
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 org.hongxi.whatsmars.earth.common.mongo.object;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import java.util.ArrayList;
import java.util.List;
/**
* Author: qing
* Date: 14-10-12
*/
public class MongoDBConfig {
private String addresses;
private List<MongoDBCredential> credentials;
public String getAddresses() {
return addresses;
}
public void setAddresses(String addresses) {
this.addresses = addresses;
}
public List<MongoDBCredential> getCredentials() {
return credentials;
}
public void setCredentials(List<MongoDBCredential> credentials) {
this.credentials = credentials;
}
public List<MongoCredential> buildCredentials() {
List<MongoCredential> mongoCredentials = new ArrayList<MongoCredential>();
for(MongoDBCredential item : this.credentials) {
MongoCredential credential = MongoCredential.createCredential(item.getUsername(),item.getDatabaseName(),item.getPassword().toCharArray());
mongoCredentials.add(credential);
}
return mongoCredentials;
}
public List<ServerAddress> buildAddresses() throws Exception{
List<ServerAddress> serverAddresses = new ArrayList<ServerAddress>();
String[] sources = addresses.split(";");
for(String item : sources) {
String[] hp = item.split(":");
serverAddresses.add(new ServerAddress(hp[0],Integer.valueOf(hp[1])));
}
return serverAddresses;
}
}
package org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.common.mongo.object;
import org.bson.types.ObjectId;
public class ObjectIdCreator{
public static String creator(){
return new ObjectId().toString();
}
}
package org.hongxi.whatsmars.earth.common.mongo.serializer;
import org.apache.commons.lang.time.DateUtils;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
public class CustomDateDeserializer extends JsonDeserializer<Date> {
private static final String[] pattern = { "yyyy-MM-dd HH:mm:ss" };
@Override
public Date deserialize(JsonParser arg0, DeserializationContext arg1)
throws IOException, JsonProcessingException {
if (JsonToken.VALUE_STRING.equals(arg0.getCurrentToken())) {
try {
return DateUtils.parseDate(arg0.getText(), pattern);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
package org.hongxi.whatsmars.earth.common.mongo.serializer;
import org.apache.commons.lang.time.DateFormatUtils;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;
import java.io.IOException;
import java.util.Date;
public class CustomDateSerializer extends JsonSerializer<Date> {
private static final String pattern = "yyyy-MM-dd HH:mm:ss";
@Override
public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(DateFormatUtils.format(value, pattern));
}
}
\ No newline at end of file
package org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.common.util;
import javax.mail.PasswordAuthentication;
/**
* Created by Administrator on 2015/4/10 0010.
*/
public class Authenticator extends javax.mail.Authenticator {
private String userName;
private String password;
public Authenticator(){
}
public Authenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
package org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.common.util;
import java.util.HashMap;
import java.util.Map;
/**
* Created by jenny on 4/13/15.
* 根据邮箱获取域名,找到邮箱登陆页
*/
public class EmailUtils {
private static final String MAIL_126 = "http://mail.126.com/";
private static final String MAIL_163 = "http://mail.163.com/";
private static final String MAIL_QQ = "https://mail.qq.com/cgi-bin/loginpage";
private static final String MAIL_SINA = "http://mail.sina.com.cn/";
private static final String MAIL_HOTMAIL = "http://hotmail.msn.com/";
private static final String MAIL_GMAIL = "http://mail.google.com/";
private static final String MAIL_YAHOO = "https://login.yahoo.com/config/mail?.src=ym&.intl=hk";
private static final String MAIL_ALIYUN = "https://mail.aliyun.com/";
private static final String MAIL_139 = "http://mail.10086.cn/";
private static final String MAIL_189 = "http://webmail30.189.cn/w2/";
private static final String MAIL_SOHU = "http://mail.sohu.com/";
private static final Map <String ,String> EMAIL_MAP = new HashMap<String,String>();
static {
EMAIL_MAP.put("126.com", MAIL_126);
EMAIL_MAP.put("163.com", MAIL_163);
EMAIL_MAP.put("qq.com", MAIL_QQ);
EMAIL_MAP.put("sina.cn", MAIL_SINA);
EMAIL_MAP.put("sina.com", MAIL_SINA);
EMAIL_MAP.put("hotmail.com", MAIL_HOTMAIL);
EMAIL_MAP.put("gmail.com", MAIL_GMAIL);
EMAIL_MAP.put("yahoo.com", MAIL_YAHOO);
EMAIL_MAP.put("aliyun.com", MAIL_ALIYUN);
EMAIL_MAP.put("139.com", MAIL_139);
EMAIL_MAP.put("189.cn", MAIL_189);
EMAIL_MAP.put("sohu.com", MAIL_SOHU);
}
public static String getEmailLoginPage(String email){
int index = email.lastIndexOf("@");
if(index == -1) {
return null;
}
return EMAIL_MAP.get(email.substring(index + 1));
}
}
package org.hongxi.whatsmars.earth.common.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author cuichengrui
* Date 2015/4/28
* 身份证工具类
*/
public class IdCardUtils {
/** 中国公民身份证号码最小长度。 */
public static final int CHINA_ID_MIN_LENGTH = 15;
/** 中国公民身份证号码最大长度。 */
public static final int CHINA_ID_MAX_LENGTH = 18;
/** 省、直辖市代码表 */
public static final String cityCode[] = {
"11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41",
"42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71",
"81", "82", "91"
};
/** 每位加权因子 */
public static final int power[] = {
7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2
};
/** 第18位校检码 */
public static final String verifyCode[] = {
"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"
};
/** 最低年限 */
public static final int MIN = 1930;
public static Map<String, String> cityCodes = new HashMap<String, String>();
/** 台湾身份首字母对应数字 */
public static Map<String, Integer> twFirstCode = new HashMap<String, Integer>();
/** 香港身份首字母对应数字 */
public static Map<String, Integer> hkFirstCode = new HashMap<String, Integer>();
static {
cityCodes.put("11", "北京");
cityCodes.put("12", "天津");
cityCodes.put("13", "河北");
cityCodes.put("14", "山西");
cityCodes.put("15", "内蒙古");
cityCodes.put("21", "辽宁");
cityCodes.put("22", "吉林");
cityCodes.put("23", "黑龙江");
cityCodes.put("31", "上海");
cityCodes.put("32", "江苏");
cityCodes.put("33", "浙江");
cityCodes.put("34", "安徽");
cityCodes.put("35", "福建");
cityCodes.put("36", "江西");
cityCodes.put("37", "山东");
cityCodes.put("41", "河南");
cityCodes.put("42", "湖北");
cityCodes.put("43", "湖南");
cityCodes.put("44", "广东");
cityCodes.put("45", "广西");
cityCodes.put("46", "海南");
cityCodes.put("50", "重庆");
cityCodes.put("51", "四川");
cityCodes.put("52", "贵州");
cityCodes.put("53", "云南");
cityCodes.put("54", "西藏");
cityCodes.put("61", "陕西");
cityCodes.put("62", "甘肃");
cityCodes.put("63", "青海");
cityCodes.put("64", "宁夏");
cityCodes.put("65", "新疆");
cityCodes.put("71", "台湾");
cityCodes.put("81", "香港");
cityCodes.put("82", "澳门");
cityCodes.put("91", "国外");
twFirstCode.put("A", 10);
twFirstCode.put("B", 11);
twFirstCode.put("C", 12);
twFirstCode.put("D", 13);
twFirstCode.put("E", 14);
twFirstCode.put("F", 15);
twFirstCode.put("G", 16);
twFirstCode.put("H", 17);
twFirstCode.put("J", 18);
twFirstCode.put("K", 19);
twFirstCode.put("L", 20);
twFirstCode.put("M", 21);
twFirstCode.put("N", 22);
twFirstCode.put("P", 23);
twFirstCode.put("Q", 24);
twFirstCode.put("R", 25);
twFirstCode.put("S", 26);
twFirstCode.put("T", 27);
twFirstCode.put("U", 28);
twFirstCode.put("V", 29);
twFirstCode.put("X", 30);
twFirstCode.put("Y", 31);
twFirstCode.put("W", 32);
twFirstCode.put("Z", 33);
twFirstCode.put("I", 34);
twFirstCode.put("O", 35);
hkFirstCode.put("A", 1);
hkFirstCode.put("B", 2);
hkFirstCode.put("C", 3);
hkFirstCode.put("R", 18);
hkFirstCode.put("U", 21);
hkFirstCode.put("Z", 26);
hkFirstCode.put("X", 24);
hkFirstCode.put("W", 23);
hkFirstCode.put("O", 15);
hkFirstCode.put("N", 14);
}
/**
* 将15位身份证号码转换为18位
*
* @param idCard
* 15位身份编码
* @return 18位身份编码
*/
public static String conver15CardTo18(String idCard) {
String idCard18 = "";
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return null;
}
if (isNum(idCard)) {
// 获取出生年月日
String birthday = idCard.substring(6, 12);
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yyMMdd").parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
if (birthDate != null)
cal.setTime(birthDate);
// 获取出生年(完全表现形式,如:2010)
String sYear = String.valueOf(cal.get(Calendar.YEAR));
idCard18 = idCard.substring(0, 6) + sYear + idCard.substring(8);
// 转换字符数组
char[] cArr = idCard18.toCharArray();
if (cArr != null) {
int[] iCard = convertCharToInt(cArr);
int iSum17 = getPowerSum(iCard);
// 获取校验位
String sVal = getCheckCode18(iSum17);
if (sVal.length() > 0) {
idCard18 += sVal;
} else {
return null;
}
}
} else {
return null;
}
return idCard18;
}
/**
* 验证身份证是否合法
*/
public static boolean validateCard(String idCard) {
String card = idCard.trim();
if (validateIdCard18(card)) {
return true;
}
if (validateIdCard15(card)) {
return true;
}
String[] cardval = validateIdCard10(card);
if (cardval != null) {
if (cardval[2].equals("true")) {
return true;
}
}
return false;
}
/**
* 验证18位身份编码是否合法
*
* @param idCard 身份编码
* @return 是否合法
*/
public static boolean validateIdCard18(String idCard) {
boolean bTrue = false;
if (idCard.length() == CHINA_ID_MAX_LENGTH) {
// 前17位
String code17 = idCard.substring(0, 17);
// 第18位
String code18 = idCard.substring(17, CHINA_ID_MAX_LENGTH);
if (isNum(code17)) {
char[] cArr = code17.toCharArray();
if (cArr != null) {
int[] iCard = convertCharToInt(cArr);
int iSum17 = getPowerSum(iCard);
// 获取校验位
String val = getCheckCode18(iSum17);
if (val.length() > 0) {
if (val.equalsIgnoreCase(code18)) {
bTrue = true;
}
}
}
}
}
return bTrue;
}
/**
* 验证15位身份编码是否合法
*
* @param idCard
* 身份编码
* @return 是否合法
*/
public static boolean validateIdCard15(String idCard) {
if (idCard.length() != CHINA_ID_MIN_LENGTH) {
return false;
}
if (isNum(idCard)) {
String proCode = idCard.substring(0, 2);
if (cityCodes.get(proCode) == null) {
return false;
}
String birthCode = idCard.substring(6, 12);
Date birthDate = null;
try {
birthDate = new SimpleDateFormat("yy").parse(birthCode.substring(0, 2));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
if (birthDate != null)
cal.setTime(birthDate);
if (!validateDate(cal.get(Calendar.YEAR), Integer.valueOf(birthCode.substring(2, 4)),
Integer.valueOf(birthCode.substring(4, 6)))) {
return false;
}
} else {
return false;
}
return true;
}
/**
* 验证10位身份编码是否合法
*
* @param idCard 身份编码
* @return 身份证信息数组
* <p>
* [0] - 台湾、澳门、香港 [1] - 性别(男M,女F,未知N) [2] - 是否合法(合法true,不合法false)
* 若不是身份证件号码则返回null
* </p>
*/
public static String[] validateIdCard10(String idCard) {
String[] info = new String[3];
String card = idCard.replaceAll("[\\(|\\)]", "");
if (card.length() != 8 && card.length() != 9 && idCard.length() != 10) {
return null;
}
if (idCard.matches("^[a-zA-Z][0-9]{9}$")) { // 台湾
info[0] = "台湾";
System.out.println("11111");
String char2 = idCard.substring(1, 2);
if (char2.equals("1")) {
info[1] = "M";
System.out.println("MMMMMMM");
} else if (char2.equals("2")) {
info[1] = "F";
System.out.println("FFFFFFF");
} else {
info[1] = "N";
info[2] = "false";
System.out.println("NNNN");
return info;
}
info[2] = validateTWCard(idCard) ? "true" : "false";
} else if (idCard.matches("^[1|5|7][0-9]{6}\\(?[0-9A-Z]\\)?$")) { // 澳门
info[0] = "澳门";
info[1] = "N";
// TODO
} else if (idCard.matches("^[A-Z]{1,2}[0-9]{6}\\(?[0-9A]\\)?$")) { // 香港
info[0] = "香港";
info[1] = "N";
info[2] = validateHKCard(idCard) ? "true" : "false";
} else {
return null;
}
return info;
}
/**
* 验证台湾身份证号码
*
* @param idCard
* 身份证号码
* @return 验证码是否符合
*/
public static boolean validateTWCard(String idCard) {
String start = idCard.substring(0, 1);
String mid = idCard.substring(1, 9);
String end = idCard.substring(9, 10);
Integer iStart = twFirstCode.get(start);
Integer sum = iStart / 10 + (iStart % 10) * 9;
char[] chars = mid.toCharArray();
Integer iflag = 8;
for (char c : chars) {
sum = sum + Integer.valueOf(c + "") * iflag;
iflag--;
}
return (sum % 10 == 0 ? 0 : (10 - sum % 10)) == Integer.valueOf(end) ? true : false;
}
/**
* 验证香港身份证号码(存在Bug,部份特殊身份证无法检查)
* <p>
* 身份证前2位为英文字符,如果只出现一个英文字符则表示第一位是空格,对应数字58 前2位英文字符A-Z分别对应数字10-35
* 最后一位校验码为0-9的数字加上字符"A","A"代表10
* </p>
* <p>
* 将身份证号码全部转换为数字,分别对应乘9-1相加的总和,整除11则证件号码有效
* </p>
*
* @param idCard 身份证号码
* @return 验证码是否符合
*/
public static boolean validateHKCard(String idCard) {
String card = idCard.replaceAll("[\\(|\\)]", "");
Integer sum = 0;
if (card.length() == 9) {
sum = (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 9
+ (Integer.valueOf(card.substring(1, 2).toUpperCase().toCharArray()[0]) - 55) * 8;
card = card.substring(1, 9);
} else {
sum = 522 + (Integer.valueOf(card.substring(0, 1).toUpperCase().toCharArray()[0]) - 55) * 8;
}
String mid = card.substring(1, 7);
String end = card.substring(7, 8);
char[] chars = mid.toCharArray();
Integer iflag = 7;
for (char c : chars) {
sum = sum + Integer.valueOf(c + "") * iflag;
iflag--;
}
if (end.toUpperCase().equals("A")) {
sum = sum + 10;
} else {
sum = sum + Integer.valueOf(end);
}
return (sum % 11 == 0) ? true : false;
}
/**
* 将字符数组转换成数字数组
*
* @param ca
* 字符数组
* @return 数字数组
*/
public static int[] convertCharToInt(char[] ca) {
int len = ca.length;
int[] iArr = new int[len];
try {
for (int i = 0; i < len; i++) {
iArr[i] = Integer.parseInt(String.valueOf(ca[i]));
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
return iArr;
}
/**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值
*
* @param iArr
* @return 身份证编码。
*/
public static int getPowerSum(int[] iArr) {
int iSum = 0;
if (power.length == iArr.length) {
for (int i = 0; i < iArr.length; i++) {
for (int j = 0; j < power.length; j++) {
if (i == j) {
iSum = iSum + iArr[i] * power[j];
}
}
}
}
return iSum;
}
/**
* 将power和值与11取模获得余数进行校验码判断
*
* @param iSum
* @return 校验位
*/
public static String getCheckCode18(int iSum) {
String sCode = "";
switch (iSum % 11) {
case 10:
sCode = "2";
break;
case 9:
sCode = "3";
break;
case 8:
sCode = "4";
break;
case 7:
sCode = "5";
break;
case 6:
sCode = "6";
break;
case 5:
sCode = "7";
break;
case 4:
sCode = "8";
break;
case 3:
sCode = "9";
break;
case 2:
sCode = "x";
break;
case 1:
sCode = "0";
break;
case 0:
sCode = "1";
break;
}
return sCode;
}
/**
* 根据身份编号获取年龄
*
* @param idCard
* 身份编号
* @return 年龄
*/
public static int getAgeByIdCard(String idCard) {
int iAge = 0;
if (idCard.length() == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
String year = idCard.substring(6, 10);
Calendar cal = Calendar.getInstance();
int iCurrYear = cal.get(Calendar.YEAR);
iAge = iCurrYear - Integer.valueOf(year);
return iAge;
}
/**
* 根据身份编号获取生日
*
* @param idCard 身份编号
* @return 生日(yyyy-MM-dd)
*/
public static String getBirthByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return idCard.substring(6, 10)+"-"+idCard.substring(10,12)+"-"+idCard.substring(12,14);
}
/**
* 根据身份编号获取生日年
*
* @param idCard 身份编号
* @return 生日(yyyy)
*/
public static Short getYearByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return Short.valueOf(idCard.substring(6, 10));
}
/**
* 根据身份编号获取生日月
*
* @param idCard
* 身份编号
* @return 生日(MM)
*/
public static Short getMonthByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return Short.valueOf(idCard.substring(10, 12));
}
/**
* 根据身份编号获取生日天
*
* @param idCard
* 身份编号
* @return 生日(dd)
*/
public static Short getDateByIdCard(String idCard) {
Integer len = idCard.length();
if (len < CHINA_ID_MIN_LENGTH) {
return null;
} else if (len == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
return Short.valueOf(idCard.substring(12, 14));
}
/**
* 根据身份编号获取性别
*
* @param idCard 身份编号
* @return 性别(M-男,F-女,N-未知)
*/
public static String getGenderByIdCard(String idCard) {
String sGender = "N";
if (idCard.length() == CHINA_ID_MIN_LENGTH) {
idCard = conver15CardTo18(idCard);
}
String sCardNum = idCard.substring(16, 17);
if (Integer.parseInt(sCardNum) % 2 != 0) {
sGender = "M";
} else {
sGender = "F";
}
return sGender;
}
/**
* 根据身份编号获取户籍省份
*
* @param idCard 身份编码
* @return 省级编码。
*/
public static String getProvinceByIdCard(String idCard) {
int len = idCard.length();
String sProvince = null;
String sProvinNum = "";
if (len == CHINA_ID_MIN_LENGTH || len == CHINA_ID_MAX_LENGTH) {
sProvinNum = idCard.substring(0, 2);
}
sProvince = cityCodes.get(sProvinNum);
return sProvince;
}
/**
* 数字验证
*
* @param val
* @return 提取的数字。
*/
public static boolean isNum(String val) {
return val == null || "".equals(val) ? false : val.matches("^[0-9]*$");
}
/**
* 验证小于当前日期 是否有效
*
* @param iYear
* 待验证日期(年)
* @param iMonth
* 待验证日期(月 1-12)
* @param iDate
* 待验证日期(日)
* @return 是否有效
*/
public static boolean validateDate(int iYear, int iMonth, int iDate) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int datePerMonth;
if (iYear < MIN || iYear >= year) {
return false;
}
if (iMonth < 1 || iMonth > 12) {
return false;
}
switch (iMonth) {
case 4:
case 6:
case 9:
case 11:
datePerMonth = 30;
break;
case 2:
boolean dm = ((iYear % 4 == 0 && iYear % 100 != 0) || (iYear % 400 == 0))
&& (iYear > MIN && iYear < year);
datePerMonth = dm ? 29 : 28;
break;
default:
datePerMonth = 31;
}
return (iDate >= 1) && (iDate <= datePerMonth);
}
}
package org.hongxi.whatsmars.earth.common.util;
import org.codehaus.jackson.map.ObjectMapper;
import org.hongxi.whatsmars.earth.common.pojo.Result;
/**
* qing
* JSON字符串与java object之间的互相转换
*
*/
public class JSONConverterUtils {
/**
* if not static,performance will be cost so much;but if you have self config,
* please get your own instance;
*/
private static final ObjectMapper mapper = new ObjectMapper();
public static <T> T converter(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String converter(Object obj) {
try{
return mapper.writeValueAsString(obj);
}catch(Exception e){
throw new RuntimeException(e);
}
}
public static void main(String[] args){
Result result = new Result();
result.setSuccess(true);
result.setResponseUrl("/test.jhtml");
result.addModel("test","test");
String json = JSONConverterUtils.converter(result);
System.out.println(json);
}
}
package org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.common.util;
import net.sf.json.JSONObject;
import org.hongxi.whatsmars.earth.common.pojo.Result;
import org.hongxi.whatsmars.earth.common.pojo.ResultCode;
import java.util.Map;
/**
* Author: qing
* Date: 14-10-14
*/
public class ResultHelper {
/**
* 页面渲染
* @param result
* @return
*/
public static String renderAsJson(Result result) {
JSONObject source = new JSONObject();
source.put("code",result.getResultCode().code);
source.put("message",result.getResultCode().getMessage());
if(result.getMessage() != null) {
source.put("message",result.getMessage());
}
//渲染实际的数据
Map<String,Object> model = result.getAll();
String responseUrl = result.getResponseUrl();
if(responseUrl != null) {
model.put("_redirect_url",responseUrl);
}
source.put("data",model);
return source.toString();
}
public static String renderAsJson(ResultCode resultCode) {
return renderAsJson(resultCode,null);
}
/**
* 直接跳转URL
* @param responseUrl
* @return
*/
public static String renderAsJson(String responseUrl) {
Result result = new Result();
result.setSuccess(true);
result.setResponseUrl(responseUrl);
return renderAsJson(result);
}
/**
* 直接提示信息
* @param resultCode
* @param message
* @return
*/
public static String renderAsJson(ResultCode resultCode,String message) {
JSONObject source = new JSONObject();
source.put("code",resultCode.code);
if(message == null) {
source.put("message", resultCode.getMessage());
}else {
source.put("message",message);
}
return source.toString();
}
}
package org.hongxi.whatsmars.earth.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 org.hongxi.whatsmars.earth.common.util;
import org.apache.commons.lang.StringUtils;
import java.util.regex.Pattern;
/**
* Created by jenny on 4/10/15.
* 校验数据格式是否正确
*/
public class ValidateUtils {
private static final String EMAIL = "^[a-z0-9]([a-z0-9]*[-_\\.\\+]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\\.][a-z]{2,3}([\\.][a-z]{2,4})?$";
private static final String CARD_ID = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}(\\d|X|x)$";
private static final String CHINA_TEXT="[\\u4e00-\\u9fa5]+";
private static final String PHONE_CHINA_TELECOM = "^1[3578][01379]\\d{8}$";
private static final String PHONE_CHINA_UNION = "^1[34578][01256]\\d{8}$";
private static final String PHONE_CHINA_MOBILE = "^(134[012345678]\\d{7}|1[34578][012356789]\\d{8})$";
/**
* validate Email
*
* @param email
* @return
*/
public static boolean validateEmail(String email) {
if (StringUtils.isBlank(email)) {
return false;
}
return Pattern.matches(EMAIL, email);
}
/**
*
* @param phone
* @return
*/
public static boolean validatePhone(String phone) {
if (StringUtils.isBlank(phone)) {
return false;
}
return Pattern.matches(PHONE_CHINA_TELECOM, phone) || Pattern.matches(PHONE_CHINA_UNION, phone) || Pattern.matches(PHONE_CHINA_MOBILE, phone);
}
/**
* 检测身份证格式是否正确
* @param cardId
* @return
*/
public static boolean validateCardId(String cardId) {
if (StringUtils.isBlank(cardId)) {
return false;
}
return Pattern.matches(CARD_ID, cardId);
}
/**
* 验证字符串是否是中文
* @param chinaText
* @return
*/
public static boolean validateChineseText(String chinaText){
if(StringUtils.isBlank(chinaText)){
return false;
}
return Pattern.matches(CHINA_TEXT,chinaText);
}
/**
* 正则表达式:验证非零的正整数
* @param str
* @return
*/
public static boolean validateNonZeroPositiveInteger(String str)
{
Pattern pattern= Pattern.compile("^[0-9]*$");
java.util.regex.Matcher match=pattern.matcher(str);
if(match.matches()==false)
{
return false;
}
else
{
return true;
}
}
/**
* 正则表达式:验证是否为所要求的金额类型
* 正浮点数
* @param str
* @return
*/
public static boolean validateCurrency(String str)
{
Pattern pattern= Pattern.compile("^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$");
java.util.regex.Matcher match=pattern.matcher(str);
if(match.matches()==false)
{
return false;
}
else
{
return true;
}
}
/**
* 密码格式不能是纯字母或纯数字
* @param str
* @return
*/
public static boolean validatePassword(String str) {
if(str.matches("[a-zA-Z]+") || str.matches("[0-9]+")) {
return false;
}
return true;
}
}
package org.hongxi.whatsmars.earth.common.util;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.log.NullLogChute;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
/**
* Created by cuichengrui on 2015/5/26.
* 使用 Velocity 模板引擎快速生成文本或文件
*/
public class VelocityUtils {
private static final String CHARSET_UTF8 = "UTF-8";
private static final Velocity velocity = new Velocity();
static {
//设置从classpath中加载模板文件
velocity.setProperty(Velocity.RESOURCE_LOADER, "class");
velocity.setProperty("class.resource.loader.class","org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new NullLogChute());
velocity.setProperty(Velocity.INPUT_ENCODING, CHARSET_UTF8);
velocity.setProperty(Velocity.OUTPUT_ENCODING, CHARSET_UTF8);
velocity.init();
}
public static String render(String vm, Map<String,Object> model) {
VelocityContext context = new VelocityContext();
for (Map.Entry<String, Object> entry : model.entrySet()){
context.put(entry.getKey(), entry.getValue());
}
try {
Template template = velocity.getTemplate(vm);
StringWriter sw = new StringWriter();
BufferedWriter writer = new BufferedWriter(sw);
template.merge(context, writer);
writer.flush();
writer.close();
return sw.toString();
} catch (IOException e) {
throw new RuntimeException("velocity to text error.");
}
}
public static void main(String[] args) {
String text = render("contract_loan.vm",new HashMap<String, Object>());
System.out.println(text);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>whatsmars-earth</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<artifactId>whatsmars-earth-dao</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>DAO - 数据访问层</description>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<dependencies>
<dependency>
<groupId>org.hongxi</groupId>
<artifactId>whatsmars-earth-domain</artifactId>
<version>Rocket.S2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.hongxi.whatsmars.earth.dao;
/**
* Created by shenhongxi on 2016/4/1.
*/
public interface AccountDao {
public String hello(String name);
}
package org.hongxi.whatsmars.earth.dao;
import org.hongxi.whatsmars.earth.domain.pojo.City;
import java.util.List;
/**
* Created by shenhongxi on 2018/1/16.
*/
public interface CityDao {
List<City> getByPid(String pid);
}
package org.hongxi.whatsmars.earth.dao;
import org.hongxi.whatsmars.earth.domain.pojo.Organization;
import org.hongxi.whatsmars.earth.domain.query.OrganizationQuery;
import org.hongxi.whatsmars.earth.domain.query.QueryResult;
/**
* Created by shenhongxi on 2016/4/6.
*/
public interface OrganizationDao {
public QueryResult<Organization> query(OrganizationQuery query);
}
package org.hongxi.whatsmars.earth.dao;
import org.hongxi.whatsmars.earth.domain.pojo.User;
/**
* Created by javahongxi on 2017/12/24.
*/
public interface UserDao {
void createIfNotExistsTable();
User findByUsername(String username);
void insert(User user);
}
package org.hongxi.whatsmars.earth.dao.impl;
import org.hongxi.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 org.hongxi.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 org.hongxi.whatsmars.earth.dao.impl;
import org.hongxi.whatsmars.earth.dao.CityDao;
import org.hongxi.whatsmars.earth.domain.pojo.City;
import java.util.List;
/**
* Created by shenhongxi on 2018/11/28.
*/
public class CityDaoImpl extends BaseDao implements CityDao {
@Override
public List<City> getByPid(String pid) {
return null;
}
}
package org.hongxi.whatsmars.earth.dao.impl;
import org.hongxi.whatsmars.earth.dao.OrganizationDao;
import org.hongxi.whatsmars.earth.domain.pojo.Organization;
import org.hongxi.whatsmars.earth.domain.query.OrganizationQuery;
import org.hongxi.whatsmars.earth.domain.query.QueryResult;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created by shenhongxi on 2016/4/6.
*/
public class OrganizationDaoImpl extends BaseDao implements OrganizationDao {
@Override
public QueryResult<Organization> query(OrganizationQuery query) {
QueryResult<Organization> qr = new QueryResult<Organization>();
qr.setQuery(query);
Map<String,Object> params = query.build();
int amount = this.countAll(params);
qr.setAmount(amount);
if(amount == 0) {
qr.setResultList(Collections.EMPTY_LIST);
return qr;
}
List<Organization> organizations = this.sqlSession.selectList("OrganizationMapper.query", params);
qr.setResultList(organizations);
return qr;
}
private int countAll(Map<String,Object> params) {
//return this.sqlSession.selectOne("OrganizationMapper.countAll",params);
return 0;
}
}
package org.hongxi.whatsmars.earth.dao.impl;
import org.hongxi.whatsmars.earth.dao.UserDao;
import org.hongxi.whatsmars.earth.domain.pojo.User;
/**
* Created by javahongxi on 2017/12/24.
*/
public class UserDaoImpl extends BaseDao implements UserDao {
@Override
public void createIfNotExistsTable() {
this.sqlSession.update("User.createIfNotExistsTable");
}
@Override
public User findByUsername(String username) {
return this.sqlSession.selectOne("User.findByUsername", username);
}
@Override
public void insert(User user) {
this.sqlSession.insert("User.insert", user);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="lazyLoadingEnabled" value="false" />
<!--<setting name="logImpl" value="SLF4J"/>-->
</settings>
<typeAliases>
<typeAlias type="org.hongxi.whatsmars.earth.domain.pojo.Organization" alias="Organization"/>
<typeAlias type="org.hongxi.whatsmars.earth.domain.pojo.User" alias="User"/>
</typeAliases>
<mappers>
<mapper resource="sqlmap/Organization-mapper.xml"/>
<mapper resource="sqlmap/User-mapper.xml"/>
</mappers>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="LenderAccountMapper">
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="User">
<update id="createIfNotExistsTable">
CREATE TABLE IF NOT EXISTS user (id BIGINT AUTO_INCREMENT, username VARCHAR(20) NOT NULL, nickname VARCHAR(20), gender TINYINT, age INT, create_date DATETIME, update_date DATETIME, PRIMARY KEY (id));
</update>
<select id="findByUsername" parameterType="string" resultType="User">
select * from user where username = #username#
</select>
<insert id="insert" parameterType="User">
insert into user(username, nickname, gender, age, create_date, update_date)
values(#{username}, #{nickname}, #{gender}, #{age}, NOW(), NOW())
</insert>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>whatsmars-earth</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<artifactId>whatsmars-earth-domain</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>Domain - 领域对象</description>
<dependencies>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.hongxi.whatsmars.earth.domain.constants;
public class Constants {
public static final String HTTP_ENCRYPT_KEY ="yc2JffcREheFQlYFIAY5f9sY7uflgBTo";
public static final int COOKIE_MAX_AGE = 24 * 60 * 60;//7 days
public static final String TEACHER_DEFAULT_PASSWORD = "xuehaodai123_";
public static final String VALIDATE_CODE_COOKIE_KEY = "_validate_code_";
//mongodb中存储admin的操作日志
public static final String MONGO_ADMIN_OPERATION_COLLECTION = "xhd-admin-operation";
//mongodb中存储organization的操作日志
public static final String MONGO_ORGANIZATION_OPERATION_COLLECTION = "xhd-organization-operation";
//mongodb中存储
public static final String MONGO_EMAIL_SEND_ERROR_COLLECTION = "xhd-email-send-error";
//发短信记录表
public static final String MONGO_SMS_SEND_OPERATION_COLLECTION = "xhd-sms-send-operation";
//学生账户操作记录
public static final String MONGO_STUDENT_ACCOUNT_FLOW = "student-account-flow";
//投资人账户操作记录
public static final String MONGO_LENDER_ACCOUNT_FLOW = "lender-account-flow";
//机构账户操作记录
public static final String MONGO_ORGANIZATION_ACCOUNT_FLOW = "organization-account-flow";
//学好贷账户操作记录
public static final String MONGO_ADMIN_ACCOUNT_FLOW = "admin-account-flow";
public static final String PHONE_VALIDATE_CODE_COOKIE_KEY = "_phone_validate_code_";
//发送短信 对学生用【阳光E学】签名 对投资人用【学好贷】签名
public static final String SMS_SEND_URL = "http://117.79.237.29:8061/mdsmssend.ashx";
public static final String SMS_SEND_SN = "SDK-SKY-010-02698";
public static final String SMS_SEND_PASSWORD = "85A1D86BFCA3A598C1F9C357070994EB";
public static final String[] DATE_PATTERN = new String[]{"yyyy-MM-dd"};
public static final String[] DATE_TIME_PATTERN = new String[]{"yyyy-MM-dd HH:mm:ss"};
public static final String DATE_PATTERN_CHINESE = "yyyy年MM月dd日";
public static final String[] FILE_FORMAT = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".jpg", ".jpeg", ".png", ".html", ".htm"};
public static final String[] IMAGE_FORMAT = {".jpg", ".jpeg", ".png"};
//系统中所用的文件或图片(从管理后台上传,/upload/upload.jhtml)
//机构资料-数据查询授权书
public static final String AUTHORIZATION_FILE = "http://stat.xuehaodai.com/ds/5fu9t2l2t3wziqlgctrmjfoedirf7x6k.pdf";
//邮件头部 LOGO
public static final String EMAIL_LOGO = "http://stat.xuehaodai.com/ds/dkh4eeiwz1wqbiszgvrdwmsmsl5gkv9m.png";
//协议文档
public static final String LOAN_PROTOCOL_FILE = "http://stat.xuehaodai.com/ds/2ou1puzlibhlwbgj4wqshq8ulh3hwrmb.pdf";
}
package org.hongxi.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 org.hongxi.whatsmars.earth.domain.enums;
/**
* Created by chenguang on 2015/4/24 0024.
* 收费
*/
public enum FeeEnum {
BELOW_2W(0.5d, "%/每月","借款管理费,两万元以下"),//借款管理费,两万以下
ABOVE_2W(0.24d, "%/每月","借款管理费,两万元以上"),//借款管理费,两万以上
RECHARGE(0.2d, "%/充值金额","充值手续费"),
WITHDRAWALS(2, "元/每笔","提现手续费");
public double code;
public String meaning;
public String name;
public double getCode() {
return code;
}
public String getMeaning() {
return meaning;
}
public String getName() {
return name;
}
FeeEnum(double code, String meaning, String name) {
this.code = code;
this.meaning = meaning;
this.name = name;
}
public static FeeEnum value(double code){
for(FeeEnum e:values()){
if(e.code == code){
return e;
}
}
return null;
}
}
package org.hongxi.whatsmars.earth.domain.enums;
/**
* Created by jenny on 4/22/15.
*/
public enum GenderEnum {
MALE(0, "男"),
FEMALE(1, "女");
public int code;
public String meaning;
public int getCode() {
return code;
}
public String getMeaning() {
return meaning;
}
GenderEnum(int code, String meaning) {
this.code = code;
this.meaning = meaning;
}
public static GenderEnum value(int code){
for(GenderEnum e:values()){
if(e.code==code){
return e;
}
}
return null;
}
}
package org.hongxi.whatsmars.earth.domain.enums;
/**
* Created by shenhongxi on 15/6/29.
* 机构类别
*/
public enum OrganizationLevelEnum {
A(1,"A类"),
B(2,"B类");
public int code;
public String meaning;//意义
public int getCode() {
return code;
}
public String getMeaning() {
return meaning;
}
OrganizationLevelEnum(int code, String meaning) {
this.code = code;
this.meaning = meaning;
}
public static OrganizationLevelEnum value(int code) {
for(OrganizationLevelEnum e : values()) {
if(e.code == code) {
return e;
}
}
return null;
}
}
package org.hongxi.whatsmars.earth.domain.enums;
/**
* Created by liuguanqing on 15/4/7.
*/
public enum OrganizationStatusEnum {
EMAIL_VALIDATING(0,"邮箱验证中"),
MATERIAL_NOT_SUBMITTED(10,"资料尚未提交"),
MATERIAL_AUDITING(20,"资料审核中"),
MATERIAL_AUDITED_SUCCESS(30,"资料审核通过"),
MATERIAL_AUDITED_FAILED(40,"资料审核不通过");
public int code;
public String meaning;
OrganizationStatusEnum(int code,String meaning) {
this.code = code;
this.meaning = meaning;
}
public static OrganizationStatusEnum value(int code) {
for(OrganizationStatusEnum e : values()) {
if(e.code == code) {
return e;
}
}
return null;
}
public int getCode() {
return code;
}
public String getMeaning() {
return meaning;
}
}
package org.hongxi.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 org.hongxi.whatsmars.earth.domain.misc;
import org.hongxi.whatsmars.earth.domain.pojo.User;
/**
* Author: qing
* Date: 14-10-29
* 保存当前登陆用户
*/
public class LoginContext {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
package org.hongxi.whatsmars.earth.domain.misc;
import org.hongxi.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 org.hongxi.whatsmars.earth.domain.misc;
/**
* Author: qing
* Date: 14-10-30
*/
public class SystemConfig {
private String cookieSecurityKey;//加密的key
private String cookieDomain;//域
private String cookieKey;//key
private String hostName;
private String imageHostName;
private Double envRecharge;
public String getCookieKey() {
return cookieKey;
}
public void setCookieKey(String cookieKey) {
this.cookieKey = cookieKey;
}
public String getCookieDomain() {
return cookieDomain;
}
public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
public String getCookieSecurityKey() {
return cookieSecurityKey;
}
public void setCookieSecurityKey(String cookieSecurityKey) {
this.cookieSecurityKey = cookieSecurityKey;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getImageHostName() {
return imageHostName;
}
public void setImageHostName(String imageHostName) {
this.imageHostName = imageHostName;
}
public Double getEnvRecharge() {
return envRecharge;
}
public void setEnvRecharge(Double envRecharge) {
this.envRecharge = envRecharge;
}
}
package org.hongxi.whatsmars.earth.domain.permission;
import org.hongxi.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 org.hongxi.whatsmars.earth.domain.pojo;
import java.io.Serializable;
import java.util.Date;
/**
* Created by javahongxi on 2017/12/24.
*/
public class AccountFlow implements Serializable {
private Integer id;
private Integer studentId;
private String studentName;
private Integer biddingId;
private Integer lenderId;
private String lenderName;
private int stage; //交易期次
private Double amount; //交易金额
private int type; //交易类型
private int status; //资金状态(1收入、0支出)
private String description;
private double balanceAfter;
private Date created;
private Date modified;
private String phone; //交易相关手机号,不参与持久化
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getLenderName() {
return lenderName;
}
public void setLenderName(String lenderName) {
this.lenderName = lenderName;
}
public int getStage() {
return stage;
}
public void setStage(int stage) {
this.stage = stage;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
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 String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public Integer getLenderId() {
return lenderId;
}
public void setLenderId(Integer lenderId) {
this.lenderId = lenderId;
}
public Integer getBiddingId() {
return biddingId;
}
public void setBiddingId(Integer biddingId) {
this.biddingId = biddingId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getBalanceAfter() {
return balanceAfter;
}
public void setBalanceAfter(double balanceAfter) {
this.balanceAfter = balanceAfter;
}
}
package org.hongxi.whatsmars.earth.domain.pojo;
/**
* Created by shenhongxi on 2018/1/16.
*/
public class City {
}
package org.hongxi.whatsmars.earth.domain.pojo;
import java.io.Serializable;
import java.util.Date;
/**
* Created by shenhongxi on 2016/6/8.
*/
public class Organization implements Serializable {
private Integer id;
private String code;
private int level;
private String auditNote;
private String email;//机构登陆邮箱
private String name;//机构名称
private String password;
private int status;//参见OrganizationStatusEnum;
private String bailPercentage; // 保证金比例
private Integer checkType; // 复检类型(频率)
private Date created;
private Date modified;
private Date submitResourceDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
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 String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getAuditNote() {
return auditNote;
}
public void setAuditNote(String auditNote) {
this.auditNote = auditNote;
}
public Date getSubmitResourceDate() {
return submitResourceDate;
}
public void setSubmitResourceDate(Date submitResourceDate) {
this.submitResourceDate = submitResourceDate;
}
public Integer getCheckType() {
return checkType;
}
public void setCheckType(Integer checkType) {
this.checkType = checkType;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public String getBailPercentage() {
return bailPercentage;
}
public void setBailPercentage(String bailPercentage) {
this.bailPercentage = bailPercentage;
}
}
package org.hongxi.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 Long id;
private String username;
private String nickname;
private Integer gender;
private Integer age;
private int type;
private Set<String> operations;//此用户允许的操作
private Date loginTime;
private String phone;
private Date createDate;
private Date updateDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Set<String> getOperations() {
return operations;
}
public void setOperations(Set<String> operations) {
this.operations = operations;
}
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;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
}
package org.hongxi.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 org.hongxi.whatsmars.earth.domain.query;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* 基本查询
*/
public class BaseQuery implements Serializable{
protected Integer pageSize = 5;//每页数据条数
private Integer currentPage = 1;//当前页码
private int startRow = 0; //
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
if(pageSize == null || pageSize <= 0){
return;
}
this.pageSize = pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
if (currentPage == null || currentPage <= 0) {
return;
}
this.currentPage = currentPage;
}
public Integer getStartRow(){
if(pageSize == null || pageSize <0 || currentPage == null || currentPage < 0){
return 0;
}
startRow = (currentPage -1) * pageSize;
return startRow;
}
public Map<String, Object> build() {
Map<String, Object> params = new HashMap<String, Object>(5);
params.put("pageSize", this.getPageSize());
params.put("currentPage", this.getCurrentPage());
params.put("startRow",this.getStartRow());
return params;
}
}
package org.hongxi.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 org.hongxi.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 org.hongxi.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 org.hongxi.whatsmars.earth.domain.util;
import org.hongxi.whatsmars.earth.domain.enums.FeeEnum;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by chenguang on 2015/5/7 0007.
*
*/
public class CalculatorUtils {
private static final Double PERCENT = 100.00d;
/**
* 宽恕期内每月利息
* @param principal
* @return
*/
public static Double gracePeriodInterest(Double principal, double yearRate) {
double interest = principal * yearRate / 1200.00;
return format(interest);
}
/**
* 宽恕期内每月总费(对应新方案:宽恕期内、宽恕期外都有服务费)
* @param principal 本金
* @param yearRate 年利率
* @param graceRate 宽恕期内费率
* @return
*/
public static Double gracePeriod(double principal,double yearRate,double graceRate){
double interest = ArithUtils.round(ArithUtils.div(ArithUtils.mul(principal,yearRate),12*PERCENT),2);
double fee =calculateGraceFee(principal,graceRate);
return ArithUtils.add(interest, fee);
}
/**
* 计算等额本息,最终得出每个月需要偿还(本金:利息)
* @param months
* @param principal
* @param yearInterestRate 年利率,数字,非百分比
* @return 按月份排序,key为本金,value为利息
*/
public static List<Map.Entry<Double,Double>> calculate(int months, Double principal, Double yearInterestRate) {
double monthInterestRate = new BigDecimal(yearInterestRate / 1200).doubleValue();
Double principalAndInterest = format((principal * monthInterestRate * Math.pow((1 + monthInterestRate), months))
/ ( Math.pow((1 + monthInterestRate), months) - 1));//月供
List<Map.Entry<Double,Double>> result = new ArrayList<Map.Entry<Double, Double>>(months * 2);
//等额本息
double leftPrincipal = principal;
Map<Double,Double> _map = new HashMap<Double, Double>(4);
for(int i = 1; i <= months; i++) {
_map.clear();
Double interestOfMonth = format(leftPrincipal * monthInterestRate);//本期偿还利息
Double principalOfMonth = 0d;
//如果是最后一期
if(i == months) {
principalOfMonth = leftPrincipal; //最后一期的本金,为未还本金
interestOfMonth = format(principalAndInterest - principalOfMonth); //最后一期的利息为,月供-最后一期本金
} else {
principalOfMonth = principalAndInterest - interestOfMonth;//本期偿还本金
leftPrincipal -= principalOfMonth;//期末剩余本金
}
_map.put(format(principalOfMonth),interestOfMonth);
result.add(_map.entrySet().iterator().next());
}
return result;
}
/**
* 等额本息期月供,仅包括(本金+利息)
* @param months 等额本息期数
* @param principal 借款总额
* @param yearInterestRate 年利率
* @return
*/
public static double monthPay(int months, Double principal, Double yearInterestRate) {
double monthRate = new BigDecimal(yearInterestRate / 1200).doubleValue();
return format((principal * monthRate * Math.pow((1 + monthRate), months))
/ ( Math.pow((1 + monthRate), months) - 1));
}
/**
* 计算标的总收益
* @param principal 本金
* @param rate 年利率
* @param monthLimit 借款期限
* @param gracePeriod 宽恕期
* @return
*/
public static double calculateInterest(double principal, double rate, int monthLimit, int gracePeriod) {
double totalPeriodInterest = gracePeriodInterest(principal,rate) * gracePeriod;
int months = monthLimit - gracePeriod ;
double totalMonthPay = monthPay(months,principal,rate) * months;
return format(totalMonthPay + totalPeriodInterest - principal);
}
/**
* 学生充值,计算交易总额:输入金额 + 手续费
* @return
*/
public static Double rechargeAndFee(double amount) {
double total = amount + rechargeFee(amount);
return format(total);
}
/**
* 学生充值计算手续费
* @param amount
* @return
*/
public static Double rechargeFee(double amount) {
return format(amount * FeeEnum.RECHARGE.code/100);
}
public static double format(double value){
if (value == Double.valueOf(value).intValue()){
return Double.valueOf(value).intValue();
}else {
BigDecimal bigDecimal = new BigDecimal(Double.toString(value));
return bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
/**
* * 计算宽恕期外月服务费率
* @param gracePeriod 宽恕期
* @param monthLimit 借款期限
* @param graceRate 宽恕期内月服务费率 数字 非百分比
* @param feeRate 月基础服务费率 数字 非百分比
* @return 宽恕期外月服务费率,数字,非百分比
* @throws Exception
*/
public static Double calculateMonthFeeRate(int gracePeriod,int monthLimit,double graceRate,double feeRate)throws Exception{
if(gracePeriod >= monthLimit){
throw new RuntimeException("请求参数错误,宽恕期限小于借款期限");
}
double totalFee = ArithUtils.mul(monthLimit,feeRate);
double graceFee = ArithUtils.mul(gracePeriod,graceRate);
if(graceFee > totalFee){
throw new RuntimeException("请求参数错误,宽恕期费率*宽恕期限 <= 总费率*借款期限");
}
double monthFee = ArithUtils.sub(totalFee, graceFee);
return ArithUtils.div(monthFee, monthLimit - gracePeriod);
}
/**
* 计算宽恕期内月服务费
* @param principal 本金
* @param graceRate 宽恕期内月服务费率
* @return 宽恕期内月服务费
*/
public static Double calculateGraceFee(double principal,double graceRate){
double _graceRate = ArithUtils.div(graceRate, PERCENT);
return ArithUtils.round(ArithUtils.mul(principal, _graceRate), 2);
}
/**
* 计算宽恕期内总服务费
* @param principal 本金
* @param graceRate 宽恕期内月服务费率,非百分比
* @param gracePeriod 宽恕期
* @return 宽恕期内服务费
*/
public static Double calculateGraceTotalFee(double principal,double graceRate,int gracePeriod){
double monthGraceFee = calculateGraceFee(principal, graceRate);
return ArithUtils.mul(monthGraceFee,gracePeriod);
}
/**
* 计算宽恕期外月服务费
* @param principal 本金
* @param gracePeriod 宽恕期
* @param monthLimit 借款期限
* @param graceRate 宽恕期内月服务费率 数字 非百分比
* @param feeRate 月基础服务费率 数字 非百分比
* @return 宽恕期外月服务费
*/
public static Double calculateMonthFee(double principal,int gracePeriod,int monthLimit,double graceRate,double feeRate){
try{
double monthRate = calculateMonthFeeRate(gracePeriod,monthLimit,graceRate,feeRate);
double _monthRate = ArithUtils.div(monthRate,PERCENT);
return ArithUtils.round(ArithUtils.mul(principal,_monthRate),2);
}catch (Exception e ){
throw new RuntimeException("计算宽恕期外月服务费异常");
}
}
/**
* 计算宽恕期外总服务费
* @param principal 本金
* @param graceRate 宽恕期内月服务费率,非百分比
* @param feeRate 月基础服务费率 数字 非百分比
* @param monthLimit 借款期限
* @param gracePeriod 宽恕期限
* @return 宽恕起外服务费
*/
public static Double calculateMonthTotalFee(double principal,double graceRate,double feeRate,int monthLimit,int gracePeriod){
Double totalFee = calculateTotalFee(principal, feeRate, monthLimit);
Double graceFee = calculateGraceTotalFee(principal, graceRate, gracePeriod);
return ArithUtils.sub(totalFee,graceFee);
}
/**
* 计算总服务费
* @param principal 本金
* @param feeRate 月基础服务费率 数字非百分比
* @param monthLimit 借款期限
* @return 总服务费
*/
public static Double calculateTotalFee(double principal,double feeRate,int monthLimit){
double _feeRate = ArithUtils.div(feeRate, PERCENT);
double monthFee = ArithUtils.mul(principal, _feeRate);
return ArithUtils.mul(monthFee,monthLimit);
}
/**
* 计算最后一期服务费(按照减法来做)
* @param principal 本金
* @param feeRate 月基础服务费率 数字非百分比
* @param monthLimit 借款期限
* @param gracePeriod 宽恕期
* @param graceRate 宽恕期内月服务费率 数字非百分比
* @return 宽恕期最后一期服务费
*/
public static Double calculateLastMonthFee(double principal,double feeRate,int monthLimit,int gracePeriod,double graceRate){
double monthTotalFee = calculateMonthTotalFee(principal,graceRate,feeRate,monthLimit,gracePeriod);
double monthFee = calculateMonthFee(principal,gracePeriod,monthLimit,graceRate,feeRate);
double monthLastFee = ArithUtils.sub(monthTotalFee, ArithUtils.mul(monthFee, monthLimit - gracePeriod - 1));
return monthLastFee;
}
/**
* TEST 测试
* @param args
*/
public static void main(String[] args) {
//借款30000,12期,宽恕期3个月,年利率12
double principal = 17800;
int monthLimit = 24;
int gracePeriod = 6;
double feeRate = 0.33;
double graceRate = 0.29; //宽恕期费率
double monthRate = 0.0d; //基本月费率
try{
monthRate = calculateMonthFeeRate(gracePeriod,monthLimit,graceRate,feeRate);
double monthFee = calculateMonthFee(principal,gracePeriod,monthLimit,graceRate,feeRate);
double totalFee = calculateTotalFee(principal,feeRate,monthLimit);
//宽恕期外服务费率
System.out.println("宽恕期外服务费率:" + monthRate);
System.out.println("宽恕期外月服务费:" + monthFee);
System.out.println("总服务费:" + totalFee);
//宽恕期内利息
System.out.println("宽恕期内利息:"+gracePeriodInterest(principal, feeRate));
//宽恕期内服务费
System.out.println("宽恕期内月服务费:"+calculateGraceFee(principal, graceRate));
//最后一个月服务费
System.out.println("最后一个月服务费:" + calculateLastMonthFee(principal,feeRate,monthLimit,gracePeriod,graceRate));
//宽恕期内总服务费
System.out.println("宽恕期内总服务费:"+calculateGraceTotalFee(principal,graceRate,gracePeriod));
//宽恕期外总服务费
System.out.println("宽恕期外总服务费:"+calculateMonthTotalFee(principal,graceRate,feeRate,monthLimit,gracePeriod));
}catch (Exception e){
System.out.println(e.getMessage());
}
/*
//宽恕期利息
double interest = gracePeriodInterest(principal,rate);
//宽恕期管理费
double fee = gracePeriodFee(principal,monthLimit,gracePeriod);
//宽恕期每月总费用
double periodAmount = gracePeriod(principal,monthLimit,gracePeriod,rate);
//等额本息月供
double monthPay = monthPay(monthLimit - gracePeriod,principal,rate);
//标的投资人总收益
double totalInterest = calculateInterest(principal,rate,monthLimit,gracePeriod);
System.out.println("宽恕期每月利息:"+interest);
System.out.println("宽恕期每月管理费:"+fee);
System.out.println("宽恕期每月总费用:"+periodAmount);
System.out.println("等额本息月供:"+monthPay);
System.out.println("标的投资人总收益"+totalInterest);
System.out.println("学好贷总服务费:"+format(fee * gracePeriod));
List<Map.Entry<Double,Double>> list = calculate(monthLimit,principal,rate);
int i = 0;
for(Map.Entry<Double, Double> map: list){
System.out.println("--------------"+(++i)+"----------------");
System.out.println(map.getKey() + " " + map.getValue());
}
*/
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>whatsmars-earth</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<artifactId>whatsmars-earth-manager</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>Manager - DAO组合或调用第三方接口</description>
<dependencies>
<dependency>
<groupId>org.hongxi</groupId>
<artifactId>whatsmars-earth-dao</artifactId>
<version>Rocket.S2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.hongxi.whatsmars.earth.manager;
import org.hongxi.whatsmars.earth.domain.pojo.City;
import java.util.List;
/**
* Created by shenhongxi on 2018/11/28.
*/
public interface CityManager {
List<City> getByPid(String pid);
}
package org.hongxi.whatsmars.earth.manager.impl;
import org.hongxi.whatsmars.earth.domain.pojo.City;
import org.hongxi.whatsmars.earth.manager.CityManager;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Created by shenhongxi on 2018/11/28.
* Manager层:通用业务处理层,它有如下特征:
* 1) 对第三方平台封装的层,预处理返回结果及转化异常信息;
* 2) 对Service层通用能力的下沉,如缓存方案、中间件通用处理;
* 3) 与DAO层交互,对多个DAO的组合复用。
*/
@Component
public class CityManagerImpl implements CityManager {
@Override
public List<City> getByPid(String pid) {
// 加载进guava缓存
return null;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>whatsmars-earth</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<artifactId>whatsmars-earth-service</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>Service - 业务层,可调DAO/Manager</description>
<dependencies>
<dependency>
<groupId>org.hongxi</groupId>
<artifactId>whatsmars-earth-common</artifactId>
<version>Rocket.S2</version>
</dependency>
<dependency>
<groupId>org.hongxi</groupId>
<artifactId>whatsmars-earth-dao</artifactId>
<version>Rocket.S2</version>
</dependency>
<dependency>
<groupId>org.hongxi</groupId>
<artifactId>whatsmars-earth-manager</artifactId>
<version>Rocket.S2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package org.hongxi.whatsmars.earth.service;
import org.hongxi.whatsmars.earth.common.pojo.Result;
/**
* Created by shenhongxi on 2016/4/1.
*/
public interface AccountService {
Result hello(String name);
}
package org.hongxi.whatsmars.earth.service;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.hongxi.whatsmars.earth.dao.CityDao;
import org.hongxi.whatsmars.earth.domain.pojo.City;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
/**
* Created by shenhongxi on 2018/1/16.
*/
public class CityService {
private CityDao cityDao;
private static Cache<String,List<City>> cache = CacheBuilder.newBuilder().maximumSize(2048).expireAfterAccess(15, TimeUnit.MINUTES).build();
public void setCityDao(CityDao cityDao) {
this.cityDao = cityDao;
}
public List<City> getByPid(final String pid) {
try {
//cache.get方法首先从Cache中查询key是否存在,如果存在则返回对应的value。
//如果不存在,则调用Callable.call方法。并把call方法返回的结果保存在cache中。
return cache.get(pid, new Callable<List<City>>() {
@Override
public List<City> call() throws Exception {
return load(pid);
}
});
}catch (Exception e) {
//如果数据库不存在此值,将会返回一个空的集合
return Collections.EMPTY_LIST;
}
}
/**
* 如果后台DAO返回结果为null,需要抛出异常。因为guava cache中不能存储null值。
*
* Callable的返回值将会被保存在cache中,然后返回给调用方法。
* 如果抛出异常,异常将会通过cache.get方法抛出。
* @param pid
* @return
* @throws Exception
*/
protected List<City> load(final String pid) throws Exception{
List<City> result = this.cityDao.getByPid(pid);
if(result == null) {
throw new NullPointerException("pid not existed");
}
return result;
}
}
package org.hongxi.whatsmars.earth.service;
import org.hongxi.whatsmars.earth.common.pojo.Result;
import org.hongxi.whatsmars.earth.domain.query.OrganizationQuery;
/**
* Created by shenhongxi on 15/4/13.
*/
public interface OrganizationService {
Result list(OrganizationQuery query);
}
package org.hongxi.whatsmars.earth.service;
import org.hongxi.whatsmars.earth.domain.pojo.User;
/**
* Created by javahongxi on 2017/12/24.
*/
public interface UserService {
User findByUsername(String username);
void add(User user);
}
package org.hongxi.whatsmars.earth.service.impl;
import org.hongxi.whatsmars.earth.common.pojo.Result;
import org.hongxi.whatsmars.earth.dao.AccountDao;
import org.hongxi.whatsmars.earth.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
/**
* 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) {
// try {
// // ...
// return true;
// } catch (Exception e) {
// transactionStatus.setRollbackOnly();
// }
// return false;
// }
// });
return result;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
}
package org.hongxi.whatsmars.earth.service.impl;
import org.hongxi.whatsmars.earth.common.pojo.Result;
import org.hongxi.whatsmars.earth.common.pojo.ResultCode;
import org.hongxi.whatsmars.earth.dao.OrganizationDao;
import org.hongxi.whatsmars.earth.service.OrganizationService;
import org.hongxi.whatsmars.earth.domain.pojo.Organization;
import org.hongxi.whatsmars.earth.domain.query.OrganizationQuery;
import org.hongxi.whatsmars.earth.domain.query.QueryResult;
import org.springframework.stereotype.Service;
import java.util.Collection;
/**
* Created by shenhongxi on 2016/4/6.
*/
@Service("organizationService")
public class OrganizationServiceImpl implements OrganizationService {
private OrganizationDao organizationDao;
public void setOrganizationDao(OrganizationDao organizationDao) {
this.organizationDao = organizationDao;
}
@Override
public Result list(OrganizationQuery query) {
Result result = new Result();
try {
QueryResult<Organization> qr = this.organizationDao.query(query);
Collection<Organization> organizations = qr.getResultList();
result.addModel("query", query);
result.addModel("queryResult", qr);
result.addModel("organizations", organizations);
} catch (Exception e) {
//logger.error("organization query error,", e);
result.setResultCode(ResultCode.SYSTEM_ERROR);
}
return result;
}
}
package org.hongxi.whatsmars.earth.service.impl;
import org.hongxi.whatsmars.earth.dao.UserDao;
import org.hongxi.whatsmars.earth.domain.pojo.User;
import org.hongxi.whatsmars.earth.service.UserService;
import org.springframework.stereotype.Service;
/**
* Created by javahongxi on 2017/12/24.
*/
@Service("userService")
public class UserServiceImpl implements UserService {
private UserDao userDao;
@Override
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
@Override
public void add(User user) {
userDao.createIfNotExistsTable(); // test
userDao.insert(user);
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
earth-web的辅助工程,提供任务调度、消息等功能
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>whatsmars-earth</artifactId>
<groupId>org.hongxi</groupId>
<version>Rocket.S2</version>
</parent>
<artifactId>whatsmars-earth-support-web</artifactId>
<packaging>war</packaging>
<name>${project.artifactId}</name>
<description>Another Controller Module</description>
<dependencies>
<dependency>
<groupId>org.hongxi</groupId>
<artifactId>whatsmars-earth-service</artifactId>
<version>Rocket.S2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
</dependency>
</dependencies>
<build>
<outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<filters>
<filter>profile/development.properties</filter>
</filters>
</build>
</profile>
<profile>
<id>test</id>
<build>
<filters>
<filter>profile/test.properties</filter>
</filters>
</build>
</profile>
<profile>
<id>production</id>
<build>
<filters>
<filter>profile/production.properties</filter>
</filters>
</build>
</profile>
</profiles>
</project>
\ No newline at end of file
whatsmars.log4j.logger.path=/data/logs
whatsmars.log4j.logger.level=debug
whatsmars.jdbc.mysql.url=jdbc:mysql://db.hongxi.org:3306/test
whatsmars.jdbc.mysql.username=root
whatsmars.jdbc.mysql.password=n36bxXMnHina
whatsmars.admin.cookie.security.key=H32ClbJteGTjbZSL
whatsmars.admin.cookie.key=_admin_
whatsmars.admin.cookie.domain=127.0.0.1
whatsmars.admin.host.name=127.0.0.1:8080
whatsmars.quartz.cluster.mysql.url=jdbc:mysql://0.0.0.0:3306/quartz
whatsmars.quartz.cluster.mysql.username=root
whatsmars.quartz.cluster.mysql.password=xxxxxxx
whatsmars.activemq.broker.url=tcp://0.0.0.0:61616
whatsmars.activemq.queue.withdraw=_whatsmars_MQ_WITHDRAW.QUEUE
##authenticationDatabase
whatsmars.mongodb.admin.dbname=admin
##gridfs
whatsmars.mongodb.filesystem.dbname=whatsmars-fs
whatsmars.mongodb.filesystem.username=toutiao
whatsmars.mongodb.filesystem.password=toutiao.im
whatsmars.mongodb.filesystem.addresses=0.0.0.0:27017
##common
whatsmars.mongodb.common.dbname=whatsmars-common
whatsmars.mongodb.common.username=toutiao
whatsmars.mongodb.common.password=toutiao.im
whatsmars.mongodb.common.addresses=0.0.0.0:27017
whatsmars.service.email.host.name=smtp.qq.com
whatsmars.service.email.smtp.port=25
whatsmars.service.email.username=toutiao
whatsmars.service.email.password=toutiao
whatsmars.service.email.from.address=service@toutiao.im
\ No newline at end of file
whatsmars.log4j.logger.path=/data/logs
whatsmars.log4j.logger.level=debug
whatsmars.jdbc.mysql.url=jdbc:mysql://db.hongxi.org:3306/test
whatsmars.jdbc.mysql.username=root
whatsmars.jdbc.mysql.password=n36bxXMnHina
whatsmars.admin.cookie.security.key=H32ClbJteGTjbZSL
whatsmars.admin.cookie.key=_admin_
whatsmars.admin.cookie.domain=127.0.0.1
whatsmars.admin.host.name=127.0.0.1:8080
whatsmars.quartz.cluster.mysql.url=jdbc:mysql://0.0.0.0:3306/quartz
whatsmars.quartz.cluster.mysql.username=root
whatsmars.quartz.cluster.mysql.password=xxxxxxx
whatsmars.activemq.broker.url=tcp://0.0.0.0:61616
whatsmars.activemq.queue.withdraw=_whatsmars_MQ_WITHDRAW.QUEUE
##authenticationDatabase
whatsmars.mongodb.admin.dbname=admin
##gridfs
whatsmars.mongodb.filesystem.dbname=whatsmars-fs
whatsmars.mongodb.filesystem.username=toutiao
whatsmars.mongodb.filesystem.password=toutiao.im
whatsmars.mongodb.filesystem.addresses=0.0.0.0:27017
##common
whatsmars.mongodb.common.dbname=whatsmars-common
whatsmars.mongodb.common.username=toutiao
whatsmars.mongodb.common.password=toutiao.im
whatsmars.mongodb.common.addresses=0.0.0.0:27017
whatsmars.service.email.host.name=smtp.qq.com
whatsmars.service.email.smtp.port=25
whatsmars.service.email.username=toutiao
whatsmars.service.email.password=toutiao
whatsmars.service.email.from.address=service@toutiao.im
\ No newline at end of file
whatsmars.log4j.logger.path=/data/logs
whatsmars.log4j.logger.level=debug
whatsmars.jdbc.mysql.url=jdbc:mysql://db.hongxi.org:3306/test
whatsmars.jdbc.mysql.username=root
whatsmars.jdbc.mysql.password=n36bxXMnHina
whatsmars.admin.cookie.security.key=H32ClbJteGTjbZSL
whatsmars.admin.cookie.key=_admin_
whatsmars.admin.cookie.domain=127.0.0.1
whatsmars.admin.host.name=127.0.0.1:8080
whatsmars.quartz.cluster.mysql.url=jdbc:mysql://0.0.0.0:3306/quartz
whatsmars.quartz.cluster.mysql.username=root
whatsmars.quartz.cluster.mysql.password=xxxxxxx
whatsmars.activemq.broker.url=tcp://0.0.0.0:61616
whatsmars.activemq.queue.withdraw=_whatsmars_MQ_WITHDRAW.QUEUE
##authenticationDatabase
whatsmars.mongodb.admin.dbname=admin
##gridfs
whatsmars.mongodb.filesystem.dbname=whatsmars-fs
whatsmars.mongodb.filesystem.username=toutiao
whatsmars.mongodb.filesystem.password=toutiao.im
whatsmars.mongodb.filesystem.addresses=0.0.0.0:27017
##common
whatsmars.mongodb.common.dbname=whatsmars-common
whatsmars.mongodb.common.username=toutiao
whatsmars.mongodb.common.password=toutiao.im
whatsmars.mongodb.common.addresses=0.0.0.0:27017
whatsmars.service.email.host.name=smtp.qq.com
whatsmars.service.email.smtp.port=25
whatsmars.service.email.username=toutiao
whatsmars.service.email.password=toutiao
whatsmars.service.email.from.address=service@toutiao.im
\ No newline at end of file
package org.hongxi.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 org.hongxi.whatsmars.earth.support.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by shenhongxi on 15/4/13.
*/
@Controller
public class IndexController {
@RequestMapping("/error")
public ModelAndView error(@RequestParam(value = "messages",required = false)String messages) {
ModelAndView mav = new ModelAndView();
mav.addObject("messages",messages);
return mav;
}
@RequestMapping("/index")
public ModelAndView index() {
return new ModelAndView();
}
}
##max size of the pool
dbcp.maxActive=64
##max size of the idle resources
dbcp.maxIdle=6
dbcp.minIdle=1
dbcp.defaultAutoCommit=true
##if no resources in the pool,How long the caller would wait
##if server is heavy loading,it should be little
## 15 seconds
dbcp.maxWait=15000
##default true,check the connection or not when resource removed from pool
##dbcp.testOnBorrow=true
##default false,check the connection or not when resource returned to pool
##dbcp.testOnReturn=false
##another thread is running for checking idle threads
##period of the checking."-1" is meaning no thread running for it.
## 5 minutes
dbcp.timeBetweenEvictionRunsMillis=300000
##The number of objects to examine during each run of the idle object evictor thread
#dbcp.numTestsPerEvictionRun= 3
##The minimum amount of time an object may sit idle in the pool before
## it is eligable for eviction by the idle object evictor
## 10 minutes
dbcp.minEvictableIdleTimeMillis=600000
##The indication of whether objects will be validated by the idle object
## evictor (if any). If an object fails to validate, it will be dropped
## from the pool.
##dbcp.testWhileIdle=false
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册