Commit 05beecd0 authored by Huang's avatar Huang
Browse files

no commit message

parent bc5dd330
/**
* * Copyright &copy; 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package com.jeespring.common.json;
import java.util.LinkedHashMap;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jeespring.common.mapper.JsonMapper;
/**
* $.ajax后需要接受的JSON
*
* @author
*
*/
public class AjaxJson {
private boolean success = true;// 是否成功
private String errorCode = "-1";//错误代码
private String msg = "操作成功";// 提示信息
private LinkedHashMap<String, Object> body = new LinkedHashMap();//封装json的map
public LinkedHashMap<String, Object> getBody() {
return body;
}
public void setBody(LinkedHashMap<String, Object> body) {
this.body = body;
}
public void put(String key, Object value){//向json中添加属性,在js中访问,请调用data.map.key
body.put(key, value);
}
public void remove(String key){
body.remove(key);
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {//向json中添加属性,在js中访问,请调用data.msg
this.msg = msg;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@JsonIgnore//返回对象时忽略此属性
public String getJsonStr() {//返回json字符串数组,将访问msg和key的方式统一化,都使用data.key的方式直接访问。
String json = JsonMapper.getInstance().toJson(this);
return json;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorCode() {
return errorCode;
}
}
/**
* * Copyright &copy; 2015-2020 <a href="https://gitee.com/JeeHuangBingGui/JeeSpring">JeeSpring</a> All rights reserved..
*/
package com.jeespring.common.json;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
public class PrintJSON {
public static void write(HttpServletResponse response,String content) {
response.reset();
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-store");
response.setCharacterEncoding("UTF-8");
try {
PrintWriter pw=response.getWriter();
pw.write(content);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package com.jeespring.common.mail;
/**
*
*/
import javax.mail.*;
public class MailAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MailAuthenticator(){
}
public MailAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
@Override
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
package com.jeespring.common.mail;
/**
*发送邮件需要使用的基本信息
*
*/
import java.util.Properties;
public class MailBody {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private String toAddress;
// 登陆邮件发送服务器的用户名和密码
private String userName;
private String password;
// 是否需要身份验证
private boolean validate = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名
private String[] attachFileNames;
/**
* 获得邮件会话属性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}
package com.jeespring.common.mail;
/**
* 简单邮件(不带附件的邮件)发送器
*/
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailSendUtils {
/**
* 以文本格式发送邮件
* @param mailInfo 待发送的邮件的信息
*/
public boolean sendTextMail(MailBody mailInfo) throws Exception{
// 判断是否需要身份认证
MailAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
// logBefore(logger, "构造一个发送邮件的session");
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 发送邮件
Transport.send(mailMessage);
System.out.println("发送成功!");
return true;
}
/**
* 以HTML格式发送邮件
* @param mailInfo 待发送的邮件信息
*/
public boolean sendHtmlMail(MailBody mailInfo) throws Exception{
// 判断是否需要身份认证
MailAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份认证,则创建一个密码验证器
if (mailInfo.isValidate()) {
authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
return true;
}
/**
* @param SMTP
* 邮件服务器
* @param PORT
* 端口
* @param EMAIL
* 本邮箱账号
* @param PAW
* 本邮箱密码
* @param toEMAIL
* 对方箱账号
* @param TITLE
* 标题
* @param CONTENT
* 内容
* @param TYPE
* 1:文本格式;2:HTML格式
*/
public static boolean sendEmail(String SMTP, String PORT, String EMAIL,
String PAW, String toEMAIL, String TITLE, String CONTENT,
String TYPE) {
// 这个类主要是设置邮件
MailBody mailInfo = new MailBody();
mailInfo.setMailServerHost(SMTP);
mailInfo.setMailServerPort(PORT);
mailInfo.setValidate(true);
mailInfo.setUserName(EMAIL);
mailInfo.setPassword(PAW);
mailInfo.setFromAddress(EMAIL);
mailInfo.setToAddress(toEMAIL);
mailInfo.setSubject(TITLE);
mailInfo.setContent(CONTENT);
// 这个类主要来发送邮件
MailSendUtils sms = new MailSendUtils();
try {
if ("1".equals(TYPE)) {
return sms.sendTextMail(mailInfo);
} else {
return sms.sendHtmlMail(mailInfo);
}
} catch (Exception e) {
return false;
}
}
}
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.jeespring.common.mapper;
import java.util.Collection;
import java.util.List;
import org.dozer.DozerBeanMapper;
import com.google.common.collect.Lists;
/**
* 简单封装Dozer, 实现深度转换Bean<->Bean的Mapper.实现:
*
* 1. 持有Mapper的单例.
* 2. 返回值类型转换.
* 3. 批量转换Collection中的所有对象.
* 4. 区分创建新的B对象与将对象A值复制到已存在的B对象两种函数.
*
* @author calvin
* @version 2013-01-15
*/
public class BeanMapper {
/**
* 持有Dozer单例, 避免重复创建DozerMapper消耗资源.
*/
private static DozerBeanMapper dozer = new DozerBeanMapper();
/**
* 基于Dozer转换对象的类型.
*/
public static <T> T map(Object source, Class<T> destinationClass) {
return dozer.map(source, destinationClass);
}
/**
* 基于Dozer转换Collection中对象的类型.
*/
@SuppressWarnings("rawtypes")
public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
List<T> destinationList = Lists.newArrayList();
for (Object sourceObject : sourceList) {
T destinationObject = dozer.map(sourceObject, destinationClass);
destinationList.add(destinationObject);
}
return destinationList;
}
/**
* 基于Dozer将对象A的值拷贝到对象B中.
*/
public static void copy(Object source, Object destinationObject) {
dozer.map(source, destinationObject);
}
}
\ No newline at end of file
/**
* Copyright (c) 2005-2012 springside.org.cn
*/
package com.jeespring.common.mapper;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.util.Assert;
import com.jeespring.common.utils.Exceptions;
import com.jeespring.common.utils.Reflections;
import com.jeespring.common.utils.StringUtils;
/**
* 使用Jaxb2.0实现XML<->Java Object的Mapper.
*
* 在创建时需要设定所有需要序列化的Root对象的Class.
* 特别支持Root对象是Collection的情形.
*
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings("rawtypes")
public class JaxbMapper {
private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();
/**
* Java Object->Xml without encoding.
*/
public static String toXml(Object root) {
Class clazz = Reflections.getUserClass(root);
return toXml(root, clazz, null);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, String encoding) {
Class clazz = Reflections.getUserClass(root);
return toXml(root, clazz, encoding);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, Class clazz, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz) {
return toXml(root, rootName, clazz, null);
}
/**
* Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
try {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection = root;
JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* Xml->Java Object.
*/
@SuppressWarnings("unchecked")
public static <T> T fromXml(String xml, Class<T> clazz) {
try {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller(clazz).unmarshal(reader);
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 创建Marshaller并设定encoding(可为null).
* 线程不安全,需要每次创建或pooling。
*/
public static Marshaller createMarshaller(Class clazz, String encoding) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
/**
* 创建UnMarshaller.
* 线程不安全,需要每次创建或pooling。
*/
public static Unmarshaller createUnmarshaller(Class clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw Exceptions.unchecked(e);
}
}
protected static JAXBContext getJaxbContext(Class clazz) {
Assert.notNull(clazz, "'clazz' must not be null");
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
} catch (JAXBException ex) {
throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
+ "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
/**
* 封装Root Element 是 Collection的情况.
*/
public static class CollectionWrapper {
@XmlAnyElement
protected Collection<?> collection;
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.mapper;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
/**
* 简单封装Jackson,实现JSON String<->Java Object的Mapper.
* 封装不同的输出风格, 使用不同的builder函数创建实例.
* @author 黄炳桂 516821420@qq.com
* @version 2013-11-15
*/
public class JsonMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private static JsonMapper mapper;
public JsonMapper() {
this(Include.NON_EMPTY);
}
public JsonMapper(Include include) {
// 设置输出时包含属性的风格
if (include != null) {
this.setSerializationInclusion(include);
}
// 允许单引号、允许不带引号的字段名称
this.enableSimple();
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 空值处理为空串
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){
@Override
public void serialize(Object value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeString("");
}
});
// 进行HTML解码。
this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>(){
@Override
public void serialize(String value, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
}
}));
// 设置时区
this.setTimeZone(TimeZone.getDefault());//getTimeZone("GMT+8:00")
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public static JsonMapper getInstance() {
if (mapper == null){
mapper = new JsonMapper().enableSimple();
}
return mapper;
}
/**
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
*/
public static JsonMapper nonDefaultMapper() {
if (mapper == null){
mapper = new JsonMapper(Include.NON_DEFAULT);
}
return mapper;
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return this.writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/**
* 反序列化POJO或简单Collection如List<String>.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
* @see #fromJson(String, JavaType)
*/
public <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return this.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
* @see #createCollectionType(Class, Class...)
*/
@SuppressWarnings("unchecked")
public <T> T fromJson(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) this.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 構造泛型的Collection Type如:
* ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class)
* HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
*/
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/**
* 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
*/
@SuppressWarnings("unchecked")
public <T> T update(String jsonString, T object) {
try {
return (T) this.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
return null;
}
/**
* 輸出JSONP格式數據.
*/
public String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
/**
* 設定是否使用Enum的toString函數來讀寫Enum,
* 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
* 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
*/
public JsonMapper enableEnumUseToString() {
this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
return this;
}
/**
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
*/
public JsonMapper enableJaxbAnnotation() {
JaxbAnnotationModule module = new JaxbAnnotationModule();
this.registerModule(module);
return this;
}
/**
* 允许单引号
* 允许不带引号的字段名称
*/
public JsonMapper enableSimple() {
this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
return this;
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public ObjectMapper getMapper() {
return this;
}
/**
* 对象转换为JSON字符串
* @param object
* @return
*/
public static String toJsonString(Object object){
return JsonMapper.getInstance().toJson(object);
}
/**
* JSON字符串转换为对象
* @param jsonString
* @param clazz
* @return
*/
public static Object fromJsonString(String jsonString, Class<?> clazz){
return JsonMapper.getInstance().fromJson(jsonString, clazz);
}
/**
* 测试
*/
// public static void main(String[] args) {
// List<Map<String, Object>> list = Lists.newArrayList();
// Map<String, Object> map = Maps.newHashMap();
// map.put("id", 1);
// map.put("pId", -1);
// map.put("name", "根节点");
// list.add(map);
// map = Maps.newHashMap();
// map.put("id", 2);
// map.put("pId", 1);
// map.put("name", "你好");
// map.put("open", true);
// list.add(map);
// String json = JsonMapper.getInstance().toJson(list);
// System.out.println(json);
// }
}
package com.jeespring.common.mapper.adapters;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MapAdapter extends XmlAdapter<MapConvertor, Map<String, Object>> {
@Override
public MapConvertor marshal(Map<String, Object> map) throws Exception {
MapConvertor convertor = new MapConvertor();
for (Map.Entry<String, Object> entry : map.entrySet()) {
MapConvertor.MapEntry e = new MapConvertor.MapEntry(entry);
convertor.addEntry(e);
}
return convertor;
}
@Override
public Map<String, Object> unmarshal(MapConvertor map) throws Exception {
Map<String, Object> result = new HashMap<String, Object>();
for (MapConvertor.MapEntry e : map.getEntries()) {
result.put(e.getKey(), e.getValue());
}
return result;
}
}
package com.jeespring.common.mapper.adapters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
@XmlType(name = "MapConvertor")
@XmlAccessorType(XmlAccessType.FIELD)
public class MapConvertor {
private List<MapEntry> entries = new ArrayList<MapEntry>();
public void addEntry(MapEntry entry) {
entries.add(entry);
}
public List<MapEntry> getEntries() {
return entries;
}
public static class MapEntry {
private String key;
private Object value;
public MapEntry() {
super();
}
public MapEntry(Map.Entry<String, Object> entry) {
super();
this.key = entry.getKey();
this.value = entry.getValue();
}
public MapEntry(String key, Object value) {
super();
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import java.util.Date;
import java.util.HashMap;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.jeespring.common.utils.IdGen;
import com.jeespring.modules.sys.entity.User;
import com.jeespring.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* 数据Entity类
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
public abstract class AbstractBaseEntity<T> extends AbstractEntity<T> {
private static final long serialVersionUID = 1L;
protected String remarks; // 备注
protected User createBy; // 创建者
protected Date createDate; // 创建日期
protected User updateBy; // 更新者
protected Date updateDate; // 更新日期
protected String delFlag; // 删除标记(0:正常;1:删除;2:审核)
protected HashMap<String,Object> extendMap;//HashMap对象的拓展属性
protected JSONObject jsonObject;//JSONObject对象的拓展属性
protected Integer totalCount;
protected String totalDate;
protected String totalType;
public void setExtendMap(String item,Object object) {
if(extendMap==null) {
extendMap = new HashMap<String, Object>();
}
extendMap.put(item,object);
}
public HashMap<String,Object> getExtendMap() {
return extendMap;
}
public JSONObject setExtendObject(String item,Object object){
if(jsonObject==null) {
jsonObject = JSON.parseObject(JSON.toJSONString(this));
}
jsonObject.put(item,object);
return jsonObject;
}
public AbstractBaseEntity() {
super();
this.delFlag = DEL_FLAG_NORMAL;
}
public AbstractBaseEntity(String id) {
super(id);
}
/**
* 插入之前执行方法,需要手动调用
*/
@Override
public void preInsert(){
// 不限制ID为UUID,调用setIsNewRecord()使用自定义ID
if (!this.isNewRecord){
setId(IdGen.uuid());
}
User user = UserUtils.getUser();
if (StringUtils.isNotBlank(user.getId())){
this.updateBy = user;
this.createBy = user;
}
this.updateDate = new Date();
this.createDate = this.updateDate;
}
/**
* 更新之前执行方法,需要手动调用
*/
@Override
public void preUpdate(){
User user = UserUtils.getUser();
if (StringUtils.isNotBlank(user.getId())){
this.updateBy = user;
}
this.updateDate = new Date();
}
@Length(min=0, max=255)
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
@JsonIgnore
@JSONField(serialize=false)
public User getCreateBy() {
return createBy;
}
public void setCreateBy(User createBy) {
this.createBy = createBy;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@JsonIgnore
@JSONField(serialize=false)
public User getUpdateBy() {
return updateBy;
}
public void setUpdateBy(User updateBy) {
this.updateBy = updateBy;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
public Date getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Date updateDate) {
this.updateDate = updateDate;
}
@JsonIgnore
@JSONField(serialize=false)
@Length(min=1, max=1)
public String getDelFlag() {
if(delFlag==null) {
delFlag = "0";
}
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public String getTotalDate() {
return totalDate;
}
public void setTotalDate(String totalDate) {
this.totalDate = totalDate;
}
public String getTotalType() {
return totalType;
}
public void setTotalType(String totalType) {
this.totalType = totalType;
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import com.jeespring.common.config.Global;
import com.jeespring.common.utils.StringUtils;
import com.jeespring.modules.sys.entity.User;
import com.jeespring.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import javax.xml.bind.annotation.XmlTransient;
import java.io.Serializable;
import java.util.Map;
/**
* Entity支持类
*
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
//@SupTreeList
public abstract class AbstractEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 实体编号(唯一标识)
*/
protected String id;
/**
* 当前用户
*/
protected User currentUser;
/**
* 当前实体分页对象
*/
protected Page<T> page;
private String orderBy = ""; // 标准查询有效, 实例: updatedate desc, name asc
private String groupBy = ""; // 标准查询有效, 实例: updatedate desc, name asc
private String where = ""; // 标准查询条件
protected int pageNo = 1; // 当前页码
protected int pageSize = Integer.valueOf(Global.getConfig("page.pageSize")); // 页面大小,设置为“-1”表示不进行分页(分页无效)
/**
* 自定义SQL(SQL标识,SQL内容)
*/
protected Map<String, String> sqlMap;
/**
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
*/
protected boolean isNewRecord = false;
public AbstractEntity() {
}
public AbstractEntity(String id) {
this();
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@JsonIgnore
@XmlTransient
@JSONField(serialize=false)
public User getCurrentUser() {
if (currentUser == null) {
currentUser = UserUtils.getUser();
}
return currentUser;
}
public void setCurrentUser(User currentUser) {
this.currentUser = currentUser;
}
@JsonIgnore
@XmlTransient
@JSONField(serialize=false)
public Page<T> getPage() {
if (page == null) {
page = new Page<T>();
}
return page;
}
public Page<T> setPage(Page<T> page) {
this.page = page;
return page;
}
@JsonIgnore
@XmlTransient
@JSONField(serialize=false)
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
this.orderBy = orderBy;
}
public String getGroupBy() {
return groupBy;
}
public void setGroupBy(String groupBy) {
this.groupBy = groupBy;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@JsonIgnore
@XmlTransient
@JSONField(serialize=false)
public Map<String, String> getSqlMap() {
if (sqlMap == null) {
sqlMap = Maps.newHashMap();
}
return sqlMap;
}
public void setSqlMap(Map<String, String> sqlMap) {
this.sqlMap = sqlMap;
}
/**
* 插入之前执行方法,子类实现
*/
public abstract void preInsert();
/**
* 更新之前执行方法,子类实现
*/
public abstract void preUpdate();
/**
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
*
* @return
*/
public boolean getIsNewRecord() {
return isNewRecord || StringUtils.isBlank(getId());
}
/**
* 是否是新记录(默认:false),调用setIsNewRecord()设置新记录,使用自定义ID。
* 设置为true后强制执行插入语句,ID不会自动生成,需从手动传入。
*/
public void setIsNewRecord(boolean isNewRecord) {
this.isNewRecord = isNewRecord;
}
/**
* 全局变量对象
*/
@JsonIgnore
@JSONField(serialize=false)
public Global getGlobal() {
return new Global();
}
/**
* 获取数据库名称,该方法至关重要,在所有的mapper里面都是用
*/
@JsonIgnore
@JSONField(serialize=false)
public String getDbName() {
return Global.getJdbcType();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
if (!getClass().equals(obj.getClass())) {
return false;
}
AbstractEntity<?> that = (AbstractEntity<?>) obj;
return null == this.getId() ? false : this.getId().equals(that.getId());
}
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
/**
* 删除标记(0:正常;1:删除;2:审核;)
*/
public static final String DEL_FLAG_NORMAL = "0";
public static final String DEL_FLAG_DELETE = "1";
public static final String DEL_FLAG_AUDIT = "2";
}
/**
* Copyright &copy; 2012-2016 <a href="https://gitee.com/JeeHuangBingGui/jeeSpringCloud">JeeSpring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jeespring.modules.act.entity.Act;
/**
* Activiti Entity类
* @author JeeSpring
* @version 2013-05-28
*/
public abstract class ActEntity<T> extends AbstractBaseEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
protected Act act; // 流程任务对象
public ActEntity() {
super();
}
public ActEntity(String id) {
super(id);
}
@JsonIgnore
public Act getAct() {
if (act == null){
act = new Act();
}
return act;
}
public void setAct(Act act) {
this.act = act;
}
/**
* 获取流程实例ID
* @return
*/
public String getProcInsId() {
return this.getAct().getProcInsId();
}
/**
* 设置流程实例ID
* @param procInsId
*/
public void setProcInsId(String procInsId) {
this.getAct().setProcInsId(procInsId);
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import java.util.List;
import org.apache.ibatis.annotations.Param;
/**
* DAO支持类实现
*
* @param <T>
* * * * @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
public interface InterfaceBaseDao<T> extends InterfaceDao {
/**
* 获取单条数据
*
* @param id
* @return
*/
T get(String id);
/**
* 获取单条数据
*
* @param entity
* @return
*/
T get(T entity);
/**
* 根据实体名称和字段名称和字段值获取唯一记录
*
* @param <T>
* @param entityClass
* @param propertyName
* @param value
* @return
*/
T findUniqueByProperty(@Param(value = "propertyName") String propertyName, @Param(value = "value") Object value);
/**
* 查询统计列表,如果需要分页,请设置分页对象,如:entity.setPage(new Page<T>());
*
* @param entity
* @return
*/
List<T> total(T entity);
/**
* 查询数据列表,如果需要分页,请设置分页对象,如:entity.setPage(new Page<T>());
*
* @param entity
* @return
*/
List<T> findList(T entity);
/**
* 查询所有数据列表
*
* @param entity
* @return
*/
List<T> findAllList(T entity);
/**
* 查询所有数据列表
*
* @return
* @see public List<T> findAllList(T entity)
*/
@Deprecated
List<T> findAllList();
/**
* 插入数据
*
* @param entity
* @return
*/
int insert(T entity);
/**
* 更新数据
*
* @param entity
* @return
*/
int update(T entity);
/**
* 删除数据(一般为逻辑删除,更新del_flag字段为1)
*
* @param id
* @return
* @see public int delete(T entity)
*/
@Deprecated
int delete(String id);
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
* @param id
* @see public int delete(T entity)
* @return
*/
@Deprecated
int deleteByLogic(String id);
/**
* 删除数据(一般为逻辑删除,更新del_flag字段为1)
*
* @param entity
* @return
*/
int delete(T entity);
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
* @param entity
* @return
*/
int deleteByLogic(T entity);
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import com.jeespring.modules.server.entity.SysServer;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* DAO支持类实现
*
* @param <T>
* * * * @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
public interface InterfaceBaseService<T> {
/**
* 获取单条数据
*
* @param id
* @return
*/
T get(String id);
/**
* 获取单条数据
*
* @param entity
* @return
*/
T get(T entity);
T getCache(String id);
List<T> totalCache(T entity);
/**
* 查询统计列表,如果需要分页,请设置分页对象,如:entity.setPage(new Page<T>());
*
* @param entity
* @return
*/
List<T> total(T entity);
/**
* 查询数据列表,如果需要分页,请设置分页对象,如:entity.setPage(new Page<T>());
*
* @param entity
* @return
*/
List<T> findList(T entity);
List<T> findAllList(T entity);
List<T> findListCache(T entity);
Page<T> findPage(Page<T> page, T entity);
Page<T> findPageCache(Page<T> page, T entity);
/**
* 插入数据
*
* @param entity
* @return
*/
void save(T entity);
/**
* 删除数据(一般为逻辑删除,更新del_flag字段为1)
*
* @param entity
* @return
* @see public int delete(T entity)
* @Deprecated
*/
void delete(T entity);
/**
* 删除数据(逻辑删除,更新del_flag字段为1,在表包含字段del_flag时,可以调用此方法,将数据隐藏)
* @param entity
* @see public int delete(T entity)
* @return
* @Deprecated
*/
void deleteByLogic(T entity);
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
/**
* DAO支持类实现
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
public interface InterfaceDao {
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import java.util.List;
/**
* DAO支持类实现
* @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
* @param <T>
*/
public interface TreeDao<T extends TreeEntity<T>> extends InterfaceBaseDao<T> {
/**
* 找到所有子节点
* @param entity
* @return
*/
List<T> findByParentIdsLike(T entity);
/**
* 更新所有父节点字段
* @param entity
* @return
*/
int updateParentIds(T entity);
}
\ No newline at end of file
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">jeespring</a> All rights reserved.
*/
package com.jeespring.common.persistence;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.jeespring.common.utils.Reflections;
import com.jeespring.common.utils.StringUtils;
/**
* 数据Entity类
* * * * @author 黄炳桂 516821420@qq.com
* @version 2014-05-16
*/
public abstract class TreeEntity<T> extends AbstractBaseEntity<T> {
private static final long serialVersionUID = 1L;
protected T parent; // 父级编号
protected String parentIds; // 所有父级编号
protected String name; // 机构名称
protected Integer sort; // 排序
public TreeEntity() {
super();
this.sort = 30;
}
public TreeEntity(String id) {
super(id);
}
/**
* 父对象,只能通过子类实现,父类实现mybatis无法读取
* @return
*/
@JsonBackReference
@NotNull
public abstract T getParent();
/**
* 父对象,只能通过子类实现,父类实现mybatis无法读取
* @return
*/
public abstract void setParent(T parent);
@Length(min=1, max=2000)
public String getParentIds() {
return parentIds;
}
public void setParentIds(String parentIds) {
this.parentIds = parentIds;
}
@Length(min=1, max=100)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getParentId() {
String id = null;
if (parent != null){
id = (String) Reflections.getFieldValue(parent, "id");
}
return StringUtils.isNotBlank(id) ? id : "0";
}
}
/**
* Copyright &copy; 2012-2016 <a href="https://github.com/HuangBingGui/jeespring">JeeSpring</a> All rights reserved.
*/
package com.jeespring.common.persistence.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
/**
* 标识MyBatis的DAO,方便{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的扫描。
* @author 黄炳桂 516821420@qq.com
* @version 2013-8-28
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Component
public @interface MyBatisDao {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
*/
String value() default "";
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment