Commit 15e7ac5b by Simon Cheng

创建项目矿建

parent 9a9ea765
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/pagehelper"/>
<classpathentry kind="output" path="target/classes"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>yd-api</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
<?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>
<groupId>com.yd.api</groupId>
<artifactId>yd-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>com.yd.api</name>
<description>project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.42</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
</dependencies>
<build>
<finalName>ydapi</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.yd;
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.annotation.Bean;
import com.github.pagehelper.PageHelper;
/**
* Application
*
*/
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class Application
{
public static void main( String[] args )
{
SpringApplication.run(Application.class, args);
}
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
p.setProperty("dialect", "mysql");
p.setProperty("supportMethodsArguments", "false");
p.setProperty("pageSizeZero", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
package com.yd.api.commission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yd.api.commission.service.CommissionService;
@Controller
@RestController
public class CommissionController {
@Autowired
private CommissionService commissionService;
/**
* 按照手机号从AGMS DB中查询佣金
* @param login
* @return
*/
@RequestMapping("/queryCommissionByLogin")
public Object queryCommissionByLogin(@RequestBody String login){
return commissionService.queryCommissionByLogin(login);
}
/**
* 按照手机号从EGolden DB中查询佣金
* @param login
* @return
*/
@RequestMapping("/queryCommissionByLoginFromEGolden")
public Object listAllUserfromEGolden(@RequestBody String login){
return commissionService.listSalesCommissionfromEGolden(login);
}
}
\ No newline at end of file
package com.yd.api.commission.service;
import java.util.List;
import com.yd.api.commission.vo.CommissionEGoldenVO;
import com.yd.api.commission.vo.CommissionVO;
public interface CommissionService {
List<CommissionVO> queryCommissionByLogin(String login);
List<CommissionEGoldenVO> listSalesCommissionfromEGolden(String login);
}
package com.yd.api.commission.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yd.api.commission.vo.CommissionEGoldenVO;
import com.yd.api.commission.vo.CommissionVO;
import com.yd.dataccess.entity.commission.Commission;
import com.yd.dataccess.entity.commission.CommissionEGolden;
import com.yd.dataccess.service.commission.CommissionEGoldenDA;
import com.yd.dataccess.service.commission.CommissionServiceDA;
@Service("commissionServiceImpl")
public class CommissionServiceImpl implements CommissionService{
@Autowired
private CommissionServiceDA commissionServiceDA;
@Autowired
private CommissionEGoldenDA commissionEGoldenDA;
/*
* 按照手机号从AGMS DB中查询佣金
* (non-Javadoc)
* @see com.yd.api.commission.service.CommissionService#queryCommissionByLogin(java.lang.String)
*/
@Override
public List<CommissionVO> queryCommissionByLogin(String login) {
List<CommissionVO> listTo =new ArrayList<CommissionVO>();
List<Commission> list = new ArrayList<Commission>();
list = commissionServiceDA.queryCommissionByLogin(login);
CommissionVO oneDestVO;
for(Commission oneSrc:list)
{
oneDestVO = new CommissionVO();
BeanUtils.copyProperties(oneSrc, oneDestVO);
listTo.add(oneDestVO);
}
return listTo;
}
/*
* 按照手机号从EGolden DB中查询佣金
* (non-Javadoc)
* @see com.yd.api.commission.service.CommissionService#listSalesCommissionfromEGolden(java.lang.String)
*/
@Override
public List<CommissionEGoldenVO> listSalesCommissionfromEGolden(String login) {
List<CommissionEGoldenVO> listTo =new ArrayList<CommissionEGoldenVO>();
List<CommissionEGolden> list = new ArrayList<CommissionEGolden>();
list = commissionEGoldenDA.listSalesCommissionfromEGolden(login);
CommissionEGoldenVO oneDestVO;
for(CommissionEGolden oneSrc:list)
{
oneDestVO = new CommissionEGoldenVO();
BeanUtils.copyProperties(oneSrc, oneDestVO);
listTo.add(oneDestVO);
}
return listTo;
}
}
package com.yd.api.commission.vo;
import com.yd.api.result.CommonResult;
public class CommissionEGoldenResponseVO {
private CommissionEGoldenVO CommissionEGoldenVO;
private CommonResult commonResult;
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
public CommissionEGoldenVO getCommissionEGoldenVO() {
return CommissionEGoldenVO;
}
public void setCommissionEGoldenVO(CommissionEGoldenVO commissionEGoldenVO) {
CommissionEGoldenVO = commissionEGoldenVO;
}
}
package com.yd.api.commission.vo;
public class CommissionEGoldenVO {
private String login;
private String incomeYearmonth;
private String name;
private String premium;
public String getIncomeYearmonth() {
return incomeYearmonth;
}
public void setIncomeYearmonth(String incomeYearmonth) {
this.incomeYearmonth = incomeYearmonth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
\ No newline at end of file
package com.yd.api.commission.vo;
import com.yd.api.result.CommonResult;
public class CommissionResponseVO {
private CommissionEGoldenVO CommissionVO;
private CommonResult commonResult;
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
public CommissionEGoldenVO getCommissionVO() {
return CommissionVO;
}
public void setCommissionVO(CommissionEGoldenVO commissionVO) {
CommissionVO = commissionVO;
}
}
package com.yd.api.commission.vo;
public class CommissionVO {
private String login;
private String incomeYearmonth;
private String name;
private String premium;
public String getIncomeYearmonth() {
return incomeYearmonth;
}
public void setIncomeYearmonth(String incomeYearmonth) {
this.incomeYearmonth = incomeYearmonth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
\ No newline at end of file
package com.yd.api.customer;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yd.api.customer.service.CustomerService;
import com.yd.api.customer.vo.CustomerQueryRequestVO;
import com.yd.api.customer.vo.CustomerQueryResponseVO;
import com.yd.api.customer.vo.CustomerVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryResponseVO;
import com.yd.api.result.JsonResult;
@Controller
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
@RequestMapping("/listAllCustomer")
public Object listAllCustomer(){
JsonResult result = new JsonResult();
List<CustomerVO> list = customerService.listAllCustomer();
result.setData(list);
return result;
}
/**
* 分页查询案例
* @param customerQueryRequestVO
* @return
*/
@RequestMapping("/findByPage")
public Object findByPage(@RequestBody CustomerQueryRequestVO customerQueryRequestVO){
JsonResult result = new JsonResult();
CustomerQueryResponseVO erpOrderQueryResponseVO = customerService.findByPage(customerQueryRequestVO);
result.addResult(erpOrderQueryResponseVO);
result.setData(erpOrderQueryResponseVO);
return result;
}
}
\ No newline at end of file
package com.yd.api.customer.service;
import java.util.List;
import com.github.pagehelper.PageInfo;
import com.yd.api.customer.vo.CustomerQueryRequestVO;
import com.yd.api.customer.vo.CustomerQueryResponseVO;
import com.yd.api.customer.vo.CustomerVO;
import com.yd.dataccess.entity.customer.Customer;
public interface CustomerService {
List<CustomerVO> listAllCustomer();
CustomerQueryResponseVO findByPage(CustomerQueryRequestVO customerQueryRequestVO);
}
package com.yd.api.customer.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageInfo;
import com.yd.api.customer.vo.CustomerQueryRequestVO;
import com.yd.api.customer.vo.CustomerQueryResponseVO;
import com.yd.api.customer.vo.CustomerVO;
import com.yd.dataccess.entity.customer.Customer;
import com.yd.dataccess.service.customer.CustomerDA;
import com.yd.util.page.PaginationInfo;
@Service("customerServiceImpl")
public class CustomerServiceImpl implements CustomerService{
@Autowired
private CustomerDA customerServiceDA;
@Override
public List<CustomerVO> listAllCustomer() {
List<CustomerVO> listTo =new ArrayList<CustomerVO>();
List<Customer> list = new ArrayList<Customer>();
list = customerServiceDA.listAllCustomers();
CustomerVO oneDestVO;
for(Customer oneSrc:list)
{
oneDestVO = new CustomerVO();
BeanUtils.copyProperties(oneSrc, oneDestVO);
listTo.add(oneDestVO);
}
return listTo;
}
@Override
public CustomerQueryResponseVO findByPage(CustomerQueryRequestVO customerQueryRequestVO)
{
CustomerQueryResponseVO customerQueryResponseVO = new CustomerQueryResponseVO();
PageInfo<Customer> page = customerQueryRequestVO.getPage();
PageInfo<Customer> list = customerServiceDA.findByPage(page.getPageNum(), page.getSize());
customerQueryResponseVO.setCustomerId(customerQueryRequestVO.getCustomerId());
customerQueryResponseVO.setCustomerPage(list);
return customerQueryResponseVO;
}
}
package com.yd.api.customer.vo;
import com.github.pagehelper.PageInfo;
import com.yd.dataccess.entity.customer.Customer;
public class CustomerQueryRequestVO {
private Long customerId;//客户ID
private PageInfo<Customer> page;
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public PageInfo<Customer> getPage() {
return page;
}
public void setPage(PageInfo<Customer> page) {
this.page = page;
}
}
package com.yd.api.customer.vo;
import com.github.pagehelper.PageInfo;
import com.yd.api.result.CommonResult;
import com.yd.dataccess.entity.customer.Customer;
public class CustomerQueryResponseVO {
private Long customerId;//客户ID
private PageInfo<Customer> customerPage;
private CommonResult commonResult;
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public PageInfo<Customer> getCustomerPage() {
return customerPage;
}
public void setCustomerPage(PageInfo<Customer> customerPage) {
this.customerPage = customerPage;
}
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
}
package com.yd.api.customer.vo;
import java.util.Date;
public class CustomerVO {
private int id;
private String login;
private String password;
private String mobileNo;
private Date createdAt;
private Date updatedAt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
}
package com.yd.api.market;
import com.yd.api.result.JsonResult;
import com.yd.api.market.service.MarketService;
import com.yd.api.market.vo.announcement.AnnouncementInfoVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryRequestVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MarketController {
@Autowired
private MarketService marketService;
/**
* 市场公告查询接口
* @param requestVO
* @return AnnouncementQueryResponseVO
*/
@RequestMapping("/announcementQuery")
public Object announcementQuery(@RequestBody AnnouncementQueryRequestVO requestVO){
JsonResult result = new JsonResult();
AnnouncementQueryResponseVO responseVO = marketService.announcementQuery(requestVO);
result.setData(responseVO);
result.addResult(responseVO);
return result;
}
/**
* 添加案例,返回自增id,以建立关联
* @param announcementInfoVO
* @return
*/
@RequestMapping("/addannouncement")
public Object addAnnouncement(@RequestBody AnnouncementInfoVO announcementInfoVO){
JsonResult result = new JsonResult();
AnnouncementQueryResponseVO responseVO = marketService.addAnnouncement(announcementInfoVO);
result.setData(responseVO);
result.addResult(responseVO);
return result;
}
/**
* 修改案例
* @param announcementInfoVO
* @return
*/
@RequestMapping("/updateannouncement")
public Object updateAnnouncement(@RequestBody AnnouncementInfoVO announcementInfoVO){
JsonResult result = new JsonResult();
int rows = marketService.update(announcementInfoVO);
result.setData(rows);
return result;
}
/**
* 删除案例
* @param announcementInfoVO
* @return
*/
@RequestMapping("/deleteannouncement")
public Object deleteAnnouncement(@RequestBody AnnouncementInfoVO announcementInfoVO){
JsonResult result = new JsonResult();
int rows = marketService.delete(announcementInfoVO.getAnnouncementType());
result.setData(rows);
return result;
}
}
package com.yd.api.market.service;
import com.yd.api.market.vo.announcement.AnnouncementInfoVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryRequestVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryResponseVO;
import com.yd.dataccess.entity.mkt.MktAnnouncement;
public interface MarketService {
AnnouncementQueryResponseVO announcementQuery(AnnouncementQueryRequestVO requestVO);
AnnouncementQueryResponseVO addAnnouncement(AnnouncementInfoVO announcementInfoVO);
Integer update(AnnouncementInfoVO mktAnnouncement);
Integer delete(Long announcementType);
}
package com.yd.api.market.service;
import com.yd.api.commission.vo.CommissionVO;
import com.yd.api.market.service.MarketService;
import com.yd.api.market.vo.announcement.AnnouncementInfoVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryRequestVO;
import com.yd.api.market.vo.announcement.AnnouncementQueryResponseVO;
import com.yd.api.result.CommonResult;
import com.yd.dataccess.entity.mkt.MktAnnouncement;
import com.yd.dataccess.service.mkt.MktAnnouncementServiceDA;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service("marketService")
public class MarketServiceImpl implements MarketService {
@Autowired
private MktAnnouncementServiceDA mktAnnouncementServiceDA;
@Override
public AnnouncementQueryResponseVO announcementQuery(AnnouncementQueryRequestVO requestVO) {
AnnouncementQueryResponseVO responseVO = new AnnouncementQueryResponseVO();
List<AnnouncementInfoVO> listTo =new ArrayList<AnnouncementInfoVO>();
List<MktAnnouncement> list = new ArrayList<MktAnnouncement>();
list = mktAnnouncementServiceDA.findByIsActiveAndAnnouncementAtBefore(1,new Date());
AnnouncementInfoVO oneDestVO;
for(MktAnnouncement oneSrc:list)
{
oneDestVO = new AnnouncementInfoVO();
BeanUtils.copyProperties(oneSrc, oneDestVO);
listTo.add(oneDestVO);
}
responseVO.setAnnouncementInfoList(listTo);
responseVO.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
return responseVO;
}
@Override
public AnnouncementQueryResponseVO addAnnouncement(AnnouncementInfoVO announcementInfoVO) {
AnnouncementQueryResponseVO announcementQueryResponseVO = new AnnouncementQueryResponseVO();
MktAnnouncement oneDest = new MktAnnouncement();
BeanUtils.copyProperties(announcementInfoVO, oneDest);
MktAnnouncement one = mktAnnouncementServiceDA.insert(oneDest);
List<AnnouncementInfoVO> announcementInfoList = new ArrayList<AnnouncementInfoVO>();
AnnouncementInfoVO oneVO = new AnnouncementInfoVO();
BeanUtils.copyProperties(one, oneVO);
announcementInfoList.add(oneVO);
announcementQueryResponseVO.setAnnouncementInfoList(announcementInfoList);
return announcementQueryResponseVO;
}
@Override
public Integer update(AnnouncementInfoVO mktAnnouncement) {
MktAnnouncement oneDest = new MktAnnouncement();
BeanUtils.copyProperties(mktAnnouncement, oneDest);
Integer result = mktAnnouncementServiceDA.update(oneDest);
return result;
}
@Override
public Integer delete(Long announcementType) {
return mktAnnouncementServiceDA.delete(announcementType);
}
}
package com.yd.api.market.vo.announcement;
public class AnnouncementInfoVO {
private Long id;
private Long insurerId;
private Long insurerBranchId;
private String title;
private String content;
private Long announcementType;
private String announcementTypeName;
private String announcementAt;
private Integer seq;
private Integer isActive;
private String createdAt;
private Long createdBy;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getInsurerId() {
return insurerId;
}
public void setInsurerId(Long insurerId) {
this.insurerId = insurerId;
}
public Long getInsurerBranchId() {
return insurerBranchId;
}
public void setInsurerBranchId(Long insurerBranchId) {
this.insurerBranchId = insurerBranchId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Long getAnnouncementType() {
return announcementType;
}
public void setAnnouncementType(Long announcementType) {
this.announcementType = announcementType;
}
public String getAnnouncementTypeName() {
return announcementTypeName;
}
public void setAnnouncementTypeName(String announcementTypeName) {
this.announcementTypeName = announcementTypeName;
}
public String getAnnouncementAt() {
return announcementAt;
}
public void setAnnouncementAt(String announcementAt) {
this.announcementAt = announcementAt;
}
public Integer getSeq() {
return seq;
}
public void setSeq(Integer seq) {
this.seq = seq;
}
public Integer getIsActive() {
return isActive;
}
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public Long getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
}
package com.yd.api.market.vo.announcement;
public class AnnouncementQueryRequestVO {
private Long id;
private Long announcementTypeId;//37(1=运营公告),38( 2=市场喜讯),39( 3=重要通知),40(4=新品上架),41(5=竞赛奖励)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAnnouncementTypeId() {
return announcementTypeId;
}
public void setAnnouncementTypeId(Long announcementTypeId) {
this.announcementTypeId = announcementTypeId;
}
}
package com.yd.api.market.vo.announcement;
import java.util.List;
import com.yd.api.result.CommonResult;
public class AnnouncementQueryResponseVO {
private List<AnnouncementInfoVO> announcementInfoList;
private CommonResult commonResult;
public List<AnnouncementInfoVO> getAnnouncementInfoList() {
return announcementInfoList;
}
public void setAnnouncementInfoList(List<AnnouncementInfoVO> announcementInfoList) {
this.announcementInfoList = announcementInfoList;
}
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
}
package com.yd.api.market.vo.poster;
public class OwnOpportunityInfoVO {
private Long opportunityId;
private Long orderId;
private String name;
private String mobileNo;
private String opportunityFrom;//商机来源
private String opportunityDate;//商机时间
private Long mdDropOptionId;
private Long leadsAssignedId;
public Long getMdDropOptionId() {
return mdDropOptionId;
}
public void setMdDropOptionId(Long mdDropOptionId) {
this.mdDropOptionId = mdDropOptionId;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Long getOpportunityId() {
return opportunityId;
}
public void setOpportunityId(Long opportunityId) {
this.opportunityId = opportunityId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getOpportunityFrom() {
return opportunityFrom;
}
public void setOpportunityFrom(String opportunityFrom) {
this.opportunityFrom = opportunityFrom;
}
public String getOpportunityDate() {
return opportunityDate;
}
public void setOpportunityDate(String opportunityDate) {
this.opportunityDate = opportunityDate;
}
public Long getLeadsAssignedId() {
return leadsAssignedId;
}
public void setLeadsAssignedId(Long leadsAssignedId) {
this.leadsAssignedId = leadsAssignedId;
}
}
package com.yd.api.market.vo.poster;
public class PosterInfoVO {
private Long id;
private Long itemType;
private Long itemId;
private String title;
private Long productCategoryId;
private String thumbnailPath;
private String productPosterPath;
private String isPlan;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the itemId
*/
public Long getItemId() {
return itemId;
}
/**
* @param itemId the itemId to set
*/
public void setItemId(Long itemId) {
this.itemId = itemId;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* @return the productCategoryId
*/
public Long getProductCategoryId() {
return productCategoryId;
}
/**
* @param productCategoryId the productCategoryId to set
*/
public void setProductCategoryId(Long productCategoryId) {
this.productCategoryId = productCategoryId;
}
/**
* @return the thumbnailPath
*/
public String getThumbnailPath() {
return thumbnailPath;
}
/**
* @param thumbnailPath the thumbnailPath to set
*/
public void setThumbnailPath(String thumbnailPath) {
this.thumbnailPath = thumbnailPath;
}
/**
* @return the productPosterPath
*/
public String getProductPosterPath() {
return productPosterPath;
}
/**
* @param productPosterPath the productPosterPath to set
*/
public void setProductPosterPath(String productPosterPath) {
this.productPosterPath = productPosterPath;
}
/**
* @return the itemType
*/
public Long getItemType() {
return itemType;
}
/**
* @param itemType the itemType to set
*/
public void setItemType(Long itemType) {
this.itemType = itemType;
}
/**
* @return the isPlan
*/
public String getIsPlan() {
return isPlan;
}
/**
* @param isPlan the isPlan to set
*/
public void setIsPlan(String isPlan) {
this.isPlan = isPlan;
}
}
package com.yd.api.market.vo.poster;
import com.yd.util.page.PaginationInfo;
public class PosterQueryRequestVO {
private Long mdDropOptionId;
/**
* @return the mdDropOptionId
*/
public Long getMdDropOptionId() {
return mdDropOptionId;
}
/**
* @param mdDropOptionId the mdDropOptionId to set
*/
public void setMdDropOptionId(Long mdDropOptionId) {
this.mdDropOptionId = mdDropOptionId;
}
private PaginationInfo paginationInfo;
/**
* @return the paginationInfo
*/
public PaginationInfo getPaginationInfo() {
return paginationInfo;
}
/**
* @param paginationInfo the paginationInfo to set
*/
public void setPaginationInfo(PaginationInfo paginationInfo) {
this.paginationInfo = paginationInfo;
}
}
package com.yd.api.market.vo.poster;
import java.util.List;
import com.yd.api.result.CommonResult;
import com.yd.util.page.PaginationInfo;
/**
* @author xxy
*
*/
public class PosterQueryResponseVO {
private List<PosterInfoVO> posterInfos;
private PaginationInfo paginationInfo;
private CommonResult commonResult;
/**
* 获取属性 commonResult
* @return commonResult
*/
public CommonResult getCommonResult() {
return commonResult;
}
/**
* 获取属性 commonResult
* @param commonResult
*/
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
/**
* 获取属性 posterInfos
* @return posterInfos
*/
public List<PosterInfoVO> getPosterInfos() {
return posterInfos;
}
/**
* 获取属性 posterInfos
* @param posterInfos
*/
public void setPosterInfos(List<PosterInfoVO> posterInfos) {
this.posterInfos = posterInfos;
}
/**
* 获取属性 paginationInfo
* @return paginationInfo
*/
public PaginationInfo getPaginationInfo() {
return paginationInfo;
}
/**
* 获取属性 paginationInfo
* @param paginationInfo
*/
public void setPaginationInfo(PaginationInfo paginationInfo) {
this.paginationInfo = paginationInfo;
}
}
package com.yd.api.result;
import java.io.Serializable;
public class CommonResult implements Serializable {
private static final long serialVersionUID = 1L;
private Boolean success; //执行是否成功
private String code; //ZHB错误编码
private String message; //ZHB错误信息
private String errorCode; //其他平台错误编码
private String errorMessage; //其他平台错误编码
private String flag;
/**
* 执行是否成功
* @return
*/
public Boolean isSuccess() {
return success;
}
/**
* 执行是否成功
* @param success
*/
public void setSuccess(Boolean success) {
this.success = success;
}
/**
* 获取属性 code
* @return code 最惠比平台对应的错误编码
*/
public String getCode() {
return code;
}
/**
* 属性赋值 code
* @param code 最惠比平台对应的错误编码
*/
public void setCode(String code) {
this.code = code;
}
/**
* 获取属性 message
* @return 最惠比平台对应的错误信息
*/
public String getMessage() {
return message;
}
/**
* 属性赋值 message
* @param message 最惠比平台对应的错误信息
*/
public void setMessage(String message) {
this.message = message;
}
/**
* 获取属性 errorCode
* @return 其他平台对应的错误编码
*/
public String getErrorCode() {
return errorCode;
}
/**
* 属性赋值 errorCode
* @param errorCode 其他平台对应的错误编码
*/
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
/**
* 获取属性 errorMessage
* @return 其他平台对应的错误信息
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* 属性赋值 errorMessage
* @param errorMessage 其他平台对应的错误信息
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public CommonResult() {
super();
}
/**
* @param success 是否执行成功
* @param message 最惠比平台错误信息
*/
public CommonResult(Boolean success, String message) {
super();
this.success = success;
this.message = message;
}
/**
* @param success 是否执行成功
* @param message 最惠比平台错误信息
* @param errorCode 其他平台错误编码
*/
public CommonResult(Boolean success, String message,String errorCode) {
super();
this.success = success;
this.message = message;
this.errorCode = errorCode;
}
/**
* @param success 是否执行成功
* @param message 最惠比平台错误信息
* @param errorCode 其他平台错误编码
* @param errorMessage 其他平台错误信息
*/
public CommonResult(Boolean success, String message,String errorCode,String errorMessage) {
super();
this.success = success;
this.message = message;
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
package com.yd.api.result;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//import com.ajb.config.ZHBErrorConfig;
/***
* 返回结果封装
*
* @author fan
*
*/
public class JsonResult implements Serializable {
private static final long serialVersionUID = 1L;
private boolean success;
private String message;
private Object data;
public JsonResult(){}
public JsonResult(boolean success,String msg,Object data){
this.success=success;
this.message=msg;
this.data=data;
}
public JsonResult(boolean success,String msg){
this.success=success;
this.message=msg;
this.data=null;
}
private JsonResult(String msg, Object data) {
this.message=msg;
this.success=true;
this.data=data;
}
public Object getData() {
return data;
}
public String getMessage() {
return message;
}
public boolean isSuccess() {
return success;
}
public JsonResult ofSuccess(String msg, Object data) {
return new JsonResult(msg, data) ;
}
public void setData(Object data) {
this.data = data;
}
public void setMessage(String message) {
this.message = message;
}
public void setSuccess(boolean success) {
this.success = success;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addResult(Object responseVO){
Class c = responseVO.getClass();
Method getMethod = null;
try {
Class[] classArr = null;
getMethod = c.getMethod("getCommonResult", classArr);
} catch (NoSuchMethodException | SecurityException e1) {
e1.printStackTrace();
}
CommonResult commonResult = null;
if(getMethod != null){
try {
Object[] objectArr = null;
commonResult = (CommonResult)getMethod.invoke(responseVO, objectArr);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
if(commonResult != null){
this.success = commonResult.isSuccess();
this.message = commonResult.getMessage();
}else{
this.success = true;
// this.message = ZHBErrorConfig.getErrorInfo("600001", null, null);
}
// Method setMethod = null;
// try {
// setMethod = c.getMethod("setCommonResult", CommonResult.class);
// } catch (NoSuchMethodException | SecurityException e) {
// e.printStackTrace();
// }
// if(setMethod != null){
// CommonResult args = null;
// try {
// setMethod.invoke(responseVO, args);
// } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// e.printStackTrace();
// }
// }
}
}
package com.yd.dataccess.entity.commission;
/**
* @author Simon
* @version 1.0
*/
public class Commission {
private String login;
private String incomeYearmonth;
private String name;
private String premium;
public String getIncomeYearmonth() {
return incomeYearmonth;
}
public void setIncomeYearmonth(String incomeYearmonth) {
this.incomeYearmonth = incomeYearmonth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
package com.yd.dataccess.entity.commission;
public class CommissionEGolden {
private String login;
private String incomeYearmonth;
private String name;
private String premium;
public String getIncomeYearmonth() {
return incomeYearmonth;
}
public void setIncomeYearmonth(String incomeYearmonth) {
this.incomeYearmonth = incomeYearmonth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPremium() {
return premium;
}
public void setPremium(String premium) {
this.premium = premium;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
package com.yd.dataccess.entity.customer;
import java.util.Date;
import lombok.Data;
/**
* @author Simon
* @version 1.0
*/
@Data
public class Customer {
private String login;
private String password;
private String mobileNo;
private Date createdAt;
private Date updatedAt;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
}
package com.yd.dataccess.entity.mkt;
import java.io.Serializable;
import java.util.Date;
public class MktAnnouncement implements Serializable{
private static final long serialVersionUID = 1L;
private Long id;//serial idPRIauto_increment
private Long insurerId;//保险公司ID, FK ag_acl_insurer.id
private Long insurerBranchId;//保险分支机构ID, FK ag_acl_insurer_branch.id
private String title;//公告标题
private String content;//公告内容
private Long announcementType;//FK ag_md_drop_options.id 1=运营公告 2=市场喜讯 3重要通知,4新品上架,5竞赛奖励
private Date announcementAt;//发布时间
private Integer seq;//listed sequence
private Integer isActive;//0=No, 1=Yes
private Date createdAt;//""
private Long createdBy;//""
/**
* 获取属性 id serial idPRIauto_increment
* @return id
*/
public Long getId() {
return id;
}
/**
* 属性赋值 id serial idPRIauto_increment
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取属性 insurerId 保险公司ID, FK ag_acl_insurer.id
* @return insurerId
*/
public Long getInsurerId() {
return insurerId;
}
/**
* 属性赋值 insurerId 保险公司ID, FK ag_acl_insurer.id
* @param insurerId
*/
public void setInsurerId(Long insurerId) {
this.insurerId = insurerId;
}
/**
* 获取属性 insurerBranchId 保险分支机构ID, FK ag_acl_insurer_branch.id
* @return insurerBranchId
*/
public Long getInsurerBranchId() {
return insurerBranchId;
}
/**
* 属性赋值 insurerBranchId 保险分支机构ID, FK ag_acl_insurer_branch.id
* @param insurerBranchId
*/
public void setInsurerBranchId(Long insurerBranchId) {
this.insurerBranchId = insurerBranchId;
}
/**
* 获取属性 title 公告标题
* @return title
*/
public String getTitle() {
return title;
}
/**
* 属性赋值 title 公告标题
* @param title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* 获取属性 content 公告内容
* @return content
*/
public String getContent() {
return content;
}
/**
* 属性赋值 content 公告内容
* @param content
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取属性 announcementType FK ag_md_drop_options.id 1=运营公告 2=市场喜讯 3重要通知,4新品上架,5竞赛奖励
* @return announcementType
*/
public Long getAnnouncementType() {
return announcementType;
}
/**
* 属性赋值 announcementType FK ag_md_drop_options.id 1=运营公告 2=市场喜讯 3重要通知,4新品上架,5竞赛奖励
* @param announcementType
*/
public void setAnnouncementType(Long announcementType) {
this.announcementType = announcementType;
}
/**
* 获取属性 announcementAt 发布时间
* @return announcementAt
*/
public Date getAnnouncementAt() {
return announcementAt;
}
/**
* 属性赋值 announcementAt 发布时间
* @param announcementAt
*/
public void setAnnouncementAt(Date announcementAt) {
this.announcementAt = announcementAt;
}
/**
* 获取属性 seq listed sequence
* @return seq
*/
public Integer getSeq() {
return seq;
}
/**
* 属性赋值 seq listed sequence
* @param seq
*/
public void setSeq(Integer seq) {
this.seq = seq;
}
/**
* 获取属性 isActive 0=No, 1=Yes
* @return isActive
*/
public Integer getIsActive() {
return isActive;
}
/**
* 属性赋值 isActive 0=No, 1=Yes
* @param isActive
*/
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
/**
* 获取属性 createdAt ""
* @return createdAt
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* 属性赋值 createdAt ""
* @param createdAt
*/
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* 获取属性 createdBy ""
* @return createdBy
*/
public Long getCreatedBy() {
return createdBy;
}
/**
* 属性赋值 createdBy ""
* @param createdBy
*/
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
}
\ No newline at end of file
package com.yd.dataccess.mapper.commission;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.yd.dataccess.entity.commission.CommissionEGolden;
/**
* @author Simon
* @version 1.0
*/
public interface CommissionEGoldenMapper {
List<CommissionEGolden> listSalesCommissionfromEGolden(@Param("login")String login);
}
package com.yd.dataccess.mapper.commission;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.yd.dataccess.entity.commission.Commission;
/**
* @author Simon
* @version 1.0
*/
public interface CommissionMapper {
List<Commission> queryCommissionByLogin(@Param("login")String login);
}
package com.yd.dataccess.mapper.customer;
import java.util.List;
import com.github.pagehelper.Page;
import com.yd.dataccess.entity.customer.Customer;
/**
* @author Simon
* @version 1.0
*/
public interface CustomerMapper {
List<Customer> listAllCustomer();
Page<Customer> queryByPage();
}
package com.yd.dataccess.mapper.mkt;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import com.yd.dataccess.entity.mkt.MktAnnouncement;
@Repository
public interface MktAnnouncementMapper{
/**
* 通过公告类型查询公告
* @param announcementType
* @return
*/
void insert(MktAnnouncement mktAnnouncement);
Integer update(MktAnnouncement mktAnnouncement);
Integer delete(@Param("announcementType")Long announcementType);
List<MktAnnouncement> findByType(@Param("announcementType")Long announcementType);
List<MktAnnouncement> findByIsActive(@Param("isActive")Integer isActive);
List<MktAnnouncement> findByIsActiveAndAnnouncementAtBefore(@Param("isActive")Integer isActive, @Param("announcementAt")Date announcementAt);
List<MktAnnouncement> findBySeqAndIsActive(@Param("seq")Integer seq, @Param("isActive")Integer isActive);
}
\ No newline at end of file
package com.yd.dataccess.service.commission;
import java.util.List;
import com.yd.dataccess.entity.commission.CommissionEGolden;
/**
* @author Simon
* @version 1.0
*/
public interface CommissionEGoldenDA {
List<CommissionEGolden> listSalesCommissionfromEGolden(String login);
}
package com.yd.dataccess.service.commission;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.yd.dataccess.entity.commission.CommissionEGolden;
import com.yd.dataccess.mapper.commission.CommissionEGoldenMapper;
import com.yd.util.intercept.annotation.TargetDataSource;
import com.yd.util.intercept.commons.DataSourceKey;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author Simon
* @version 1.0
*/
@Service("commissionEGoldenDAImpl")
public class CommissionEGoldenDAImpl implements CommissionEGoldenDA {
private static final Logger LOG = Logger.getLogger(CommissionEGoldenDAImpl.class);
@Resource
private CommissionEGoldenMapper commissionEGoldenMapper;
/*
* 按照手机号从EGolden DB中查询佣金
* 通过标签指定数据源:dataSourceKey = DataSourceKey.DB_EGOLDEN
* (non-Javadoc)
* @see com.yd.dataccess.service.commission.CommissionEGoldenDA#listSalesCommissionfromEGolden(java.lang.String)
*/
@Override
@TargetDataSource(dataSourceKey = DataSourceKey.DB_EGOLDEN)
public List<CommissionEGolden> listSalesCommissionfromEGolden(String login) {
List<CommissionEGolden> destList = new ArrayList<CommissionEGolden>();
destList = commissionEGoldenMapper.listSalesCommissionfromEGolden(login);
return destList;
}
}
package com.yd.dataccess.service.commission;
import java.util.List;
import com.yd.dataccess.entity.commission.Commission;
/**
* @author Simon
* @version 1.0
*/
public interface CommissionServiceDA {
List<Commission> queryCommissionByLogin(String login);
}
package com.yd.dataccess.service.commission;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.yd.dataccess.entity.commission.Commission;
import com.yd.dataccess.mapper.commission.CommissionMapper;
import com.yd.util.intercept.annotation.TargetDataSource;
import com.yd.util.intercept.commons.DataSourceKey;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @Transactional class level transaction管理
* @author Simon
* @version 1.0
*/
@Service("commissionServiceDAImpl")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CommissionServiceDAImpl implements CommissionServiceDA {
private static final Logger LOG = Logger.getLogger(CommissionServiceDAImpl.class);
@Resource
private CommissionMapper commissionMapper;
/*
* 按照手机号从AGMS DB中查询佣金
* 通过标签指定数据源:dataSourceKey = DataSourceKey.DB_MASTER
* 不指定@TargetDataSource,缺省的就是DB_MASTER主库
*
* @Transactional method level transaction管理
* (non-Javadoc)
* @see com.yd.dataccess.service.commission.CommissionServiceDA#queryCommissionByLogin(java.lang.String)
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@TargetDataSource(dataSourceKey = DataSourceKey.DB_MASTER)
public List<Commission> queryCommissionByLogin(String login){
List<Commission> destList = new ArrayList<Commission>();
destList = commissionMapper.queryCommissionByLogin(login);
return destList;
}
}
package com.yd.dataccess.service.customer;
import java.util.List;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.yd.dataccess.entity.customer.Customer;
/**
* @author Simon
* @version 1.0
*/
public interface CustomerDA {
List<Customer> listAllCustomers();
PageInfo<Customer> findByPage(int pageNo, int pageSize);
}
package com.yd.dataccess.service.customer;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yd.dataccess.entity.customer.Customer;
import com.yd.dataccess.mapper.customer.CustomerMapper;
import com.yd.util.intercept.annotation.TargetDataSource;
import com.yd.util.intercept.commons.DataSourceKey;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author Simon
* @version 1.0
*/
@Service("customerDAImpl")
public class CustomerDAImpl implements CustomerDA {
private static final Logger LOG = Logger.getLogger(CustomerDAImpl.class);
@Resource
private CustomerMapper customerMapper;
@Override
@TargetDataSource(dataSourceKey = DataSourceKey.DB_MASTER)
public List<Customer> listAllCustomers() {
PageHelper.startPage(1,10);
List<Customer> destList = new ArrayList<Customer>();
destList = customerMapper.listAllCustomer();
return destList;
}
/**
* 分页查询,指定页数,每页rows行数
*/
@Override
public PageInfo<Customer> findByPage(int pageNo, int pageSize) {
String orderBy = "created_at desc";
PageHelper.startPage(pageNo, pageSize, orderBy);
Page<Customer> destList = customerMapper.queryByPage();
PageInfo<Customer> pageInfo = new PageInfo<>(destList);
return pageInfo;
}
}
package com.yd.dataccess.service.mkt;
import com.yd.dataccess.entity.mkt.MktAnnouncement;
import java.util.Date;
import java.util.List;
public interface MktAnnouncementServiceDA {
/**** 下面是自定义方法 ****/
/**
* 通过公告类型查询公告
* @param announcementType
* @return
*/
MktAnnouncement insert(MktAnnouncement mktAnnouncement);
int update(MktAnnouncement mktAnnouncement);
int delete(Long announcementType);
List<MktAnnouncement> findByType(Long announcementType);
/**
* 查询所有有效的公告
* @param isActive
* @return
*/
List<MktAnnouncement> findByIsActive(Integer isActive);
List<MktAnnouncement> findByIsActiveAndAnnouncementAtBefore(int isActive, Date announcementAt);
List<MktAnnouncement> findBySeqAndIsActive(Integer seq, Integer isActive);
}
\ No newline at end of file
package com.yd.dataccess.service.mkt;
import com.yd.dataccess.entity.mkt.MktAnnouncement;
import com.yd.dataccess.mapper.mkt.MktAnnouncementMapper;
import com.yd.util.intercept.annotation.TargetDataSource;
import com.yd.util.intercept.commons.DataSourceKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* @Transactional class level transaction管理
* @author Simon
* @version 1.0
*/
@Service("mktAnnouncementServiceDAImpl")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class MktAnnouncementServiceDAImpl implements MktAnnouncementServiceDA {
@Resource
private MktAnnouncementMapper mktAnnouncementMapper;
@Override
@TargetDataSource(dataSourceKey = DataSourceKey.DB_MASTER)
public List<MktAnnouncement> findByType(Long announcementType) {
List<MktAnnouncement> destList = new ArrayList<MktAnnouncement>();
destList = mktAnnouncementMapper.findByType(announcementType);
return destList;
}
@Override
public List<MktAnnouncement> findByIsActive(Integer isActive) {
List<MktAnnouncement> destList = new ArrayList<MktAnnouncement>();
destList = mktAnnouncementMapper.findByIsActive(isActive);
return destList;
}
@Override
public List<MktAnnouncement> findByIsActiveAndAnnouncementAtBefore(int isActive, Date announcementAt) {
List<MktAnnouncement> destList = new ArrayList<MktAnnouncement>();
destList = mktAnnouncementMapper.findByIsActiveAndAnnouncementAtBefore(isActive,announcementAt);
return destList;
}
/*
* 查询记录
* (non-Javadoc)
* @see com.yd.dataccess.service.mkt.MktAnnouncementServiceDA#findBySeqAndIsActive(java.lang.Integer, java.lang.Integer)
*/
@Override
public List<MktAnnouncement> findBySeqAndIsActive(Integer seq, Integer isActive) {
List<MktAnnouncement> destList = new ArrayList<MktAnnouncement>();
destList = mktAnnouncementMapper.findBySeqAndIsActive(seq,isActive);
return destList;
}
/*
* add添加一条记录
* @Transactional method level transaction管理
* (non-Javadoc)
* @see com.yd.dataccess.service.mkt.MktAnnouncementServiceDA#insert(com.yd.dataccess.entity.mkt.MktAnnouncement)
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public MktAnnouncement insert(MktAnnouncement mktAnnouncement) {
mktAnnouncementMapper.insert(mktAnnouncement);
return mktAnnouncement;
}
/*
* update修改一条记录
* (non-Javadoc)
* @see com.yd.dataccess.service.mkt.MktAnnouncementServiceDA#update(com.yd.dataccess.entity.mkt.MktAnnouncement)
*/
@Override
public int update(MktAnnouncement mktAnnouncement) {
int result = mktAnnouncementMapper.update(mktAnnouncement);
return result;
}
/*
* delete删除一条记录
* (non-Javadoc)
* @see com.yd.dataccess.service.mkt.MktAnnouncementServiceDA#delete(java.lang.Long)
*/
@Override
public int delete(Long announcementType) {
int result = mktAnnouncementMapper.delete(announcementType);
return result;
}
}
\ No newline at end of file
package com.yd.util;
/*import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
*/
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.*;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CommonUtil {
private static final String EMAIL_REGEX="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";//邮箱正则表达式
/*
* 日期格式:http://blog.csdn.net/linghu_java/article/details/38379603
* yyyy-MM-dd HH:mm:ss:SSS 24小时制
* yyyy-MM-dd hh:mm:ss:SSS 12小时制
*/
/**
* 日期转换成字符串
* @param source
* @param pattern 例如 yyyy-MM-dd HH:mm:ss
* @return
*/
public static String dateParseString(Date source,String pattern){
if(source == null){
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(source);
}
/**
* n年后
* @param current
* @param year
* @return
*/
public static Date afterYear(Date current,int year)
{
Calendar cal = Calendar.getInstance();
cal.setTime(current);
cal.add(Calendar.YEAR, year);//增加一年
return cal.getTime();
}
/**
* 字符串转换成日期
* @param source
* @param pattern 例如 yyyy-MM-dd HH:mm:ss
* @return
*/
public static Date stringParseDate(String source,String pattern){
if(isNullOrBlank(source) || isNullOrBlank(pattern)){
return null;
}
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
date = sdf.parse(source);
} catch (ParseException e) {
return null;
}
return date;
}
public static double doubleFormat(Double source,int num){
if(source == null){
source = 0d;
}
BigDecimal bd = new BigDecimal(source.toString());
double result = bd.setScale(num, BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
public static String doubleParseString(Double source,String parten){
if(source == null){
source = 0d;
}
if(parten == null){
parten = "##,###,###,##0.00";
}
DecimalFormat fmt = new DecimalFormat(parten);
return fmt.format(source);
}
public static String longParseString(Long source,String parten){
if(source == null){
source = 0L;
}
if(parten == null){
parten = "##,###,###,###";
}
DecimalFormat fmt = new DecimalFormat(parten);
return fmt.format(source);
}
/**
* 空字符串付默认值
* @param source
* @param defaultValue
* @return
*/
public static String nullStringToDefault(String source,String defaultValue){
String result = source;
if(isNullOrBlank(source)){
result = defaultValue;
}
return result;
}
public static Integer stringParseInt(String source){
Integer result = null;
if(isNullOrBlank(source)){
return null;
}else{
try{
result = Integer.parseInt(source);
}catch(Exception e){}
}
return result;
}
public static Long stringParseLong(String source){
Long result = null;
if(isNullOrBlank(source)){
return null;
}else{
try{
result = Long.parseLong(source);
}catch(Exception e){}
}
return result;
}
public static Double stringParseDouble(String source){
Double result = null;
if(isNullOrBlank(source)){
return null;
}else{
try{
result = Double.parseDouble(source);
}catch(Exception e){}
}
return result;
}
public static boolean isNullOrBlank(String source){
boolean result = false;
if(source == null){
result = true;
}else if("".equals(source.trim())){
result = true;
}
return result ;
}
public static String getClassType(Object source){
String classType = "Integer";
if(source == null){
return null;
}
String className = source.getClass().getName();
if(className.contains("java.lang.Integer")){
classType = "Integer";
}else if(className.contains("java.lang.Long")){
classType = "Long";
}else if(className.contains("java.lang.Double")){
classType = "Double";
}else if(className.contains("java.math.BigInteger")){
classType = "BigInteger";
}else if(className.contains("java.math.BigDecimal")){
classType = "BigDecimal";
}
return classType;
}
public static Integer intValue(Object source){
Integer result = null;
if(source == null){
return 0;
}
try{
if("Integer".equals(getClassType(source))){
result = ((Integer)source).intValue();
}else if("BigInteger".equals(getClassType(source))){
result = ((BigInteger)source).intValue();
}else if("BigDecimal".equals(getClassType(source))){
result = ((BigDecimal)source).intValue();
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static boolean isNullOrZero(Object source){
boolean result = false;
if(source == null){
result = true;
}else{
if("Integer".equals(getClassType(source))){
int value = ((Integer)source).intValue();
if(value == 0){
result = true;
}
}else if("Long".equals(getClassType(source))){
long value = ((Long)source).longValue();
if(value == 0){
result = true;
}
}else if("Double".equals(getClassType(source))){
double value = ((Double)source).doubleValue();
if(value == 0){
result = true;
}
}else if("BigInteger".equals(getClassType(source))){
double value = ((BigInteger)source).doubleValue();
if(value == 0){
result = true;
}
}else if("BigDecimal".equals(getClassType(source))){
double value = ((BigDecimal)source).doubleValue();
if(value == 0){
result = true;
}
}
}
return result ;
}
/**
* 求时间差
* @param source 终止时间
* @param target 开始时间
* @param unit D天 H小时 M分 S秒 MS毫秒
* @return
*/
public static long getDatePeriod(Date source,Date target,String unit){
long result = 0;
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long ms = 1;
// 获得两个时间的毫秒时间差异
long diff = source.getTime() - target.getTime();
/*
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
long sec = diff % nd % nh % nm / ns;
//return day + "天" + hour + "小时" + min + "分钟";
*/
if("D".equals(unit)){
result = diff / nd;
}else if("H".equals(unit)){
result = diff / nh;
}else if("M".equals(unit)){
result = diff / nm;
}else if("S".equals(unit)){
result = diff / ns;
}else if("MS".equals(unit)){
result = diff / ms;
}
return result;
}
/**
*
* @param source
* @param operation ADD或SUB
* @param unit S秒 M分钟 H小时 D天 W周 Mon月 Y年
* @param number
* @return
*/
public static Date dateOperation(Date source,String operation,String unit,int number){
Date result = null;
Calendar calendar = Calendar.getInstance();
calendar.setTime(source);
int field = Calendar.SECOND;
if("S".equals(unit)){
field = Calendar.SECOND;
}else if("M".equals(unit)){
field = Calendar.MINUTE;
}else if("H".equals(unit)){
field = Calendar.HOUR_OF_DAY;
}else if("D".equals(unit)){
field = Calendar.DATE;
}else if("W".equals(unit)){
field = Calendar.WEEK_OF_MONTH;
}else if("Mon".equals(unit)){
field = Calendar.MONTH;
}else if("Y".equals(unit)){
field = Calendar.YEAR;
}
if("SUB".equals(operation)){
calendar.add(field, -number);
}else{
calendar.add(field, number);
}
result = calendar.getTime();
return result;
}
/**
* 由出生日期获得年龄
* @param birthDay
* @return
* @throws Exception
*/
public static int getAge(Date birthDay){
int age = 0;
if(birthDay == null){
return 0;
}
try{
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
// throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
return -1;
}
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth){
age--;
}
}else{
age--;
}
}
}catch(Exception e){}
return age;
}
/**
* 由出生日期到截至日期获得年龄
* @param birthDay
* @return
* @throws Exception
*/
public static int getAge(Date birthDay,Date endDate){
int age = 0;
if(birthDay == null){
return 0;
}
try{
Calendar cal = Calendar.getInstance();
if (cal.before(birthDay)) {
// throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
return -1;
}
cal.setTime(endDate);
int yearNow = cal.get(Calendar.YEAR);
int monthNow = cal.get(Calendar.MONTH);
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(birthDay);
int yearBirth = cal.get(Calendar.YEAR);
int monthBirth = cal.get(Calendar.MONTH);
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
age = yearNow - yearBirth;
if (monthNow <= monthBirth) {
if (monthNow == monthBirth) {
if (dayOfMonthNow < dayOfMonthBirth){
age--;
}
}else{
age--;
}
}
}catch(Exception e){}
return age;
}
/**
* 根据异常对象获取异常堆栈字符串
* @param e
* @return
*/
public static String parseExceptionStack(Exception e){
String exceptionStack = null;
/*StringBuffer sbf = new StringBuffer();
StackTraceElement[] stack = e.getStackTrace();
StackTraceElement element = null;
String message = e.toString();
sbf.append(message+"\n");
for(int i=0;i<stack.length;i++){
element = stack[i];
String fileName = element.getFileName();
String methodName = element.getMethodName();
String className = element.getClassName();
int lineNumber = element.getLineNumber();
String append = fileName+":"+lineNumber;
boolean isNativeMethod = element.isNativeMethod();
if(isNativeMethod){
append = "Native Method";
}
sbf.append(" at "+className+"."+methodName+"("+append+")\n");
}
exceptionStack = sbf.toString();*/
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
exceptionStack = sw.toString();
return exceptionStack;
}
public static boolean isValidDate(String source,String pattern) {
boolean convertSuccess = true;
if(isNullOrBlank(source)){
return false;
}
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
format.setLenient(false);
format.parse(source);
}catch(Exception e) {
convertSuccess=false;
}
return convertSuccess;
}
public static boolean checkEmail(String email){
return Pattern.matches(EMAIL_REGEX, email.trim());
}
/**
*
* @param area 省份名、城市名、县名
* @param birthDay 出生日期,格式(19891019)
* @param gender 性别(范围:1-9,男:奇数,女:偶数)
* @param age
* @return
*/
public static String createID(String area,String birthDay,String gender,Integer age){
String idNo = null;
String areaCode = null;
String seqNo = getRandomNum(2)+""; // (两位)顺序号,格式(00-99)
Random random = new Random();
String areaCodeFile = CommonUtil.class.getResource("").getPath()+File.separator+"areaCode.txt";
System.out.println(areaCodeFile);
List<String> areaList = readFile(areaCodeFile, "UTF-8");
if(area == null || "".equals(area)){
String item = areaList.get(random.nextInt(areaList.size()) -1);
areaCode = item.split(" ")[0];
}else{
for(String item : areaList){
if(item.contains(area)){
areaCode = item.split(" ")[0];
break;
}
}
}
if(areaCode == null){areaCode = "110101";}
if(birthDay == null || "".equals(birthDay)){
if(age == null || age <= 0){
int[] arr = new int[]{1,2,3,4};
int a = arr[random.nextInt(4)];
String ageStr = a+getRandomNum(1);
age = Integer.parseInt(ageStr);
}
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -age);
int randomDay = 1+(int)(Math.random()*360);
calendar.add(Calendar.DAY_OF_YEAR, -randomDay);
birthDay = dateParseString(calendar.getTime(), "yyyyMMdd");
}
if(gender == null || "".equals(gender)){
gender = getRandomNum(1)+"";
}
// 前17位要除以的数:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
int finalAreaCode = Integer.parseInt(areaCode.substring(0, 1)) * 7
+ Integer.parseInt(areaCode.substring(1, 2)) * 9
+ Integer.parseInt(areaCode.substring(2, 3)) * 10
+ Integer.parseInt(areaCode.substring(3, 4)) * 5
+ Integer.parseInt(areaCode.substring(4, 5)) * 8
+ Integer.parseInt(areaCode.substring(5, 6)) * 4;
int finalBirthday = Integer.parseInt(birthDay.substring(0, 1)) * 2
+ Integer.parseInt(birthDay.substring(1, 2)) * 1
+ Integer.parseInt(birthDay.substring(2, 3)) * 6
+ Integer.parseInt(birthDay.substring(3, 4)) * 3
+ Integer.parseInt(birthDay.substring(4, 5)) * 7
+ Integer.parseInt(birthDay.substring(5, 6)) * 9
+ Integer.parseInt(birthDay.substring(6, 7)) * 10
+ Integer.parseInt(birthDay.substring(7, 8)) * 5;
int NoIs = (Integer.parseInt(seqNo.substring(0, 1))) * 8
+ (Integer.parseInt(seqNo.substring(1, 2))) * 4;
int sexNo = (Integer.parseInt(gender.substring(0, 1))) * 2;
int checkCode = (finalAreaCode + finalBirthday + NoIs + sexNo) % 11;
int finalCheckCode = 0;
// 余数范围: 0 1 2 3 4 5 6 7 8 9 10
// 余数对应的数:1 0 X 9 8 7 6 5 4 3 2
// 计算出最终的校验码:finalCheckCode
switch (checkCode) {
case 0:
finalCheckCode = 1;
break;
case 1:
finalCheckCode = 0;
break;
case 2:
finalCheckCode = -3;
break;
case 3:
finalCheckCode = 9;
break;
case 4:
finalCheckCode = 8;
break;
case 5:
finalCheckCode = 7;
break;
case 6:
finalCheckCode = 6;
break;
case 7:
finalCheckCode = 5;
break;
case 8:
finalCheckCode = 4;
break;
case 9:
finalCheckCode = 3;
break;
case 10:
finalCheckCode = 2;
break;
default:
break;
}
// 区域编号(6位数)+出生日期(8位数)+顺序编号(2位数)+性别号(1位数)+校验码(1位数)=身份证号(18位数)
String checkInd = null;
if(finalCheckCode == -3){
checkInd = "X";
}else{
checkInd = finalCheckCode+"";
}
idNo = areaCode + birthDay + seqNo + gender + checkInd;
return idNo;
}
public static String createMail(){
String mail = getRandomString(5)+"@163.com";
return mail;
}
public static String createPhoneNo(){
return "139"+getRandomNum(8);
}
public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static String getRandomNum(int length) { //length表示生成字符串的长度
String base = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public static String createName(){
Random random=new Random(System.currentTimeMillis());
/* 598 百家姓 */
String[] Surname= {"赵","钱","孙","李","周","吴","郑","王","冯","陈","褚","卫","蒋","沈","韩","杨","朱","秦","尤","许",
"何","吕","施","张","孔","曹","严","华","金","魏","陶","姜","戚","谢","邹","喻","柏","水","窦","章","云","苏","潘","葛","奚","范","彭","郎",
"鲁","韦","昌","马","苗","凤","花","方","俞","任","袁","柳","酆","鲍","史","唐","费","廉","岑","薛","雷","贺","倪","汤","滕","殷",
"罗","毕","郝","邬","安","常","乐","于","时","傅","皮","卞","齐","康","伍","余","元","卜","顾","孟","平","黄","和",
"穆","萧","尹","姚","邵","湛","汪","祁","毛","禹","狄","米","贝","明","臧","计","伏","成","戴","谈","宋","茅","庞","熊","纪","舒",
"屈","项","祝","董","梁","杜","阮","蓝","闵","席","季","麻","强","贾","路","娄","危","江","童","颜","郭","梅","盛","林","刁","钟",
"徐","邱","骆","高","夏","蔡","田","樊","胡","凌","霍","虞","万","支","柯","昝","管","卢","莫","经","房","裘","缪","干","解","应",
"宗","丁","宣","贲","邓","郁","单","杭","洪","包","诸","左","石","崔","吉","钮","龚","程","嵇","邢","滑","裴","陆","荣","翁","荀",
"羊","于","惠","甄","曲","家","封","芮","羿","储","靳","汲","邴","糜","松","井","段","富","巫","乌","焦","巴","弓","牧","隗","山",
"谷","车","侯","宓","蓬","全","郗","班","仰","秋","仲","伊","宫","宁","仇","栾","暴","甘","钭","厉","戎","祖","武","符","刘","景",
"詹","束","龙","叶","幸","司","韶","郜","黎","蓟","溥","印","宿","白","怀","蒲","邰","从","鄂","索","咸","籍","赖","卓","蔺","屠",
"蒙","池","乔","阴","郁","胥","能","苍","双","闻","莘","党","翟","谭","贡","劳","逄","姬","申","扶","堵","冉","宰","郦","雍","却",
"璩","桑","桂","濮","牛","寿","通","边","扈","燕","冀","浦","尚","农","温","别","庄","晏","柴","瞿","阎","充","慕","连","茹","习",
"宦","艾","鱼","容","向","古","易","慎","戈","廖","庾","终","暨","居","衡","步","都","耿","满","弘","匡","国","文","寇","广","禄",
"阙","东","欧","殳","沃","利","蔚","越","夔","隆","师","巩","厍","聂","晁","勾","敖","融","冷","訾","辛","阚","那","简","饶","空",
"曾","毋","沙","乜","养","鞠","须","丰","巢","关","蒯","相","查","后","荆","红","游","郏","竺","权","逯","盖","益","桓","公","仉",
"督","岳","帅","缑","亢","况","郈","有","琴","归","海","晋","楚","闫","法","汝","鄢","涂","钦","商","牟","佘","佴","伯","赏","墨",
"哈","谯","篁","年","爱","阳","佟","言","福","南","火","铁","迟","漆","官","冼","真","展","繁","檀","祭","密","敬","揭","舜","楼",
"疏","冒","浑","挚","胶","随","高","皋","原","种","练","弥","仓","眭","蹇","覃","阿","门","恽","来","綦","召","仪","风","介","巨",
"木","京","狐","郇","虎","枚","抗","达","杞","苌","折","麦","庆","过","竹","端","鲜","皇","亓","老","是","秘","畅","邝","还","宾",
"闾","辜","纵","侴","万俟","司马","上官","欧阳","夏侯","诸葛","闻人","东方","赫连","皇甫","羊舌","尉迟","公羊","澹台","公冶","宗正",
"濮阳","淳于","单于","太叔","申屠","公孙","仲孙","轩辕","令狐","钟离","宇文","长孙","慕容","鲜于","闾丘","司徒","司空","兀官","司寇",
"南门","呼延","子车","颛孙","端木","巫马","公西","漆雕","车正","壤驷","公良","拓跋","夹谷","宰父","谷梁","段干","百里","东郭","微生",
"梁丘","左丘","东门","西门","南宫","第五","公仪","公乘","太史","仲长","叔孙","屈突","尔朱","东乡","相里","胡母","司城","张廖","雍门",
"毋丘","贺兰","綦毋","屋庐","独孤","南郭","北宫","王孙"};
int index=random.nextInt(Surname.length-1);
String name = Surname[index]; //获得一个随机的姓氏
/* 从常用字中选取一个或两个字作为名 */
if(random.nextBoolean()){
name+=getChinese()+getChinese();
}else {
name+=getChinese();
}
// System.out.println(name);
return name;
}
public static String getChinese() {
String str = null;
int highPos, lowPos;
Random random = new Random();
highPos = (176 + Math.abs(random.nextInt(71)));//区码,0xA0打头,从第16区开始,即0xB0=11*16=176,16~55一级汉字,56~87二级汉字
random=new Random();
lowPos = 161 + Math.abs(random.nextInt(94));//位码,0xA0打头,范围第1~94列
byte[] bArr = new byte[2];
bArr[0] = (new Integer(highPos)).byteValue();
bArr[1] = (new Integer(lowPos)).byteValue();
try {
str = new String(bArr, "GB2312"); //区位码组合成汉字
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
@SuppressWarnings("rawtypes")
public static String currentIP(){
String currentIP = null;
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()){
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()){
ip = (InetAddress) addresses.nextElement();
if(ip != null && ip instanceof Inet4Address){
if(currentIP == null){
currentIP = "";
}
currentIP += ip.getHostAddress()+";";
// System.out.println("本机的IP = " + currentIP);
}
if(ip != null && ip instanceof Inet6Address){
if(currentIP == null){
currentIP = "";
}
currentIP += ip.getHostAddress()+":";
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return currentIP;
}
/**
* 获取HttpServletRequest请求IP
* @param request
* @return
*/
public static String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
@SuppressWarnings("rawtypes")
public static void simpleObjectCopy(Object source,Object target){
if(source == null || target == null){ return; }
try {
Method[] sourceMethods = source.getClass().getDeclaredMethods();
for(Method smethod : sourceMethods){
Class returnType = smethod.getReturnType();
String sourceMethodName = smethod.getName();
if(!returnType.getTypeName().equals("void") && sourceMethodName.startsWith("get")){
Object[] paramArr = null;
Object getValue = smethod.invoke(source,paramArr);
if(getValue != null){
// System.out.println("--------------in simpleObjectCopy returnType : "+returnType.getTypeName()+" sourceMethodName="+sourceMethodName);
Method[] targetMethods = target.getClass().getDeclaredMethods();
for(Method tmethod : targetMethods){
String targetMethodName = tmethod.getName();
if(targetMethodName.equals("set"+sourceMethodName.substring(3))){
Class[] parameterTypes = tmethod.getParameterTypes();
if(parameterTypes != null && parameterTypes.length == 1 && parameterTypes[0].getTypeName().equals(returnType.getTypeName())){
// System.out.println("--------------in simpleObjectCopy targetMethodName:"+targetMethodName);
tmethod.invoke(target,getValue);
}//set value
break;
}//set
}//for targetMethod
}//get value != null
}//get
}//for sourceMethod
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
public static String getInputStreamContent(InputStream inputStream,String charset)throws Exception{
String content = null;
if(inputStream == null){
return null;
}
if(charset == null ){
charset = "UTF-8";
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,charset));// 为了进行一行读取操作
StringBuilder buffer = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
content = buffer.toString();
return content;
}
public static List<String> readFile(String fileName,String encoding){
List<String> contents = new ArrayList<String>();
File file = new File(fileName);
FileInputStream fi = null;
InputStreamReader ir = null;
BufferedReader br = null;
try {
fi = new FileInputStream(file);
ir = new InputStreamReader(fi,encoding);
br = new BufferedReader(ir);
while(br.ready()){
String line = br.readLine();
contents.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
fi.close();
ir.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return contents;
}
public static void writeFile(List<String> contents,String fileName,boolean appending,String encoding){
File file = new File(fileName);
FileOutputStream fo = null;
OutputStreamWriter or = null;
BufferedWriter bw = null;
try {
fo = new FileOutputStream(file,appending);
or = new OutputStreamWriter(fo,encoding);
bw = new BufferedWriter(or);
for(String line : contents){
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
fo.close();
or.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断是否是数字
*/
private static final Pattern NUMBER_PATTERN = Pattern.compile("[0-9]*");
public static boolean isNumeric(String str){
// Pattern pattern = Pattern.compile("[0-9]*");
// Matcher isNum = pattern.matcher(str);
Matcher numMatcher = NUMBER_PATTERN.matcher(str);
if( !numMatcher.matches() ){
return false;
}
return true;
}
// 根据Unicode编码完美的判断中文汉字和符号
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
return true;
}
return false;
}
/**
* 判断字符串中是否含有数字
* @param content
* @return
*/
public static boolean hasDigit(String content) {
boolean flag = false;
Pattern pattern = Pattern.compile(".*\\d+.*");
Matcher m = pattern.matcher(content);
if (m.matches()) {
flag = true;
}
return flag;
}
/**
* 判断是否含有特殊字符
*
* @param str
* @return true为包含,false为不包含
*/
public static final String DEFAULT_QUERY_REGEX = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
public static boolean isSpecialCharacter(String str) {
Pattern p = Pattern.compile(DEFAULT_QUERY_REGEX);
Matcher m = p.matcher(str);
return m.find();
}
/**
* 通过ip地址获取该ip的实际地理地址
* @param ip
* @return
*//*
public static String getAddressByIP(String ip){
String address = null;
try{
URL url = new URL( "http://ip.taobao.com/service/getIpInfo.php?ip=" + ip);
URLConnection conn = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line = null;
StringBuffer result = new StringBuffer();
while((line = reader.readLine()) != null){
result.append(line);
}
reader.close();
String ipInfo = result.toString();
IpToAddress ipToAddress = (IpToAddress) JsonUtil.jsonToObj(ipInfo, IpToAddress.class);
if (ipToAddress != null) {
if("0".equals(ipToAddress.getCode())){
String area = ipToAddress.getData().getCountry();
if (area == null && "".equals(area)) {
area = ipToAddress.getData().getArea();
}
String region = ipToAddress.getData().getRegion();
String city = ipToAddress.getData().getCity();
String isp = ipToAddress.getData().getIsp();
address = area+"_"+region+"_"+city+"_"+isp;
}
}
}
catch( IOException e){
System.out.println( "获取失败!!!!");
}
return address;
}*/
/**
* 判断姓名(中文姓名和英文姓名)
* @param idType
*/
public static boolean isConSpeCharacters(String str, Long idType) {
if (idType==9) {
if (str.replaceAll("^[\u3400-\u9fa5A-Za-z]+[\\s·/.,(())\u3400-\u9fa5A-Za-z]*[\u3400-\u9fa5A-Za-z))]+$", "").length() == 0) {
return false;
}
}else{
if (str.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*[\\s·.]*", "").length() == 0) {
return false;
}
}
return true;
}
/**
* 通过身份证号码获取出生日期、性别、年龄
* @param certificateNo
* @return 返回的出生日期格式:1990-01-01 性别格式:F-女,M-男
*/
/**
* 通过身份证号码获取出生日期、性别、年龄
* @param certificateNo 身份证号码
* @param type birthday -- 出生年月日 age--年龄 sex--性别
* @return 结果 sex--性别 1-男 2-女
*/
public static String getBirAgeSex(String certificateNo,String type) {
String birthday = "";
String age = "";
String sexCode = "";
String result = "";
int year = Calendar.getInstance().get(Calendar.YEAR);
char[] number = certificateNo.toCharArray();
boolean flag = true;
if (number.length == 15) {
for (int x = 0; x < number.length; x++) {
if (!flag) return null;
flag = Character.isDigit(number[x]);
}
} else if (number.length == 18) {
for (int x = 0; x < number.length - 1; x++) {
if (!flag) return null;
flag = Character.isDigit(number[x]);
}
}
if (flag && certificateNo.length() == 15) {
birthday = "19" + certificateNo.substring(6, 8) + "-"
+ certificateNo.substring(8, 10) + "-"
+ certificateNo.substring(10, 12);
sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 3, certificateNo.length())) % 2 == 0 ? "F" : "M";
age = (year - Integer.parseInt("19" + certificateNo.substring(6, 8))) + "";
} else if (flag && certificateNo.length() == 18) {
birthday = certificateNo.substring(6, 10) + "-"
+ certificateNo.substring(10, 12) + "-"
+ certificateNo.substring(12, 14);
sexCode = Integer.parseInt(certificateNo.substring(certificateNo.length() - 4, certificateNo.length() - 1)) % 2 == 0 ? "F" : "M";
age = (year - Integer.parseInt(certificateNo.substring(6, 10))) + "";
}
Map<String, String> map = new HashMap<String, String>();
map.put("birthday", birthday);
map.put("age", age);
map.put("sexCode", sexCode);
if ("birthday".equals(type)) {
result = birthday;
}else if("age".equals(type)){
result = age;
}else if("sex".equals(type)){
if("F".equals(sexCode)){
sexCode = "2";
}else if ("M".equals(sexCode)) {
sexCode = "1";
}
result = sexCode;
}
return result;
}
/**
* 根据属性,获取get方法
* @param ob 对象
* @param name 属性名
* @return
* @throws Exception
*/
public static Object getGetMethod(Object ob , String name){
try {
Method[] m = ob.getClass().getMethods();
for(int i = 0;i < m.length;i++){
if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
return m[i].invoke(ob);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 根据属性,拿到set方法,并把值set到对象中
* @param obj 对象
* @param filedName 对象的class
* @param value 需要设置值得属性
*/
public static void setValue(Object obj,String filedName,Object value){
filedName = getString(filedName);
String methodName = "set" + filedName.substring(0,1).toUpperCase()+filedName.substring(1);
try{
Method method = obj.getClass().getDeclaredMethod(methodName, new Class[]{obj.getClass().getDeclaredField(filedName).getType()});
method.invoke(obj, new Object[]{getClassTypeValue(obj.getClass().getDeclaredField(filedName).getType(), value)});
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 通过class类型获取获取对应类型的值
* @param typeClass class类型
* @param value 值
* @return Object
*/
private static Object getClassTypeValue(Class<?> typeClass, Object value){
if(typeClass == int.class || value instanceof Integer){
if(null == value){
return 0;
}
return value;
}else if(typeClass == short.class){
if(null == value){
return 0;
}
return value;
}else if(typeClass == byte.class){
if(null == value){
return 0;
}
return value;
}else if(typeClass == double.class){
if(null == value){
return 0;
}
return value;
}else if(typeClass == long.class){
if(null == value){
return 0;
}
return value;
}else if(typeClass == String.class){
if(null == value){
return "";
}
return value;
}else if(typeClass == boolean.class){
if(null == value){
return true;
}
return value;
}else if(typeClass == BigDecimal.class){
if(null == value){
return new BigDecimal(0);
}
return new BigDecimal(value+"");
}else {
return typeClass.cast(value);
}
}
/**
* 处理字符串 如: abc_dex ---> abcDex
* @param str
* @return
*/
public static String getString(String str){
if(str != null){
while(str.contains("_") || str.contains(" ")){
if(str.contains("_")){
int i = str.indexOf("_");
String str1 = str.charAt(i+1)+"";
str = str.substring(0, i)+str1.toUpperCase()+str.substring(i+2);
}
if(str.contains(" ")){
int i = str.indexOf(" ");
String str1 = str.charAt(i+1)+"";
str = str.substring(0, i)+str1.toUpperCase()+str.substring(i+2);
}
}
}
if(str.endsWith("?") || str.endsWith("#")){
str = str.substring(0, str.length()-2);
}
return str;
}
/**
* 姓名如果是英文,就全部转换为大写
* @param name
* @return
*/
public static String enNameToUp(String name) {
String rightName = name;
Pattern p = Pattern.compile(".*[a-zA-z].*");
Matcher m = p.matcher(name);
boolean isValid = m.matches();
if(isValid){
rightName = name.toUpperCase();
}
return rightName;
}
public static String getUTF8StringFromGBKString(String gbkStr) {
try {
return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new InternalError();
}
}
public static byte[] getUTF8BytesFromGBKString(String gbkStr) {
int n = gbkStr.length();
byte[] utfBytes = new byte[3 * n];
int k = 0;
for (int i = 0; i < n; i++) {
int m = gbkStr.charAt(i);
if (m < 128 && m >= 0) {
utfBytes[k++] = (byte) m;
continue;
}
utfBytes[k++] = (byte) (0xe0 | (m >> 12));
utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));
utfBytes[k++] = (byte) (0x80 | (m & 0x3f));
}
if (k < utfBytes.length) {
byte[] tmp = new byte[k];
System.arraycopy(utfBytes, 0, tmp, 0, k);
return tmp;
}
return utfBytes;
}
/**
* 获取最惠比平台的错误信息
* @param insurerId 保险公司id,微信999,支付宝998,非第三方平台传null
* @param errorCode 错误编码,如果传入insurerId,则为第三方的错误编码,相反,则为自定义的错误编码
* @param insurerErrorMessage 错误信息,为第三方平台的错误信息,非第三方平台,传null
* @param paramStr 参数信息
* @return list.get(0)=errorCode;list.get(1)=errorMessage
*/
public static List<String> getZHBErrorInfo(Long insurerId,String errorCode,String insurerErrorMessage,String[] paramStr){
List<String> errorList = new ArrayList<String>();
String zhbErrorCode = null;
String zhbErrorMessage = null;
if(!isNullOrBlank(errorCode)){
if(insurerId == null){
zhbErrorCode = errorCode;
}else {
zhbErrorCode = createZHBErrorCode(insurerId,errorCode);
}
zhbErrorMessage = readProperties("errortest.properties",zhbErrorCode);
if(!isNullOrBlank(zhbErrorMessage)){
if(zhbErrorMessage.contains("}{")){
String[] errorMessageInfoArr = zhbErrorMessage.split("\\}\\{");
zhbErrorMessage = errorMessageInfoArr[0];
}
if(paramStr.length > 0){
for (int i = 0; i < paramStr.length; i++) {
zhbErrorMessage = zhbErrorMessage.replace("{"+i+"}", paramStr[i]);
}
}
}else{
if(!isNullOrBlank(insurerErrorMessage)){
zhbErrorMessage = "错误信息待配置!!!!";
writeProperties("errortest.properties",zhbErrorCode,zhbErrorMessage+"}{"+insurerErrorMessage);
}
}
}else{
try {
throw new Exception("errorCode不能为空!");
} catch (Exception e) {
e.printStackTrace();
}
}
errorList.add(zhbErrorCode);
errorList.add(zhbErrorMessage);
return errorList;
}
/**
* 写properties文件
* @param fileName
* @param key
* @param value
* @throws Exception
*/
public static void writeProperties(String fileName,String key,String value){
FileInputStream fis = null;
String file = null;
BufferedReader bf = null;
FileOutputStream fos = null;
BufferedWriter bw = null;
Properties properties = new Properties();
if(!isNullOrBlank(fileName)){
file = "src\\main\\resources\\"+fileName;
try {
fis = new FileInputStream(file);
bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
properties.load(bf);
properties.setProperty(key, value);
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
properties.store(bw, "update");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bf != null){
try {
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!= null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
try {
throw new Exception("Properties的文件名不能为空!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取properties文件
* @param fileName 文件名 (目录为{src\main\resources\fileName})
* @param zhbErrorCode properties的key值
* @return properties的value值
* @throws Exception
*/
public static String readProperties(String fileName,String zhbErrorCode){
String errorMessage = null;
FileInputStream fis = null;
Properties properties = null;
BufferedReader bf= null;
String file = null;
if(!isNullOrBlank(fileName)){
file = "src\\main\\resources\\"+fileName;
try {
properties = new Properties();
fis = new FileInputStream(file);
bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
properties.load(bf);
errorMessage = properties.getProperty(zhbErrorCode);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(properties != null){
properties = null;
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bf != null){
try {
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
try {
throw new Exception("Properties的文件名不能为空!");
} catch (Exception e) {
e.printStackTrace();
}
}
return errorMessage;
}
/**
* 生成最惠比的errorCode
* @param insurerId 保险公司id,微信999,支付宝998
* @param insurerCode 保险公errorCode
* @return 最惠比平台 errorCode
*/
private static String createZHBErrorCode(Long insurerId, String insurerCode) {
String zhbErrorCode = null;
if (insurerId<10) {
zhbErrorCode = "900"+insurerId;
}else if(insurerId<100){
zhbErrorCode = "90"+insurerId;
}else {
zhbErrorCode = "9"+insurerId;
}
zhbErrorCode = zhbErrorCode+insurerCode;
return zhbErrorCode;
}
/**
* 给手机加密
* @param mobileNo
* @return
*/
public static String encryptMobile(String mobileNo) {
if (!isNullOrBlank(mobileNo) && mobileNo.length() == 11) {
mobileNo = mobileNo.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
}
return mobileNo;
}
/**
* 用GET方法打开URL
* @param url
* @return
*/
/*
public static String transactionGet(String url) {
String result = null;
CloseableHttpClient client = null;
CloseableHttpResponse response = null;
try {
*//**
* 创建HttpClient对象
*//*
client = HttpClients.createDefault();
*//**
* 创建URIBuilder
*//*
URIBuilder uriBuilder = new URIBuilder(url);
*//**
* 设置参数
*//*
// List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
// nameValuePairList.add(new BasicNameValuePair("param1", "value1"));
// uriBuilder.addParameters(nameValuePairList);
*//**
* 创建HttpGet
*//*
HttpGet httpGet = new HttpGet(uriBuilder.build());
*//**
* 设置请求头部编码
*//*
httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
*//**
* 设置返回编码
*//*
httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
*//**
* 请求服务
*//*
response = client.execute(httpGet);
*//**
* 获取响应吗
*//*
int statusCode = response.getStatusLine().getStatusCode();
if(200 == statusCode){
*//**
* 获取返回对象
*//*
HttpEntity entity = response.getEntity();
*//**
* 通过EntityUitls获取返回内容
*//*
result = EntityUtils.toString(entity,"UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
*/
}
package com.yd.util;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
* 加密/解密工具
* @author ershuai
* @date 2017年4月18日 上午11:27:36
*/
public class DESUtils {
private final byte[] DESIV = new byte[] { 0x12, 0x34, 0x56, 120, (byte) 0x90, (byte) 0xab, (byte) 0xcd, (byte) 0xef };// 向量
private AlgorithmParameterSpec iv = null;// 加密算法的参数接口
private Key key = null;
private String charset = "utf-8";
/**
* 初始化
* @param deSkey 密钥
* @return
* @throws Exception
*/
public DESUtils(String deSkey, String charset) throws Exception {
if (charset!=null && !charset.isEmpty())
{
this.charset = charset;
}
DESKeySpec keySpec = new DESKeySpec(deSkey.getBytes(this.charset));// 设置密钥参数
iv = new IvParameterSpec(DESIV);// 设置向量
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
key = keyFactory.generateSecret(keySpec);// 得到密钥对象
}
/**
* 加密
* @author ershuai
* @date 2017年4月19日 上午9:40:53
* @param data
* @return
* @throws Exception
*/
public String encode(String data) throws Exception {
Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(pasByte);
}
/**
* 解密
* @author ershuai
* @date 2017年4月19日 上午9:41:01
* @param data
* @return
* @throws Exception
*/
public String decode(String data) throws Exception {
Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
deCipher.init(Cipher.DECRYPT_MODE, key, iv);
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
return new String(pasByte, "UTF-8");
}
}
package com.yd.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @description
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return SpringContextUtil.applicationContext;
}
// 传入线程中
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> t) {
return SpringContextUtil.applicationContext.getBean(t);
}
// 国际化使用
public static String getMessage(String key) {
String message = null;
try {
Locale locale = new Locale("zh", "CN");
message = applicationContext.getMessage(key, null,locale);
} catch (Exception e) {
e.getMessage();
}
return message;
}
/// 获取当前环境
public static String getActiveProfile() {
return applicationContext.getEnvironment().getActiveProfiles()[0];
}
/**
* 是否为本地环境
* @return
*/
public static boolean isLocal() {
return "LOCAL".equals(getEnvironmentName());
}
/**
* 是否为DEV环境
* @return
*/
public static boolean isDev() {
return "DEV".equals(getEnvironmentName());
}
/**
* 是否为STAGE环境
* @return
*/
public static boolean isStage() {
return "STAGE".equals(getEnvironmentName());
}
/**
* 是否为PROD环境
* @return
*/
public static boolean isProd() {
return "PROD".equals(getEnvironmentName());
}
/**
* 获取环境名字
*/
public static String getEnvironmentName() {
return getActiveProfile().toUpperCase();
}
}
package com.yd.util.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yd.api.result.JsonResult;
import com.yd.util.auth.service.AuthorizeService;
import com.yd.util.auth.vo.CheckTokenRequestVO;
import com.yd.util.auth.vo.CheckTokenResponseVO;
import com.yd.util.auth.vo.ObtainTokenRequestVO;
import com.yd.util.auth.vo.ObtainTokenResponseVO;
import com.yd.util.config.ZHBErrorConfig;
@RestController
@RequestMapping("/authorize")
public class AuthorizeController {
@Autowired
private AuthorizeService authorizeService;
/**
* 获取TOKEN接口
* @param requestVO
* @return
*/
@RequestMapping("/obtainToken")
public Object obtainToken(@RequestBody ObtainTokenRequestVO requestVO){
JsonResult result = new JsonResult();
ObtainTokenResponseVO responseVO = authorizeService.obtainToken(requestVO);
result.addResult(responseVO);
result.setData(responseVO);
return result;
}
/**
* 校验TOKEN接口
* @param requestVO
* @return
*/
@RequestMapping("/checkToken")
public Object checkToken(@RequestBody CheckTokenRequestVO requestVO){
JsonResult result = new JsonResult();
CheckTokenResponseVO responseVO = authorizeService.checkToken(requestVO);
result.addResult(responseVO);
result.setData(responseVO);
return result;
}
@RequestMapping("/checkavailable")
public Object checkAvailable(){
JsonResult result = new JsonResult();
result.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
result.setSuccess(true);
return result;
}
}
package com.yd.util.auth.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// import org.apache.commons.httpclient.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import com.yd.util.CommonUtil;
import com.yd.util.auth.setting.AudienceSetting;
import com.yd.util.auth.setting.JwtTokenUtil;
/**
* jwt过滤器
* @author
* zuihuibi intercept all request from client, check whether token is there,verify the token is valid.
*/
public class HttpZuihuibiAuthorizeFilter implements Filter{
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private AudienceSetting audienceSetting;
private static final String BY_PASS_ALL = "TEST";
@Override
public void destroy() {}
/**
* 过滤器,对客户请求过滤,验证
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException{
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
String requestUri = httpRequest.getRequestURI();
boolean isDoFilter = false;
//这里通过判断请求的方法,判断此次是否是预检请求,如果是,立即返回一个204状态吗,标示,允许跨域;预检后,正式请求,这个方法参数就是我们设置的post了
if ("OPTIONS".equals(httpRequest.getMethod())){
//HttpStatus.SC_NO_CONTENT = 204
httpResponse.setStatus(HttpStatus.NO_CONTENT.value());
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");//当判定为预检请求后,设定允许请求的方法
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Token, X-Authorization"); //当判定为预检请求后,设定允许请求的头部类型
httpResponse.addHeader("Access-Control-Max-Age", "1");
chain.doFilter(request, response);
return;
}
String byPass = audienceSetting.bypass;
if(!CommonUtil.isNullOrBlank(byPass)){
if(byPass.contains(BY_PASS_ALL)){//bypass配置为TEST时所有方法都放过
isDoFilter = true;
}else{
if(byPass.contains(requestUri)){//完整路径匹配
isDoFilter = true;
}else{//按照“,”拆分后逐个模糊匹配
String[] arr = byPass.split(",");
for(String item : arr){
if(item.startsWith("*") && item.endsWith("*")){//以*开头且以*结尾
if(requestUri.contains(item.replace("*", ""))){
isDoFilter = true;
break;
}
}else if(item.startsWith("*")){//仅以*开头
if(requestUri.endsWith(item.replace("*", ""))){
isDoFilter = true;
break;
}
}else if(item.endsWith("*")){//仅以*结尾
if(requestUri.startsWith(item.replace("*", ""))){
isDoFilter = true;
break;
}
}
}//for arr
}//!byPass.contains(requestUri)
}//not BY_PASS_ALL
}//byPass != null
if (isDoFilter){
chain.doFilter(request, response);
return;
}
//其他的URL请求,先获取head中的token,进行验证即可
int issuerLength = audienceSetting.issuer.length();
String token = httpRequest.getHeader(audienceSetting.header);
/*
if (!isIpValid("ProdCheckIP") || !isIpValid("StageCheckIP")) {
if("autogeneral".equals(token)){
chain.doFilter(request, response);
return;
}
}*/
if(!CommonUtil.isNullOrBlank(token) && token.length() > issuerLength){
String headStr = token.substring(0, issuerLength).toLowerCase();
if (headStr.compareTo(audienceSetting.issuer) == 0){
token = token.substring(issuerLength, token.length());
//token格式合法并且没有失效
if (jwtTokenUtil.validateToken(token) && !jwtTokenUtil.isTokenExpired(token)){
chain.doFilter(request, response);
return;
}
}
}
//验证失败,返回错误提示
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType("application/json; charset=utf-8");
httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
String responseJson = "{"
+"\n \"success\": false,"
+"\n \"errorCode\": \"T001\","
+"\n \"message\": \"请联系管理员,开通API访问账号!\""
+"\n}";
httpResponse.getWriter().write(responseJson);
return;
}
@Override
public void init(FilterConfig arg0) throws ServletException {}
/* @SuppressWarnings("unused")
private boolean isIpValid(String configType){
boolean ipValid = false;
String currentIP = CommonUtil.currentIP();
String validIPS = systemConfigService.getSingleConfigValue(configType);
if(!CommonUtil.isNullOrBlank(currentIP) && !CommonUtil.isNullOrBlank(validIPS)){
String[] arr = validIPS.split("\\|");
for(String item : arr){
if(currentIP.contains(item)){
ipValid = true;
break;
}
}
}
return ipValid;
}*/
}
package com.yd.util.auth.service;
import com.yd.util.auth.vo.CheckTokenRequestVO;
import com.yd.util.auth.vo.CheckTokenResponseVO;
import com.yd.util.auth.vo.ObtainTokenRequestVO;
import com.yd.util.auth.vo.ObtainTokenResponseVO;
public interface AuthorizeService {
ObtainTokenResponseVO obtainToken(ObtainTokenRequestVO requestVO);
CheckTokenResponseVO checkToken(CheckTokenRequestVO requestVO);
}
package com.yd.util.auth.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yd.api.result.CommonResult;
import com.yd.util.CommonUtil;
import com.yd.util.auth.setting.AudienceSetting;
import com.yd.util.auth.setting.JwtTokenUtil;
import com.yd.util.auth.vo.CheckTokenRequestVO;
import com.yd.util.auth.vo.CheckTokenResponseVO;
import com.yd.util.auth.vo.ObtainTokenRequestVO;
import com.yd.util.auth.vo.ObtainTokenResponseVO;
import com.yd.util.config.ZHBErrorConfig;
@Service("authorizeService")
public class AuthorizeServiceImpl implements AuthorizeService {
@Autowired
private JwtTokenUtil jwtTokenUtil;
@Autowired
private AudienceSetting audienceSetting;
@Override
public ObtainTokenResponseVO obtainToken(ObtainTokenRequestVO requestVO) {
ObtainTokenResponseVO responseVO = new ObtainTokenResponseVO();
//入参校验
if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getTicket())){
responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("600001")));
return responseVO;
}
//获取TOKEN
String token = jwtTokenUtil.generateToken(requestVO.getTicket());
responseVO.setToken(token);
responseVO.setCommonResult(new CommonResult(true,ZHBErrorConfig.getErrorInfo("800000")));
return responseVO;
}
@Override
public CheckTokenResponseVO checkToken(CheckTokenRequestVO requestVO) {
boolean success = true;
String message = ZHBErrorConfig.getErrorInfo("600000");
CheckTokenResponseVO responseVO = new CheckTokenResponseVO();
if(requestVO == null || CommonUtil.isNullOrBlank(requestVO.getToken())){
responseVO.setCommonResult(new CommonResult(false,ZHBErrorConfig.getErrorInfo("600001")));
return responseVO;
}
String token = requestVO.getToken();
if(token.startsWith(audienceSetting.issuer)){
token = token.substring(audienceSetting.issuer.length()+1);
}
boolean isTokenValid = jwtTokenUtil.validateToken(token);
boolean isTokenExpired = jwtTokenUtil.isTokenExpired(token);
if(isTokenExpired){
success = false;
message =ZHBErrorConfig.getErrorInfo("810001");
}else if(isTokenValid){
String ticket = requestVO.getTicket();
if(!CommonUtil.isNullOrBlank(ticket)){
boolean valid = jwtTokenUtil.validateToken(token, ticket);
if(!valid){
success = false;
message = ZHBErrorConfig.getErrorInfo("810001");
}
}
}else{
success = false;
message = ZHBErrorConfig.getErrorInfo("810001");
}
responseVO.setCommonResult(new CommonResult(success,message));
return responseVO;
}
}
package com.yd.util.auth.setting;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* jwt安全验证设置 head tag,seal封条,过期时间,发行,bypass
* @author Simon Cheng
*/
@Service
public class AudienceSetting {
@Value("${jwt.header}")
public String header;
@Value("${jwt.seal}")
public String seal;
@Value("${jwt.expiration}")
public Long expiration;
@Value("${jwt.issuer}")
public String issuer;
@Value("${jwt.bypass}")
public String bypass;
@Value("${enable.datasecurity}")
public String datasecurity;
@Value("${prod.checkavailable}")
public String checkProdAvailable;
}
package com.yd.util.auth.setting;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
/**
* jwt 工具类
* @author
*/
@Service
public class JwtTokenUtil {
private static final String CLAIM_KEY_SUBJECT = "sub";
// private static final String CLAIM_KEY_ISSURE = "iss";
// private static final String CLAIM_KEY_AUDIENCE = "aud";
private static final String CLAIM_KEY_CREATED = "created";
// private static final String CLAIM_KEY_BIRTHDAY = "birthDay";
// private static final String CLAIM_KEY_ADDRESS = "address";
@Autowired
private AudienceSetting audienceSetting;
/**
* 从token中获取subject
* @param token
* @return
*/
public String getSubjectFromToken(String token) {
String subject = null;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
subject = claims.getSubject();
}
}
return subject;
}
/**
* 获取创建时间
* @param token
* @return
*/
public Date getCreatedDateFromToken(String token) {
Date created = null ;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
created = new Date((Long) claims.get(CLAIM_KEY_CREATED));
}
}
return created;
}
/**
* 获取过期时间
* @param token
* @return
*/
public Date getExpirationDateFromToken(String token){
Date expiration = null;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
expiration = claims.getExpiration();
}
}
return expiration;
}
/**
* check token是否过期
* @param token
* @return
*/
public Boolean isTokenExpired(String token) {
boolean result = false;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("EXPIRED".equals(resultCode)){
result = true;
}else if("SUCCESS".equals(resultCode)){
Date expiration = getExpirationDateFromToken(token);
if(expiration != null){
result = expiration.before(new Date());
}
}
return result;
}
/**
* 检查是否可以被刷新
* @param token
* @param lastPasswordReset
* @return
*/
public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
//如果过期则不可以刷新
if(isTokenExpired(token)){
return false;
}
Date created = getCreatedDateFromToken(token);
if(created == null){
return false;
}
//如果token是在上次密码重置前生成则不可以刷新
if(lastPasswordReset != null && created.before(lastPasswordReset)){
return false;
}
return true;
}
/**
* 刷新token
* @param token
* @return
*/
public String refreshToken(String token) {
String refreshedToken = null ;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("SUCCESS".equals(resultCode)){
Object obj = map.get("claims");
if(obj != null){
Claims claims = (Claims)obj;
claims.put(CLAIM_KEY_CREATED, new Date());
refreshedToken = generateToken(claims);
}
}
return refreshedToken;
}
/**
* 根据ticket验证token有效
* @param ticket
* @param user
* @return
*/
public Boolean validateToken(String token, String ticket) {
boolean result = false;
final String subject = getSubjectFromToken(token);
if(subject == null){
return false;
}
if(!isTokenExpired(token)){
if(ticket != null && subject.equals(ticket)){
result = true;
}
}
return result;
}
/**
* 判断token是否有效(主要是格式是否有效)
* @param token
* @return
*/
public Boolean validateToken(String token) {
boolean result = true;
Map<String,Object> map = getClaimsFromToken(token);
String resultCode = (String)map.get("resultCode");
if("INVALID".equals(resultCode)){
result = false;
}
return result;
}
/**
* 生成过期时间
* @return
*/
private Date generateExpirationDate() {
Date expirationDate = new Date(System.currentTimeMillis() + audienceSetting.expiration * 1000);
return expirationDate;
}
/**
* 根据ticket生成token
* @param ticket
* @return
*/
public String generateToken(String ticket){
String token = null;
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_SUBJECT, ticket);
claims.put(CLAIM_KEY_CREATED, new Date());
token = generateToken(claims);
token = audienceSetting.issuer + " " + token;
return token;
}
/**
* 根据Map 生成token串
* @param Map<String, Object>claims
* @return
*/
private String generateToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, audienceSetting.seal)
.compact();
}
/**
* 根据token获取Claims,申明内容
* @param token
* @return
*/
private Map<String,Object> getClaimsFromToken(String token){
Map<String,Object> map = new HashMap<String,Object>();
String resultCode = "SUCCESS";
Claims claims = null;
try {
JwtParser jwtParser = Jwts.parser().setSigningKey(audienceSetting.seal);
Jws<Claims> jwsClaims = jwtParser.parseClaimsJws(token);
claims = jwsClaims.getBody();
}catch(ExpiredJwtException e){
resultCode = "EXPIRED";
}catch(UnsupportedJwtException|MalformedJwtException|SignatureException|IllegalArgumentException e){
resultCode = "INVALID";
}catch(Exception e){
resultCode = "INVALID";
}
map.put("resultCode", resultCode);
map.put("claims", claims);
return map;
}
}
package com.yd.util.auth.vo;
public class CheckTokenRequestVO {
private String token;
private String ticket;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
}
package com.yd.util.auth.vo;
import com.yd.api.result.CommonResult;
public class CheckTokenResponseVO {
private CommonResult commonResult;
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
}
package com.yd.util.auth.vo;
public class ObtainTokenRequestVO {
private String ticket;
private String ipAddress;
private String loginId;
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
}
package com.yd.util.auth.vo;
import com.yd.api.result.CommonResult;
public class ObtainTokenResponseVO {
private String token;
private CommonResult commonResult;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
}
package com.yd.util.config;
/**
* Register security zuihuibi filter
*/
import javax.servlet.Filter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.CharacterEncodingFilter;
import com.yd.util.auth.filter.HttpZuihuibiAuthorizeFilter;
@Configuration
public class HttpZuihuibiAuthorizeConfig {
@Bean
public Filter AuthFilter() {
return new HttpZuihuibiAuthorizeFilter();
}
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
filter.setForceRequestEncoding(true);
filter.setForceResponseEncoding(true);
return filter;
}
}
package com.yd.util.config;
import javax.servlet.Filter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class SpringMvcConfig {
/**
* 解决同源策略问题的filter
* @return
*/
@Bean
public Filter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
package com.yd.util.config;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;
import com.yd.Application;
import com.yd.util.SpringContextUtil;
public class ZHBErrorConfig {
/**
* 获取最惠比平台的错误信息
* @param zhbErrorCode 错误编码,如果传入insurerId,则为第三方的错误编码,相反,则为自定义的错误编码
* @return zhbErrorMessage
*/
public static String getErrorInfo(String zhbErrorCode){
return SpringContextUtil.getMessage(zhbErrorCode);
}
/**
* 获取最惠比平台的错误信息
* @param zhbErrorCode 错误编码,如果传入insurerId,则为第三方的错误编码,相反,则为自定义的错误编码
* @param params 参数信息
* @return zhbErrorMessage
*/
public static String getErrorInfo(String zhbErrorCode,String[] params){
String zhbErrorMessage = null;
zhbErrorMessage = SpringContextUtil.getMessage(zhbErrorCode);
if(!isNullOrBlank(zhbErrorMessage)){
if(params != null && params.length > 0){
for (int i = 0; i < params.length; i++) {
zhbErrorMessage = zhbErrorMessage.replace("{"+i+"}", params[i]);
}
}
}
return zhbErrorMessage;
}
/**
* 获取最惠比平台的错误信息
* @param zhbErrorCode 错误编码,如果传入insurerId,则为第三方的错误编码,相反,则为自定义的错误编码
* @param insurerErrorMessage 错误信息,为第三方平台的错误信息,
* @return zhbErrorMessage
*/
public static String getErrorInfo(Long insurerId,String insurerCode,String insurerErrorMessage){
String zhbErrorMessage = null;
String zhbErrorCode = null;
if(insurerId != null && !isNullOrBlank(insurerCode)){
zhbErrorCode = getErrorCode(insurerId, insurerCode);
zhbErrorMessage = SpringContextUtil.getMessage(zhbErrorCode);
if(!isNullOrBlank(zhbErrorMessage)){
if("EQUAL".equals(zhbErrorMessage)){
return insurerErrorMessage;
}else if(zhbErrorMessage.contains("}{")){//保险公司错误
String[] errorMessageInfoArr = zhbErrorMessage.split("\\}\\{");
zhbErrorMessage = errorMessageInfoArr[1];
}
}else{
return insurerErrorMessage;
}
}
return zhbErrorMessage;
}
/**
* 获取最惠比平台的错误信息
* @param zhbErrorCode 错误编码,如果传入insurerId,则为第三方的错误编码,相反,则为自定义的错误编码
* @param insurerErrorMessage 错误信息,为第三方平台的错误信息,非第三方平台,传null
* @param params 参数信息
* @return zhbErrorMessage
*/
public static String getErrorInfo(String zhbErrorCode,String insurerErrorMessage,String[] params){
String zhbErrorMessage = null;
if(!isNullOrBlank(zhbErrorCode)){
zhbErrorMessage = readProperties("zhb-error.properties",zhbErrorCode);
if(!isNullOrBlank(zhbErrorMessage)){
if(zhbErrorMessage.contains("}{")){//保险公司错误
String[] errorMessageInfoArr = zhbErrorMessage.split("\\}\\{");
zhbErrorMessage = errorMessageInfoArr[1];
if("EQUAL".equals(zhbErrorMessage)){
zhbErrorMessage = insurerErrorMessage;
}
}else{//平台内部错误
if(params != null && params.length > 0){
for (int i = 0; i < params.length; i++) {
zhbErrorMessage = zhbErrorMessage.replace("{"+i+"}", params[i]);
}
}
}
}else{
if(!isNullOrBlank(insurerErrorMessage)){
zhbErrorMessage = ZHBErrorConfig.getErrorInfo("810036");
// writeProperties("zhb-error.properties",zhbErrorCode,insurerErrorMessage+"}{"+zhbErrorMessage);
}
}
}else{
try {
String [] paramss = {"zhbErrorCode"};
throw new Exception(ZHBErrorConfig.getErrorInfo("610001", paramss));
} catch (Exception e) {
e.printStackTrace();
}
}
return zhbErrorMessage;
}
/**
* 写properties文件
* @param fileName
* @param key
* @param value
* @throws Exception
*/
@SuppressWarnings("unused")
private static void writeProperties(String fileName,String key,String value){
FileInputStream fis = null;
String file = null;
BufferedReader bf = null;
FileOutputStream fos = null;
BufferedWriter bw = null;
Properties properties = new Properties();
if(!isNullOrBlank(fileName)){
file = Application.class.getClassLoader().getResource(fileName).getPath();
try {
fis = new FileInputStream(file);
bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
properties.load(bf);
properties.setProperty(key, value);
fos = new FileOutputStream(file);
bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
properties.store(bw, "update");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(bw != null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bf != null){
try {
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!= null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
try {
String [] params = {"fileName"};
throw new Exception(ZHBErrorConfig.getErrorInfo("610001", params));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取properties文件
* @param fileName 文件名 (目录为{src\main\resources\fileName})
* @param zhbErrorCode properties的key值
* @return properties的value值
* @throws Exception
*/
private static String readProperties(String fileName,String zhbErrorCode){
String errorMessage = null;
FileInputStream fis = null;
Properties properties = null;
BufferedReader bf= null;
String file = null;
if(!isNullOrBlank(fileName)){
file = Application.class.getClassLoader().getResource(fileName).getPath();
try {
properties = new Properties();
fis = new FileInputStream(file);
bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
properties.load(bf);
errorMessage = properties.getProperty(zhbErrorCode);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(properties != null){
properties = null;
}
if(fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bf != null){
try {
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
try {
String [] params = {"fileName"};
throw new Exception(ZHBErrorConfig.getErrorInfo("610001", params));
} catch (Exception e) {
e.printStackTrace();
}
}
return errorMessage;
}
/**
* 生成最惠比的errorCode
* @param insurerId 保险公司id,微信999,支付宝998
* @param insurerCode 保险公errorCode
* @return 最惠比平台 errorCode
*/
private static String getErrorCode(Long insurerId, String insurerCode) {
String zhbErrorCode = null;
if (insurerId<10) {
zhbErrorCode = "900"+insurerId;
}else if(insurerId<100){
zhbErrorCode = "90"+insurerId;
}else {
zhbErrorCode = "9"+insurerId;
}
zhbErrorCode = zhbErrorCode+insurerCode;
return zhbErrorCode;
}
private static boolean isNullOrBlank(String source){
boolean result = false;
if(source == null){
result = true;
}else if("".equals(source.trim())){
result = true;
}
return result ;
}
}
package com.yd.util.deshandler;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import com.yd.util.DESUtils;
public class DESTypeHandler extends BaseTypeHandler<Object> {
private static final String secret_property_key = "encryption.key";
private static final String secret_property_enabled_key = "encryption.enabled";
private static final Properties properties = new Properties();
private static String sensitivekey = null;
private static Boolean sensitiveenabled = false;
static {
try {
properties.load(DESTypeHandler.class.getClassLoader()
.getResourceAsStream("persistence.properties"));
} catch (Exception e) {
properties.put(secret_property_key, "12345678");
properties.put(secret_property_enabled_key, "false");
}
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType)
throws SQLException {
sensitiveenabled = Boolean.valueOf(properties.get(secret_property_enabled_key).toString());
if (sensitiveenabled==false)
{
return;
}
if (parameter == null)
{
return;
}
sensitivekey = (String)properties.get(secret_property_key);
DESUtils des;
String result = null;
try {
des = new DESUtils(sensitivekey, "utf-8");
if (parameter != null)
{
result = des.encode((String)parameter);
}
ps.setString(i, result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
String columnValue = rs.getString(columnName);
String result = decode(columnValue);
return result;
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String columnValue = rs.getString(columnIndex);
String result = decode(columnValue);
return result;
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
String columnValue = cs.getString(columnIndex);
String result = decode(columnValue);
return result;
}
private String decode(String columnValue) {
sensitiveenabled = Boolean.valueOf(properties.get(secret_property_enabled_key).toString());
if (sensitiveenabled==false)
{
return columnValue;
}
if (columnValue == null)
{
return null;
}
sensitivekey = (String)properties.get(secret_property_key);
DESUtils des;
String result = null;
try {
des = new DESUtils(sensitivekey, "utf-8");
if (columnValue != null)
{
result = des.decode(columnValue);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
package com.yd.util.exception;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yd.api.result.JsonResult;
import com.yd.util.CommonUtil;
/***
* 统一异常处理
* @author fan
*
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
*
* @param req
* @param ex
* @return
* @throws Exception
*/
@ExceptionHandler(value=Exception.class)
public JsonResult handler(HttpServletRequest req,Exception ex) throws Exception{
logger.error("request url is:"+req.getRequestURL()+" \n "+CommonUtil.parseExceptionStack(ex));//ex.getMessage()
JsonResult result=new JsonResult();
result.setSuccess(false);
result.setMessage("system error"+ex.getMessage());
//TODO log
return result;
}
}
package com.yd.util.exception;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Component;
@Component
public class MessageLocaleManager {
private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@Autowired
private MessageSource messageSource;
/**
* 国际化
* @param result
* @return
*/
public String getMessage(String code, Object[] params) {
String message = "";
try {
//Locale locale = LocaleContextHolder.getLocale();
Locale locale = new Locale("zh","CN");//中文,中国
message = messageSource.getMessage(code, params, locale);
} catch (Exception e) {
logger.error("parse message error! ", e);
}
finally
{
}
return message;
}
}
package com.yd.util.intercept.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.yd.util.intercept.commons.DataSourceKey;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {
DataSourceKey dataSourceKey() default DataSourceKey.DB_MASTER;
}
package com.yd.util.intercept.commons;
public enum DataSourceKey {
DB_MASTER,
DB_EGOLDEN
}
package com.yd.util.intercept.commons;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import com.yd.util.intercept.annotation.TargetDataSource;
@Aspect
@Order(-1)
@Component
public class DynamicDataSourceAspect {
private static final Logger LOG = Logger.getLogger(DynamicDataSourceAspect.class);
@Pointcut("execution(* com.yd.dataccess.service.*.*(..))")
public void pointCut() {
}
/**
* 执行方法前更换数据源
*
* @param joinPoint 切点
* @param targetDataSource 动态数据源
*/
@Before("@annotation(targetDataSource)")
public void doBefore(JoinPoint joinPoint, TargetDataSource targetDataSource) {
DataSourceKey dataSourceKey = targetDataSource.dataSourceKey();
if (dataSourceKey == DataSourceKey.DB_MASTER) {
LOG.info(String.format("设置数据源为 %s", DataSourceKey.DB_MASTER));
DynamicDataSourceContextHolder.set(DataSourceKey.DB_MASTER);
} else if (dataSourceKey == DataSourceKey.DB_EGOLDEN) {
LOG.info(String.format("使用默认数据源 %s", DataSourceKey.DB_EGOLDEN));
DynamicDataSourceContextHolder.set(DataSourceKey.DB_EGOLDEN);
}
}
/**
* 执行方法后清除数据源设置
*
* @param joinPoint 切点
* @param targetDataSource 动态数据源
*/
@After("@annotation(targetDataSource)")
public void doAfter(JoinPoint joinPoint, TargetDataSource targetDataSource) {
LOG.info(String.format("当前数据源 %s 执行清理方法", targetDataSource.dataSourceKey()));
DynamicDataSourceContextHolder.clear();
}
@Before(value = "pointCut()")
public void doBeforeWithSlave(JoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取当前切点方法对象
Method method = methodSignature.getMethod();
if (method.getDeclaringClass().isInterface()) {//判断是否为借口方法
try {
//获取实际类型的方法对象
method = joinPoint.getTarget().getClass()
.getDeclaredMethod(joinPoint.getSignature().getName(), method.getParameterTypes());
} catch (NoSuchMethodException e) {
LOG.error("方法不存在!", e);
}
}
if (null == method.getAnnotation(TargetDataSource.class)) {
DynamicDataSourceContextHolder.setSlave();
}
}
}
package com.yd.util.intercept.commons;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
public class DynamicDataSourceContextHolder {
private static final Logger LOG = Logger.getLogger(DynamicDataSourceContextHolder.class);
private static final ThreadLocal<DataSourceKey> currentDatesource = new ThreadLocal<>();
/**
* 清除当前数据源
*/
public static void clear() {
currentDatesource.remove();
}
/**
* 获取当前使用的数据源
*
* @return 当前使用数据源的ID
*/
public static DataSourceKey get() {
return currentDatesource.get();
}
/**
* 设置当前使用的数据源
*
* @param value 需要设置的数据源ID
*/
public static void set(DataSourceKey value) {
currentDatesource.set(value);
}
/**
* 设置从从库读取数据
*/
public static void setSlave() {
if (RandomUtils.nextInt(0, 2) > 0) {
DynamicDataSourceContextHolder.set(DataSourceKey.DB_MASTER);
} else {
DynamicDataSourceContextHolder.set(DataSourceKey.DB_EGOLDEN);
}
}
}
package com.yd.util.intercept.commons;
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
private static final Logger LOG = Logger.getLogger(DynamicRoutingDataSource.class);
@Override
protected Object determineCurrentLookupKey() {
LOG.info("当前数据源:{}"+ DynamicDataSourceContextHolder.get());
return DynamicDataSourceContextHolder.get();
}
}
package com.yd.util.intercept.configuration;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.yd.util.intercept.commons.DataSourceKey;
import com.yd.util.intercept.commons.DynamicRoutingDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@MapperScan(basePackages = "com.yd.dataccess.mapper.*")
@Configuration
public class DynamicDataSourceConfiguration {
@Bean
@ConfigurationProperties(prefix = "multiple.datasource.master")
public DataSource dbMaster() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties(prefix = "multiple.datasource.egolden")
public DataSource dbEGolden() {
return DruidDataSourceBuilder.create().build();
}
/**
* 核心动态数据源
*
* @return 数据源实例
*/
@Bean
public DataSource dynamicDataSource() {
DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
dataSource.setDefaultTargetDataSource(dbMaster());
Map<Object, Object> dataSourceMap = new HashMap<>(4);
dataSourceMap.put(DataSourceKey.DB_MASTER, dbMaster());
dataSourceMap.put(DataSourceKey.DB_EGOLDEN, dbEGolden());
dataSource.setTargetDataSources(dataSourceMap);
return dataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dynamicDataSource());
//此处设置为了解决找不到mapper文件的问题
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
return new SqlSessionTemplate(sqlSessionFactory());
}
/**
* 事务管理
*
* @return 事务管理实例
*/
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(dynamicDataSource());
}
}
package com.yd.util.page;
import java.util.ArrayList;
import java.util.List;
public class PaginationInfo {
private Integer number;
private Integer size;
private Long totalElements;
private Integer totalPages;
private Integer numberOfElements;
private List<SortInfo> sortInfo;
private String noLimitFlag;
public void addOrderInfo(String isASC, String orderProperty){
if(this.sortInfo == null){
this.sortInfo = new ArrayList<SortInfo>();
}
SortInfo orderInfoItem = new SortInfo(isASC,orderProperty);
this.sortInfo.add(orderInfoItem);
}
public void addOrderInfo(SortInfo orderInfoItem){
if(this.sortInfo == null){
this.sortInfo = new ArrayList<SortInfo>();
}
this.sortInfo.add(orderInfoItem);
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public Long getTotalElements() {
return totalElements;
}
public void setTotalElements(Long totalElements) {
this.totalElements = totalElements;
}
public Integer getTotalPages() {
return totalPages;
}
public void setTotalPages(Integer totalPages) {
this.totalPages = totalPages;
}
public Integer getNumberOfElements() {
return numberOfElements;
}
public void setNumberOfElements(Integer numberOfElements) {
this.numberOfElements = numberOfElements;
}
public List<SortInfo> getSortInfo() {
return sortInfo;
}
public void setSortInfo(List<SortInfo> sortInfo) {
this.sortInfo = sortInfo;
}
public String getNoLimitFlag() {
return noLimitFlag;
}
public void setNoLimitFlag(String noLimitFlag) {
this.noLimitFlag = noLimitFlag;
}
}
package com.yd.util.page;
public class SortInfo{
private String orderProperty;
private String isASC;
public SortInfo() {
super();
}
public SortInfo(String orderProperty) {
super();
this.orderProperty = orderProperty;
}
public SortInfo(String isASC,String orderProperty) {
super();
this.isASC = isASC;
this.orderProperty = orderProperty;
}
public String getOrderProperty() {
return orderProperty;
}
public void setOrderProperty(String orderProperty) {
this.orderProperty = orderProperty;
}
public String getIsASC() {
return isASC;
}
public void setIsASC(String isASC) {
this.isASC = isASC;
}
}
\ No newline at end of file
server.port=9998
server.context-path=/ydapi
#mybatis mapping文件位置配置
mybatis.mapper-locations=classpath:mapper/**/*.xml
######datasource######
###spring boot自动配置单数据源###
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://139.224.139.2:13307/ajb?useUnicode=true&characterEncoding=utf8&useSSL=false&useAffectedRows=true
spring.datasource.username=devdbuser
spring.datasource.password=devdbpass1
###手动配置多数据源###
#master
multiple.datasource.master.driver-class-name=com.mysql.jdbc.Driver
multiple.datasource.master.url=jdbc:mysql://139.224.139.2:13307/ajb?useUnicode=true&characterEncoding=utf8&useSSL=false&useAffectedRows=true
multiple.datasource.master.username=devdbuser
multiple.datasource.master.password=devdbpass1
#egolden
multiple.datasource.egolden.driver-class-name=com.mysql.jdbc.Driver
multiple.datasource.egolden.url=jdbc:MySql://139.224.94.140:13307/ydinsurance?characterEncoding=UTF-8&useSSL=false&useAffectedRows=true
multiple.datasource.egolden.username=stageuser
multiple.datasource.egolden.password=AG@#$mstage234
#pagehelper分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
mybatis.type-handlers-package=com.yd.util.deshandler
# mybatis.check-config-location=检查配置文件是否存在
# 设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE
mybatis.executor-type=SIMPLE
# JWT 单位秒钟
jwt.header:X-Authorization
jwt.seal:zhb123!@#
jwt.expiration:86400
jwt.issuer:zuihuibi
jwt.bypass:TEST
#jwt.bypass:/api/user/login,
#存量数据接口开关
enable.datasecurity:false
#存量数据接口开关
prod.checkavailable:
\ No newline at end of file
server.port=9998
server.context-path=/ydapi
#mybatis mapping文件位置配置
mybatis.mapper-locations=classpath:mapper/**/*.xml
######datasource######
###spring boot自动配置单数据源###
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://139.224.139.2:13307/ajb?useUnicode=true&characterEncoding=utf8&useSSL=false&useAffectedRows=true
spring.datasource.username=devdbuser
spring.datasource.password=devdbpass1
###手动配置多数据源###
#master
multiple.datasource.master.driver-class-name=com.mysql.jdbc.Driver
multiple.datasource.master.url=jdbc:mysql://139.224.139.2:13307/ajb?useUnicode=true&characterEncoding=utf8&useSSL=false&useAffectedRows=true
multiple.datasource.master.username=devdbuser
multiple.datasource.master.password=devdbpass1
#egolden
multiple.datasource.egolden.driver-class-name=com.mysql.jdbc.Driver
multiple.datasource.egolden.url=jdbc:MySql://139.224.94.140:13307/ydinsurance?characterEncoding=UTF-8&useSSL=false&useAffectedRows=true
multiple.datasource.egolden.username=stageuser
multiple.datasource.egolden.password=AG@#$mstage234
#pagehelper分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
mybatis.type-handlers-package=com.yd.util.deshandler
# mybatis.check-config-location=检查配置文件是否存在
# 设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE
mybatis.executor-type=SIMPLE
# JWT 单位秒钟
jwt.header:X-Authorization
jwt.seal:zhb123!@#
jwt.expiration:86400
jwt.issuer:zuihuibi
jwt.bypass:TEST
#jwt.bypass:/api/user/login,
#存量数据接口开关
enable.datasecurity:false
#存量数据接口开关
prod.checkavailable:
\ No newline at end of file
spring.profiles.active=local
spring.session.store-type=none
spring.http.multipart.maxFileSize = 10Mb
spring.http.multipart.maxRequestSize=100Mb
#编码格式
#spring.http.encoding.force=true
#spring.http.encoding.charset=GBK
#spring.http.encoding.enabled=true
#server.tomcat.uri-encoding=GBK
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8
\ No newline at end of file
/*
Navicat Premium Data Transfer
Source Server : 本地库
Source Server Type : MySQL
Source Server Version : 50720
Source Host : localhost:3306
Source Schema : db_master
Target Server Type : MySQL
Target Server Version : 50720
File Encoding : 65001
Date: 19/01/2018 18:38:11
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`create_time` datetime(0) NOT NULL,
`update_time` datetime(0) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1002 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1000, 'admin', 'admin', '2018-01-19 16:43:38', '2018-01-19 16:43:40');
INSERT INTO `user` VALUES (1001, 'rocliu', 'rocliu', '2018-01-19 16:43:58', '2018-01-19 16:44:00');
SET FOREIGN_KEY_CHECKS = 1;
/*
Navicat Premium Data Transfer
Source Server : 本地库
Source Server Type : MySQL
Source Server Version : 50720
Source Host : localhost:3306
Source Schema : db_other
Target Server Type : MySQL
Target Server Version : 50720
File Encoding : 65001
Date: 19/01/2018 18:38:18
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user_info
-- ----------------------------
DROP TABLE IF EXISTS `user_info`;
CREATE TABLE `user_info` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1001 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_info
-- ----------------------------
INSERT INTO `user_info` VALUES (1000, 'admin', 'admin@apedad.com');
SET FOREIGN_KEY_CHECKS = 1;
## 暂时不用更新2019/10/10-water ##
######################参数信息校验########################
600000=参数检验成功!
600001=参数信息不能为空!
600002=参数校验失败!
800000=执行成功!
##系统提示信息
810001=token无效或者错误!
\ No newline at end of file
## 暂时不用更新2019/10/10-water ##
######################参数信息校验########################
600000=参数检验成功!
600001=参数信息不能为空!
600002=参数校验失败!
800000=执行成功!
##系统提示信息
810001=token无效或者错误!
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<configuration><!-- 使用spring profile 来管理多环节log文件 -->
<springProfile name="local"> <!-- local 环境 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><!-- 控制台输出 -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern><!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"><!-- 按照每天生成日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>opt/log/yd/yd-api.%d{yyyy-MM-dd}.log</FileNamePattern><!--日志文件输出的文件名 -->
<MaxHistory>30</MaxHistory><!--日志文件保留天数 -->
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern><!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"><!--日志文件最大的大小 -->
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<appender name="accurateQuotationFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>opt/log/yd/accurate.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory><!--日志文件保留天数 -->
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
</springProfile>
<springProfile name="dev,stage"> <!-- dev stage 环境 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>/opt/log/yd/yd-api.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<appender name="accurateQuotationFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>/opt/log/yd/accurate.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory><!--日志文件保留天数 -->
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
</springProfile>
<springProfile name="prod"><!-- prod环境 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>/opt/log/yd/yd-api.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<appender name="accurateQuotationFILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>/opt/log/yd/accurate.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory><!--日志文件保留天数 -->
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}- %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
</springProfile>
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<logger name="accurateQuotation" level="WARN" additivity="false">
<appender-ref ref="STDOUT" />
<appender-ref ref="accurateQuotationFILE"/>
</logger>
</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="com.yd.dataccess.mapper.commission.CommissionEGoldenMapper">
<resultMap id="base_result_mapegolden" type="com.yd.dataccess.entity.commission.CommissionEGolden">
<result column="SAL_MST_MOBILE" property="login"/>
<result column="SAL_MST_NAME" property="name"/>
<result column="MON_TS_TAXABLE_AMOUNT" property="premium"/>
<result column="MON_TS_Period" property="incomeYearmonth"/>
</resultMap>
<select id="listSalesCommissionfromEGolden" parameterType="java.lang.String" resultMap="base_result_mapegolden">
SELECT s.SAL_MST_MOBILE,s.SAL_MST_NAME,
m.MON_TS_Period,m.MON_TS_TAXABLE_AMOUNT
FROM sal001 s
INNER JOIN cmon019 m ON trim(s.SAL_MST_ID) = trim(m.FK_SAL_MST_ID)
WHERE s.SAL_MST_MOBILE = #{login}
</select>
</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="com.yd.dataccess.mapper.commission.CommissionMapper">
<resultMap id="base_result_map" type="com.yd.dataccess.entity.commission.Commission">
<result column="login" property="login"/>
<result column="name" property="name"/>
<result column="referral_amount" property="premium"/>
<result column="incomeYearmonth" property="incomeYearmonth"/>
</resultMap>
<select id="queryCommissionByLogin" parameterType="java.lang.String" resultMap="base_result_map">
SELECT
c.login,
c.name,
sum(f.referral_amount) AS referral_amount,
f.order_date as incomeYearmonth
FROM
ag_acl_customer c INNER JOIN ag_acl_customer_fortune f
on c.id = f.customer_id
WHERE c.login = #{login}
</select>
</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="com.yd.dataccess.mapper.customer.CustomerMapper">
<resultMap id="base_result_map" type="com.yd.dataccess.entity.customer.Customer">
<result column="login" property="login"/>
<result column="password" property="password"/>
<result column="mobile_no" property="mobileNo" typeHandler="com.yd.util.deshandler.DESTypeHandler"/>
<result column="created_at" property="createdAt"/>
<result column="updated_at" property="updatedAt"/>
</resultMap>
<sql id="base_sql">
login,password,mobile_no,created_at,updated_at
</sql>
<select id="listAllCustomer" resultMap="base_result_map">
SELECT
<include refid="base_sql"/>
FROM ag_acl_customer limit 100
</select>
<select id="queryByPage" resultMap="base_result_map">
SELECT
<include refid="base_sql"/>
FROM ag_acl_customer
</select>
</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="com.yd.dataccess.mapper.mkt.MktAnnouncementMapper">
<resultMap id="base_result_map" type="com.yd.dataccess.entity.mkt.MktAnnouncement">
<id property="id" column="id"/>
<result column="insurerId" property="insurerId"/>
<result column="insurer_branch_id" property="insurerBranchId"/>
<result column="title" property="title"/>
<result column="content" property="content"/>
<result column="announcement_type" property="announcementType"/>
<result column="announcement_at" property="announcementAt"/>
<result column="seq" property="seq"/>
<result column="is_active" property="isActive"/>
<result column="created_at" property="createdAt"/>
<result column="created_by" property="createdBy"/>
</resultMap>
<insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.yd.dataccess.entity.mkt.MktAnnouncement">
INSERT INTO yd_mkt_announcement
(insurer_id,insurer_branch_id,title,content,announcement_type,announcement_at,seq,is_active,created_at,created_by)
VALUES
(#{insurerId},#{insurerBranchId},#{title},#{content},#{announcementType},#{announcementAt},#{seq},#{isActive},#{createdAt},#{createdBy})
</insert>
<update id="update" parameterType="com.yd.dataccess.entity.mkt.MktAnnouncement">
UPDATE yd_mkt_announcement SET
<if test="insurerId != null">insurer_id = #{insurerId},</if>
<if test="insurerBranchId != null">insurer_branch_id = #{insurerBranchId},</if>
<if test="title != null">title = #{title},</if>
<if test="content != null">content = #{content},</if>
<if test="announcementType != null">announcement_type = #{announcementType},</if>
<if test="announcementAt != null">announcement_at = #{announcementAt},</if>
<if test="seq != null">seq = #{seq},</if>
<if test="isActive != null">is_active = #{isActive},</if>
<if test="createdAt != null">created_at = #{createdAt},</if>
<if test="createdBy != null">created_by = #{createdBy},</if>
id = #{id}
WHERE id = #{id}
</update>
<delete id="delete">
delete from yd_mkt_announcement
WHERE announcement_type = #{announcementType}
</delete>
<sql id="base_sql">
id,insurer_id,insurer_branch_id,title,content,announcement_type,announcement_at,seq,is_active,created_at,created_by
</sql>
<select id="findByType" resultMap="base_result_map">
SELECT
<include refid="base_sql"/>
FROM yd_mkt_announcement t WHERE t.announcement_type = #{announcementType} and t.is_active = 1 order by t.seq asc , t.created_at desc
</select>
<select id="findByIsActive" resultMap="base_result_map">
SELECT
<include refid="base_sql"/>
From yd_mkt_announcement t WHERE t.is_active = #{isActive} order by t.seq asc , t.created_at desc
</select>
<select id="findByIsActiveAndAnnouncementAtBefore" resultMap="base_result_map">
SELECT
<include refid="base_sql"/>
From yd_mkt_announcement t WHERE 1= 1
and t.is_active = #{isActive}
and t.announcement_at &lt;= #{announcementAt} order by t.seq asc , t.created_at desc
</select>
<select id="findBySeqAndIsActive" resultMap="base_result_map">
SELECT
<include refid="base_sql"/>
From yd_mkt_announcement t WHERE t.is_active = #{isActive} and t.seq = #{seq} order by t.announcement_at desc ;
</select>
</mapper>
\ No newline at end of file
encryption.key=12345678
encryption.enabled=true
####stage
#encryption.key=87654321
#encryption.enabled=true
Markdown is supported
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