import org.apache.log4j.Logger;
public class DateUtil {
final static Logger logger = Logger.getLogger(DateUtil.class);
private final static String[] months = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", };
public final static Date parseComplicateDate(String str) {
try{
if (StringUtil.isNullOrEmpty(str))
return null;
String[] strs = str.split(" ");
int nYear = Integer.parseInt(strs[5]);
int nMonth = 0;
for (int i = 0; i < months.length; i++) {
if (months[i].equals(strs[1])) {
nMonth = i;
break;
}
}
int nDay = Integer.parseInt(strs[2]);
String strTime = strs[3];
String[] strTimes = strTime.split(":");
int nHour = Integer.parseInt(strTimes[0]);
int nMinute = Integer.parseInt(strTimes[1]);
int nSecond = Integer.parseInt(strTimes[2]);
Calendar cal = new GregorianCalendar(nYear, nMonth, nDay, nHour,
nMinute, nSecond);
Date aDate = cal.getTime();
return aDate;
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
/**
* 返回用戶指定日期的前或后n天的字符串 正數為向后n天,負數相反
* @param date
* @param day
* @return
* @throws ParseException
*/
public static String getNumToDate(String date,int day) throws ParseException
{
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
c.setTime(sdf1.parse(date));
c.add( Calendar.DAY_OF_MONTH, day );
return sdf1.format(c.getTime());
}
public final static Date getYyyyMmDdHhMmss(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
String[] strs = str.split(" ");
String[] strDays = strs[0].split("-");
int nYear = Integer.parseInt(strDays[0]);
int nMonth = Integer.parseInt(strDays[1]);
int nDay = Integer.parseInt(strDays[2]);
String[] strTimes = strs[1].split(":");
int nHour = Integer.parseInt(strTimes[0]);
int nMinute = Integer.parseInt(strTimes[1]);
int nSecond = Integer.parseInt(strTimes[2]);
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, nHour,
nMinute, nSecond);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
/**
* 返回與指定日期n個月的日期
* @param date
* @param day
* @return
* @throws ParseException
*/
public static Date getMonthToDate(Date date,int month) throws ParseException
{
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DAY_OF_MONTH, -month*30);
return c.getTime();
}
/**
* 返回用戶指定日期的前或后n天的字符串 正數為向后n天,負數相反
* @param date
* @param day
* @return
* @throws ParseException
*/
public static Date getNumToDate(Date date,int day) throws ParseException
{
Calendar c = Calendar.getInstance();
c.add( Calendar.DAY_OF_MONTH, day );
return c.getTime();
}
/**
* 比較兩個日期
* @param date1
* @param date2
* @return
*/
public static boolean compareDate(Date date1,Date date2)
{
Calendar c = Calendar.getInstance();
c.setTime(date1);
c.add( Calendar.DAY_OF_MONTH, 1 );
return c.getTime().getTime()>date2.getTime()?true:false;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
System.out.println(autoCommit());
}
public final static Date getYyyyMmDdHhMm(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
String[] strs = str.split(" ");
String[] strDays = strs[0].split("-");
int nYear = Integer.parseInt(strDays[0]);
int nMonth = Integer.parseInt(strDays[1]);
int nDay = Integer.parseInt(strDays[2]);
String[] strTimes = strs[1].split(":");
int nHour = Integer.parseInt(strTimes[0]);
int nMinute = Integer.parseInt(strTimes[1]);
int nSecond = 0;
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, nHour,
nMinute, nSecond);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static Date getYyyyMmDdHhMmSsFlexible(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
String[] strs = str.split(" ");
String[] strDays = strs[0].split("-");
int nYear = Integer.parseInt(strDays[0]);
int nMonth = Integer.parseInt(strDays[1]);
int nDay = Integer.parseInt(strDays[2]);
int nHour = 0;
int nMinute = 0;
int nSecond = 0;
if (strs.length > 1){
String[] strTimes = strs[1].split(":");
if (strTimes.length > 1)
nHour = Integer.parseInt(strTimes[0]);
if (strTimes.length > 2)
nMinute = Integer.parseInt(strTimes[1]);
if (strTimes.length > 3)
nSecond = Integer.parseInt(strTimes[2]);
}
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, nHour,
nMinute, nSecond);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static Date getHhMm(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
String[] strTimes = str.split(":");
int nHour = Integer.parseInt(strTimes[0]);
int nMinute = Integer.parseInt(strTimes[1]);
int nSecond = 0;
Calendar cal = new GregorianCalendar(nHour,
nMinute, nSecond);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static Date getYyyyMmDd(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
// String[] strs = str.split(" ");
String[] strDays = str.split("-");
int nYear = Integer.parseInt(strDays[0]);
int nMonth = Integer.parseInt(strDays[1]);
int nDay = Integer.parseInt(strDays[2]);
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
0, 0);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static Date getYyyyMmDdNotHyphenated(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
// String[] strs = str.split(" ");
int nYear = Integer.parseInt(str.substring(0, 4));
int nMonth = Integer.parseInt(str.substring(4, 6));
int nDay = Integer.parseInt(str.substring(6, 8));
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
0, 0);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static Date getYyMmDd(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
// String[] strs = str.split(" ");
String[] strDays = str.split("-");
int nYear = Integer.parseInt(strDays[0]);
nYear += 2000;
int nMonth = Integer.parseInt(strDays[1]);
int nDay = Integer.parseInt(strDays[2]);
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
0, 0);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static Date getYyMmDdNotHyphenated(String str) {
if (StringUtil.isNullOrEmpty(str))
return null;
try{
int nYear = Integer.parseInt(str.substring(0,2));
nYear += 2000;
int nMonth = Integer.parseInt(str.substring(2,4));
int nDay = Integer.parseInt(str.substring(4,6));
Calendar cal = new GregorianCalendar(nYear, nMonth-1, nDay, 0,
0, 0);
return cal.getTime();
}
catch (ArrayIndexOutOfBoundsException e){
logger.warn("", e);
return null;
}
catch (NumberFormatException e){
logger.warn("", e);
return null;
}
catch (Exception e){
logger.warn("", e);
return null;
}
}
public final static String toYyMmdd(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
StringBuilder sb = new StringBuilder();
int nYear = cal.get(Calendar.YEAR);
nYear = nYear % 100;
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
if (nYear < 10)
sb.append('0');
sb.append(nYear);
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
if (nDay < 10)
sb.append('0');
sb.append(nDay);
return sb.toString();
}
public final static String toHyphenatedYyMmdd(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
StringBuilder sb = new StringBuilder();
int nYear = cal.get(Calendar.YEAR);
nYear = nYear % 100;
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
if (nYear < 10)
sb.append('0');
sb.append(nYear);
sb.append('-');
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
sb.append('-');
if (nDay < 10)
sb.append('0');
sb.append(nDay);
return sb.toString();
}
public final static String toYyyyMmdd(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
StringBuilder sb = new StringBuilder();
int nYear = cal.get(Calendar.YEAR);
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
sb.append(nYear);
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
if (nDay < 10)
sb.append('0');
sb.append(nDay);
return sb.toString();
}
public final static String toHyphenatedYyyyMmdd(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
int nYear = cal.get(Calendar.YEAR);
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
StringBuilder sb = new StringBuilder();
sb.append(nYear);
sb.append('-');
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
sb.append('-');
if (nDay < 10)
sb.append('0');
sb.append(nDay);
return sb.toString();
}
public final static String toHyphenatedYyyyMmDdHhMm(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
int nYear = cal.get(Calendar.YEAR);
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
int nHour = cal.get(Calendar.HOUR_OF_DAY);
int nMinute = cal.get(Calendar.MINUTE);
StringBuilder sb = new StringBuilder();
sb.append(nYear);
sb.append('-');
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
sb.append('-');
if (nDay < 10)
sb.append('0');
sb.append(nDay);
sb.append(" ");
if (nHour < 10)
sb.append('0');
sb.append(nHour);
sb.append(":");
if (nMinute < 10)
sb.append('0');
sb.append(nMinute);
return sb.toString();
}
public final static String toHyphenatedYyyyMmDdHhMmSsFlexible(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
int nYear = cal.get(Calendar.YEAR);
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
int nHour = cal.get(Calendar.HOUR_OF_DAY);
int nMinute = cal.get(Calendar.MINUTE);
int nSecond = cal.get(Calendar.SECOND);
StringBuilder sb = new StringBuilder();
sb.append(nYear);
sb.append('-');
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
sb.append('-');
if (nDay < 10)
sb.append('0');
sb.append(nDay);
if (nHour > 0 ||
nMinute > 0 ||
nSecond > 0){
sb.append(" ");
if (nHour < 10)
sb.append('0');
sb.append(nHour);
sb.append(":");
if (nMinute < 10)
sb.append('0');
sb.append(nMinute);
if (nSecond > 0){
sb.append(":");
if (nSecond < 10)
sb.append('0');
sb.append(nSecond);
}
}
return sb.toString();
}
public final static String toYyyyMmddHHmm(Date aDate){
if (aDate== null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
int nYear = cal.get(Calendar.YEAR);
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
int nHour = cal.get(Calendar.HOUR_OF_DAY);
int nMinute = cal.get(Calendar.MINUTE);
StringBuilder sb = new StringBuilder();
sb.append(nYear);
sb.append("-");
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
sb.append("-");
if (nDay < 10)
sb.append('0');
sb.append(nDay);
sb.append(" ");
if (nHour < 10)
sb.append('0');
sb.append(nHour);
sb.append(":");
if (nMinute < 10)
sb.append('0');
sb.append(nMinute);
return sb.toString();
}
public final static String toYyyymmddHhmmss(Date aDate){
if (aDate == null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
int nYear = cal.get(Calendar.YEAR);
int nMonth = cal.get(Calendar.MONTH);
nMonth++;
int nDay = cal.get(Calendar.DAY_OF_MONTH);
int nHour = cal.get(Calendar.HOUR_OF_DAY);
int nMInute = cal.get(Calendar.MINUTE);
int nSeconf= cal.get(Calendar.SECOND);
StringBuilder sb = new StringBuilder();
sb.append(nYear);
sb.append('-');
if (nMonth < 10)
sb.append('0');
sb.append(nMonth);
sb.append('-');
if (nDay < 10)
sb.append('0');
sb.append(nDay);
sb.append(' ');
if (nHour < 10)
sb.append('0');
sb.append(nHour);
sb.append(':');
if (nMInute < 10)
sb.append('0');
sb.append(nMInute);
sb.append(':');
if (nSeconf < 10)
sb.append('0');
sb.append(nSeconf);
return sb.toString();
}
public final static String toHHmm(Date aDate){
if (aDate== null)
return "";
Calendar cal = new GregorianCalendar();
cal.setTime(aDate);
int nHour = cal.get(Calendar.HOUR_OF_DAY);
int nMinute = cal.get(Calendar.MINUTE);
StringBuilder sb = new StringBuilder();
if (nHour < 10)
sb.append('0');
sb.append(nHour);
sb.append(":");
if (nMinute < 10)
sb.append('0');
sb.append(nMinute);
return sb.toString();
}
public static java.sql.Timestamp toTimestamp (Date theDate){
if (theDate== null)
return null;
return new Timestamp (theDate.getTime());
}
/**
* 判斷當前的時小數是否在23:00---08:00內,如果在就自動commit到供應商下單
* @return
*/
public static boolean autoCommit(){
SimpleDateFormat sdf=new SimpleDateFormat("HH");
Date d=new Date();
String str=sdf.format(d);
int num=Integer.parseInt(str) ;
return (num>=23 || num<8)?true:false;
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package com.lvyou.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
public class StringUtil {
static Logger logger = Logger.getLogger (StringUtil.class);
public final static String ENCODING = "GBK";
private static String[] strArray = new String[] { "a", "b", "c", "d", "e",
"f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E",
"F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4",
"5", "6", "7", "8", "9", "!", "@", "#", "$", "%", "^", "&", "(",
")" };
public static boolean isNullOrEmpty (String str){
if (str== null ||
"".equals(str))
return true;
else
return false;
}
public static String nullToEmpty(String str){
if (str== null)
return "";
return str;
}
public static String getEscaped(String str ){
try {
return URLEncoder.encode(str, ENCODING);
} catch (UnsupportedEncodingException e) {
logger.warn("", e);
}
return "";
}
/**
* 校驗手機號碼
* @param num
* @return
*
*/
public static boolean IsMobileCode(String code)
{
String Code = "[0-9]{3}";
if(isNumeric(code,Code))
return true;
else
return false;
}
public static boolean IsMobileNum1(String num){
String HK="[0-9]{8}";
String MainLand="[0-9]{11}";
// String USA="";
if( (isNumeric(num,HK)==true || isNumeric(num,MainLand)==true ) && num.matches("^(13|15|18)\\d{9}$"))
return true;
else
return false;
}
public static boolean IsMoblieNum(String num)
{
String Code="[0-9]{1,4}";
String HK="[0-9]{8}";
String MainLand="[0-9]{11}";
if(num.trim()!=null || num.trim()!="")
{
String[] str=num.split(" ");
if(isNumeric(str[0],Code))
{
if((isNumeric(str[1],HK)==true || isNumeric(str[1],MainLand)==true) && str[1].matches("^(13|15|18)\\d{6,9}$"))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
public static boolean isNumeric(String str,String where )
{
Pattern pattern = Pattern.compile(where);
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() )
{
return false;
}
return true;
}
/**
* 生成唯一字符串
* @param length 需要長度
* @param symbol 是否允許出現特殊字符 -- !@ $%^&*()
* @return
*/
public static String getUniqueString(int length, boolean symbol)
throws Exception {
Random ran = new Random();
int num = ran.nextInt(61);
String returnString = "";
String str = "";
for (int i = 0; i < length;) {
if (symbol)
num = ran.nextInt(70);
else
num = ran.nextInt(61);
str = strArray[num];
if (!(returnString.indexOf(str) >= 0)) {
returnString += str;
i++;
}
}
return returnString;
}
public static void main(String[] args) {
System.out.println(IsMoblieNum("568 ga1345")?"對的":"錯的");
//
// String str="16020895785";
// System.out.println(str.matches("^(13|15|18)\\d{9}$"));
}
}
package com.icicle.goldenfly.web.admin.busAdmin;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.easymvc.ActionException;
import com.easymvc.ReturnableCommand;
import com.easymvc.annotation.In;
import com.easymvc.annotation.Out;
import com.easymvc.dispatcher.CommandDispatcher;
import com.easymvc.dispatcher.Dispatcher;
import com.easymvc.dispatcher.DownloadDispatcher;
import com.icicle.framework.member.client.criteria.OrderBy;
import com.icicle.framework.member.client.criteria.SetRestriction;
import com.icicle.framework.member.client.interfaces.ContentManager;
import com.icicle.framework.order.client.enums.BusTicketSource;
import com.icicle.framework.order.client.models.BusTicketPrice;
import com.icicle.goldenfly.bus.client.criteria.BusTicketPriceCriteria;
import com.icicle.goldenfly.member.client.ClientManagerFactory;
import com.icicle.goldenfly.web.order.report.ExportBusTicketPriceUtil;
/**
* 下載 車票價格數據 command
* @author James pu
*
*/
public class BusPriceExportCommand extends ReturnableCommand{
/**
*
*/
private static final long serialVersionUID = 1705270988040058854L;
private static final Logger logger = Logger.getLogger(BusPriceExportCommand.class);
@In(init=false)
private String source;//來源
@In(init=false)
private String fromBusStop;//起始站點
@In(init=false)
private String toBusStop;//目的站點
private InputStream exportStream;//輸出流
/**
* 接口管理類
*/
private ContentManager manager;
public BusPriceExportCommand(){
manager = ClientManagerFactory.getInstance().getContentManager();
}
@Override
protected String execute2() throws ActionException {
try{
//查詢條件
BusTicketPriceCriteria criteria=new BusTicketPriceCriteria();
if(StringUtils.isNotEmpty(source)){
criteria.setSource(SetRestriction.in(BusTicketSource.valueOf(source)));
}
if(StringUtils.isNotEmpty(fromBusStop)){
criteria.setFromBusStop(fromBusStop);
}
if(StringUtils.isNotEmpty(toBusStop)){
criteria.setToBusStop(toBusStop);
}
criteria.setOrderBys(OrderBy.desc("id"));
List<BusTicketPrice> tmpList=manager.findBusTicketPrice(criteria);
//生成輸出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExportBusTicketPriceUtil exprotUtil=new ExportBusTicketPriceUtil();
try{
exprotUtil.initWorkbook(out);
exprotUtil.createSheet("車票價格", 1);
exprotUtil.writeDetails(tmpList);
}
finally{
exprotUtil.closeWorkbook();
out.close();
}
exportStream = new ByteArrayInputStream(out.toByteArray());
return SUCCESS;
}
catch(Exception e){
logger.error(Calendar.getInstance().getTime()+":BusPriceExportCommand.execute2={}", e);
this.addErrorMessage("下載時發生異常." + e.toString());
return FAILURE;
}
}
@Override
public Dispatcher getMapping2(String result) {
if(SUCCESS.equals(result)){
return new DownloadDispatcher(exportStream, "application/ms-excel", "busPriceImportFormat.xls");
}else{
return new CommandDispatcher(this.getReturnCommand(), this.getOutputMessage());
}
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getFromBusStop() {
return fromBusStop;
}
public void setFromBusStop(String fromBusStop) {
this.fromBusStop = fromBusStop;
}
public String getToBusStop() {
return toBusStop;
}
public void setToBusStop(String toBusStop) {
this.toBusStop = toBusStop;
}
}
3.ExportBusTicketPriceUtil
package com.icicle.goldenfly.web.order.report;
import java.io.IOException;
import java.util.List;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.lang.StringUtils;
import com.icicle.framework.member.client.MemberClientUtils;
import com.icicle.framework.order.client.models.BusTicketPrice;
/**
* 處理車票價格導出數據 為Excel格式
* @author James pu
*
*/
public class ExportBusTicketPriceUtil extends JxlExcelExportFacade<BusTicketPrice>{
public void writeDetails(List<BusTicketPrice> busTicketPriceList)
throws RowsExceededException, WriteException, IOException {
this.writeHeader("來源[CNHKBUS-中港通,TRANSISLAND-環島通]", "出發站點代碼","目的站點代碼", "單程 賣價",
"雙程 賣價", "單程 買入價", "雙程 買入價", "單程 門市價","雙程 門市價","票數量","有效期","備注[50字內]"
);
for(BusTicketPrice busTicketPrice :busTicketPriceList){
writeContents(busTicketPrice);
}
}
@Override
protected JxlFormatAndValue[] getContents(BusTicketPrice busTicketPrice, Object... parameters) {
JxlFormatAndValue[] fnvs = new JxlFormatAndValue[15];
// 來源[CNHKBUS-中港通,TRANSISLAND-環島通]
fnvs[0] = new JxlFormatAndValue(
StringUtils.defaultString(busTicketPrice.getSource().name()), CELL_FORMAT_DEFAULT);
// 出發站點代碼
fnvs[1] = new JxlFormatAndValue(
StringUtils.defaultString(busTicketPrice.getFromBusStop()), CELL_FORMAT_DEFAULT);
// 目的站點代碼
fnvs[2] = new JxlFormatAndValue(
StringUtils.defaultString(busTicketPrice.getToBusStop()), CELL_FORMAT_DEFAULT);
// 單程 賣價
fnvs[3] = new JxlFormatAndValue(
MemberClientUtils.getFirstNotNull(busTicketPrice.getPriceOfSingle(),0.0), CELL_FORMAT_DEFAULT_DECIMAL);
// 雙程 賣價
fnvs[4] = new JxlFormatAndValue(MemberClientUtils.getFirstNotNull(busTicketPrice.getPriceOfRound(),0.0), CELL_FORMAT_DEFAULT_DECIMAL);
// 單程 買入價
fnvs[5] = new JxlFormatAndValue(
MemberClientUtils.getFirstNotNull(busTicketPrice.getDealPriceOfSingle(),0.0), CELL_FORMAT_DEFAULT_DECIMAL);
// 雙程 買入價
fnvs[6] = new JxlFormatAndValue(MemberClientUtils.getFirstNotNull(busTicketPrice.getDealPriceOfRound(),0.0), CELL_FORMAT_DEFAULT_DECIMAL);
// 單程 門市價
fnvs[7] = new JxlFormatAndValue(
MemberClientUtils.getFirstNotNull(busTicketPrice.getRealPriceOfSingle(),0.0), CELL_FORMAT_DEFAULT_DECIMAL);
//雙程 門市價
fnvs[8] = new JxlFormatAndValue(MemberClientUtils.getFirstNotNull(busTicketPrice.getRealPriceOfRound(),0.0), CELL_FORMAT_DEFAULT_DECIMAL);
// 票數量
fnvs[9] = new JxlFormatAndValue(MemberClientUtils.getFirstNotNull(busTicketPrice.getRestNumber(), 0), CELL_FORMAT_DEFAULT_INTEGER);
//有效期
fnvs[10] = new JxlFormatAndValue(busTicketPrice.getExpiredDate(), CELL_FORMAT_DEFAULT_DATE);
//備注[50字內]
fnvs[11] = new JxlFormatAndValue(StringUtils.defaultString(busTicketPrice.getRemark()), CELL_FORMAT_DEFAULT);
return fnvs;
}
}
4.JxlExcelExportFacade
package com.icicle.goldenfly.web.order.report;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Colour;
import jxl.write.DateFormat;
import jxl.write.Label;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.CellValue;
import jxl.write.biff.RowsExceededException;
/**
* make list of maps to xls output stream.
*/
public abstract class JxlExcelExportFacade<T> {
protected final NumberFormat NUMBER_FORMAT = new NumberFormat("#,##0.00");
protected final NumberFormat INTEGER_FORMAT = new NumberFormat("#,##0");
protected final DateFormat DATETIME_FORMAT = new DateFormat("yyyy-MM-dd HH:mm:ss");
protected final DateFormat DATE_FORMAT = new DateFormat("yyyy-MM-dd");
protected WritableFont FONT;
protected WritableFont BOLD_FONT;
protected WritableCellFormat CELL_FORMAT_HEADER;
protected WritableCellFormat CELL_FORMAT_DEFAULT;
protected WritableCellFormat CELL_FORMAT_DEFAULT_INTEGER;
protected WritableCellFormat CELL_FORMAT_DEFAULT_DECIMAL;
protected WritableCellFormat CELL_FORMAT_DEFAULT_DATETIME;
protected WritableCellFormat CELL_FORMAT_DEFAULT_DATE;
protected WritableCellFormat CELL_FORMAT_HIGHLIGHT;
protected WritableCellFormat CELL_FORMAT_HIGHLIGHT_INTEGER;
protected WritableCellFormat CELL_FORMAT_HIGHLIGHT_DECIMAL;
protected WritableCellFormat CELL_FORMAT_HIGHLIGHT_DATETIME;
protected WritableCellFormat CELL_FORMAT_HIGHLIGHT_DATE;
private int xIndex;
private int yIndex;
protected WritableWorkbook workbook;
protected Map<String, WritableSheet> sheetsMap = new LinkedHashMap<String, WritableSheet>();
protected Map<String, WritableCellFormat> cacheMap = new LinkedHashMap<String, WritableCellFormat>();
protected WritableSheet sheet;
protected static final Logger logger = Logger.getLogger(JxlExcelExportFacade.class);
public JxlExcelExportFacade() {
try {
FONT = new WritableFont(WritableFont.TAHOMA);
BOLD_FONT = new WritableFont(FONT);
BOLD_FONT.setBoldStyle(WritableFont.BOLD);
CELL_FORMAT_DEFAULT = new WritableCellFormat(FONT);
CELL_FORMAT_DEFAULT_INTEGER = new WritableCellFormat(FONT, INTEGER_FORMAT);
CELL_FORMAT_DEFAULT_DECIMAL = new WritableCellFormat(FONT, NUMBER_FORMAT);
CELL_FORMAT_DEFAULT_DATETIME = new WritableCellFormat(FONT, DATETIME_FORMAT);
CELL_FORMAT_DEFAULT_DATE = new WritableCellFormat(FONT, DATE_FORMAT);
CELL_FORMAT_HIGHLIGHT = new WritableCellFormat(FONT);
CELL_FORMAT_HIGHLIGHT.setBackground(Colour.VERY_LIGHT_YELLOW);
CELL_FORMAT_HEADER = new WritableCellFormat(BOLD_FONT);
CELL_FORMAT_HIGHLIGHT_INTEGER = new WritableCellFormat(FONT, INTEGER_FORMAT);
CELL_FORMAT_HIGHLIGHT_INTEGER.setBackground(Colour.VERY_LIGHT_YELLOW);
CELL_FORMAT_HIGHLIGHT_DECIMAL = new WritableCellFormat(FONT, NUMBER_FORMAT);
CELL_FORMAT_HIGHLIGHT_DECIMAL.setBackground(Colour.VERY_LIGHT_YELLOW);
CELL_FORMAT_HIGHLIGHT_DATETIME = new WritableCellFormat(FONT, DATETIME_FORMAT);
CELL_FORMAT_HIGHLIGHT_DATE = new WritableCellFormat(FONT, DATE_FORMAT);
CELL_FORMAT_HIGHLIGHT_DATETIME.setBackground(Colour.VERY_LIGHT_YELLOW);
} catch (WriteException e) {
e.printStackTrace();
}
}
public void initWorkbook(OutputStream outputStream) throws IOException {
final WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setGCDisabled(false);
workbookSettings.setEncoding("UTF-8");
workbook = Workbook.createWorkbook(outputStream, workbookSettings);
}
public void initWorkbook(File file) throws IOException {
final WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("UTF-8");
workbook = Workbook.createWorkbook(file, workbookSettings);
}
public WritableSheet createSheet(String label, Integer index) {
WritableSheet ws = workbook.createSheet(label, index);
sheet = ws;
sheetsMap.put(label, ws);
xIndex = 0;
yIndex = 0;
return ws;
}
public WritableSheet setWorkingSheet(String label) {
WritableSheet ws = null;
if (sheetsMap.containsKey(label)) {
ws = sheetsMap.get(label);
sheet = ws;
}
return ws;
}
public void writeContents(T object, Object... parameters) throws RowsExceededException,
WriteException, IOException {
JxlFormatAndValue[] contents = getContents(object, parameters);
writeContents(contents);
}
public void writeGroupContents(List<T> objects, Object... parameters) throws RowsExceededException,
WriteException, IOException {
List<JxlFormatAndValue[]> collection = getGroupContents(objects, parameters);
for(JxlFormatAndValue[] fnvs : collection){
writeContents(fnvs);
}
}
protected abstract JxlFormatAndValue[] getContents(T object, Object... parameters);
protected List<JxlFormatAndValue[]> getGroupContents(List<T> objects, Object... parameters){
List<JxlFormatAndValue[]> list = new ArrayList<JxlFormatAndValue[]>();
for(T object : objects){
list.add(getContents(object, parameters));
}
return list;
}
public void writeContents(JxlFormatAndValue... contents)
throws RowsExceededException, WriteException, IOException {
for (JxlFormatAndValue content : contents) {
writeCell(content);
}
nextRow();
}
public void writeHeader(String... headerData)
throws RowsExceededException, WriteException, IOException {
writeHeader(0, 0, headerData);
}
public void writeHeader(int row, int col, String... headerData)
throws RowsExceededException, WriteException, IOException {
xIndex = col;
yIndex = row;
for (String key : headerData) {
final Label label = new Label(xIndex++, yIndex, key,
CELL_FORMAT_HEADER);
sheet.addCell(label);
}
nextRow();
}
public void mergeCells(int row, int col, int rowspan, int colspan)
throws RowsExceededException, WriteException{
sheet.mergeCells(row, col, row + rowspan - 1, col + colspan -1);
}
public void writeCell(JxlFormatAndValue content) throws RowsExceededException,
WriteException {
if(content == null){
nextCell();
}else{
if( content.getColspan() > 1 || content.getRowspan() > 1 ){
sheet.mergeCells(xIndex, yIndex,
xIndex + content.getColspan() - 1,
yIndex + content.getRowspan() - 1);
}
writeCell(content.getValue(), content.getFormat());
}
}
public void writeCell(Object value, WritableCellFormat writableCellFormat)
throws RowsExceededException, WriteException {
if (value == null) {
nextCell();
} else {
CellValue cellValue = null;
if (Date.class.isAssignableFrom(value.getClass())) {
if (writableCellFormat == null) {
cellValue = new jxl.write.DateTime(xIndex++, yIndex,
(Date) value, CELL_FORMAT_DEFAULT_DATETIME);
} else {
cellValue = new jxl.write.DateTime(xIndex++, yIndex,
(Date) value, writableCellFormat);
}
} else if (Number.class.isAssignableFrom(value.getClass())) {
Number numberValue = (Number)value;
if (writableCellFormat == null) {
cellValue = new jxl.write.Number(xIndex++, yIndex,
numberValue.doubleValue(), CELL_FORMAT_DEFAULT_DECIMAL);
} else {
cellValue = new jxl.write.Number(xIndex++, yIndex,
numberValue.doubleValue(), writableCellFormat);
}
} else {
if (writableCellFormat == null) {
cellValue = new Label(xIndex++, yIndex, value.toString(),
CELL_FORMAT_DEFAULT);
} else {
cellValue = new Label(xIndex++, yIndex, value.toString(),
writableCellFormat);
}
}
if (cellValue != null) {
sheet.addCell(cellValue);
}
}
}
public void nextCell() {
xIndex++;
}
public void nextRow() {
xIndex = 0;
yIndex++;
}
public void closeWorkbook() throws IOException {
try {
if (workbook != null) {
workbook.write();
}
if (workbook != null) {
workbook.close();
}
} catch (WriteException e) {
e.printStackTrace();
}
}
public int getxIndex() {
return xIndex;
}
public void setxIndex(int xIndex) {
this.xIndex = xIndex;
}
public int getyIndex() {
return yIndex;
}
public void setyIndex(int yIndex) {
this.yIndex = yIndex;
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import common.Logger;
import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public abstract class JxlExcelImportFacade<T> {
private static final Logger logger = Logger.getLogger(JxlExcelImportFacade.class);
protected InputStream in;
protected Workbook workbook;
public void init(File file) throws BiffException, IOException{
this.in = new FileInputStream(file);
workbook = Workbook.getWorkbook(in);
}
public void init(InputStream in) throws BiffException, IOException{
this.in = in;
workbook = Workbook.getWorkbook(in);
}
public Sheet getSheet(int index){
return workbook.getSheet(index);
}
public abstract T readContent(Cell[] cells);
public List<T> readContents(List<Cell[]> rows){
List<T> result = new ArrayList<T>();
for(Cell[] cells : rows){
T content = readContent(cells);
result.add(content);
}
return result;
}
public void close() throws IOException{
workbook.close();
in.close();
}
public boolean isEmpty(Cell[] cells){
for(Cell cell : cells){
if( cell != null && StringUtils.isNotEmpty(cell.getContents())){
return false;
}
}
return true;
}
public Number readNumber(Cell cell, String defaultFormat){
String formatStr = defaultFormat;
if(cell.getType().equals(CellType.NUMBER)){
formatStr = cell.getCellFormat().getFormat().getFormatString();
if(StringUtils.isEmpty(formatStr)){
formatStr = defaultFormat;
}
}
String content = readString(cell);
try {
return new DecimalFormat(formatStr).parse(content);
} catch (ParseException e) {
logger.error("NumberFormat:" + formatStr + " NumberString:" + content , e);
return null;
}
}
public Number readNumber(Cell[] cells, int index, String defaultFormat){
if(cells.length > index){
return readNumber(cells[index], defaultFormat);
}
return null;
}
public Date readDate(Cell cell, String defaultFormat){
Date date = null;
String content = readString(cell);
try{
if(cell.getType().equals(CellType.DATE)){
if(cell instanceof DateCell){
date = DateUtils.truncate(((DateCell)cell).getDate(), Calendar.DATE);
}else{
String formatStr = cell.getCellFormat().getFormat().getFormatString();
try {
date = new SimpleDateFormat(formatStr).parse(content);
} catch (Exception e) {
date = new SimpleDateFormat(defaultFormat).parse(content);
}
}
}else{
date = new SimpleDateFormat(defaultFormat).parse(content);
}
}catch(ParseException e){
logger.error("Date:" + content + " Format:" + defaultFormat, e);
}
return date;
}
public Date readDate(Cell[] cells, int index, String defaultFormat){
if(cells.length > index){
return readDate(cells[index], defaultFormat);
}
return null;
}
public String readString(Cell cell){
return cell.getContents();
}
public String readString(Cell[] cells, int index){
if(cells.length > index){
return readString(cells[index]);
}
return "";
}
}
二、ImportBusTicketPrice
package com.icicle.goldenfly.web.order.report;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import org.apache.commons.lang.StringUtils;
import com.icicle.framework.member.client.MemberClientUtils;
import com.icicle.framework.order.client.enums.BusTicketSource;
import com.icicle.framework.order.client.models.BusTicketPrice;
import com.icicle.goldenfly.bus.server.BusTicketList;
/**
* 車票價格導入 處理Excel數據
* @author James pu
*
*/
public class ImportBusTicketPrice extends JxlExcelImportFacade<BusTicketPrice>{
public List<BusTicketPrice> readContents(){
List<BusTicketPrice> busTicketPriceList = new ArrayList<BusTicketPrice>();
Sheet sheet = getSheet(0);
int rows = sheet.getRows();
for(int i = 1; i < rows; i++){
Cell[] cells = sheet.getRow(i);
if( !isEmpty(cells)){
BusTicketPrice busTicketPrice = readContent(cells);
busTicketPriceList.add(busTicketPrice);
}
}
return busTicketPriceList;
}
@Override
public BusTicketPrice readContent(Cell[] cells) {
//來源
String source = StringUtils.defaultString(readString(cells, 0));
//起始站點代碼
String fromBusStop = StringUtils.defaultString(readString(cells, 1));
//目的站點代碼
String toBusStop = StringUtils.defaultString(readString(cells, 2));
//單程 賣價
double priceOfSingle =MemberClientUtils.getFirstNotNull(readNumber(cells, 3, "###0.00"), 0).doubleValue();
//雙程 賣價
double priceOfRound =MemberClientUtils.getFirstNotNull(readNumber(cells, 4, "###0.00"), 0).doubleValue();
//單程 買價
double dealPriceOfSingle =MemberClientUtils.getFirstNotNull(readNumber(cells, 5, "###0.00"), 0).doubleValue();
//雙程 買價
double dealPriceOfRound =MemberClientUtils.getFirstNotNull(readNumber(cells, 6, "###0.00"), 0).doubleValue();
//單程 門市價
double realPriceOfSingle =MemberClientUtils.getFirstNotNull(readNumber(cells, 7, "###0.00"), 0).doubleValue();
//雙程 門市價
double realPriceOfRound =MemberClientUtils.getFirstNotNull(readNumber(cells, 8, "###0.00"), 0).doubleValue();
//票數量
Integer restNumber =MemberClientUtils.getFirstNotNull(readNumber(cells, 9, "###0"), 0).intValue();
//有效期
Date expiredDate=null;
if(StringUtils.isNotEmpty(readString(cells,10))){
expiredDate = readDate(cells,10, "yyyy-MM-dd");
}
//備注
String remark = StringUtils.defaultString(readString(cells, 11));
BusTicketPrice busTicketPrice = new BusTicketPrice();
busTicketPrice.setSource(BusTicketSource.valueOf(source));
busTicketPrice.setFromBusStop(fromBusStop);
busTicketPrice.setFromBusStopDesc(BusTicketList.getStationDescByKey(fromBusStop));
busTicketPrice.setToBusStop(toBusStop);
busTicketPrice.setToBusStopDesc(BusTicketList.getStationDescByKey(toBusStop));
busTicketPrice.setPriceOfSingle(BigDecimal.valueOf(priceOfSingle));
busTicketPrice.setPriceOfRound(BigDecimal.valueOf(priceOfRound));
busTicketPrice.setDealPriceOfSingle(BigDecimal.valueOf(dealPriceOfSingle));
busTicketPrice.setDealPriceOfRound(BigDecimal.valueOf(dealPriceOfRound));
busTicketPrice.setRealPriceOfSingle(BigDecimal.valueOf(realPriceOfSingle));
busTicketPrice.setRealPriceOfRound(BigDecimal.valueOf(realPriceOfRound));
busTicketPrice.setRestNumber(restNumber);
busTicketPrice.setRemark(remark);
busTicketPrice.setExpiredDate(expiredDate);
return busTicketPrice;
}
}
三、HotNewsManagerEngine
package com.icicle.framework.member.server.driver;
import java.util.List;
import org.apache.commons.beanutils.PropertyUtils;
import com.icicle.framework.member.client.Principal;
import com.icicle.framework.member.client.ReturnResult;
import com.icicle.framework.member.client.criteria.GroupByResult;
import com.icicle.framework.member.client.criteria.HotNewsCriteria;
import com.icicle.framework.member.client.criteria.QuestionAnswerCriteria;
import com.icicle.framework.member.client.criteria.QuestionCriteria;
import com.icicle.framework.member.client.criteria.SetRestriction;
import com.icicle.framework.member.client.driver.HotNewsManagerDriver;
import com.icicle.framework.member.client.enums.ReturnCode;
import com.icicle.framework.member.client.exceptions.ClientGenericException;
import com.icicle.framework.member.client.models.Feedback;
import com.icicle.framework.member.client.models.FreeTravel;
import com.icicle.framework.member.client.models.FreeTravelHotel;
import com.icicle.framework.member.client.models.FreeTravelOther;
import com.icicle.framework.member.client.models.FreeTravelTraffic;
import com.icicle.framework.member.client.models.HotNews;
import com.icicle.framework.member.client.models.Question;
import com.icicle.framework.member.client.models.QuestionAnswer;
import com.icicle.framework.member.client.models.UploadImages;
import com.icicle.framework.member.client.models.WebSiteComment;
import com.icicle.framework.member.server.ApplicationContextLoader;
import com.icicle.framework.member.server.Constants;
import com.icicle.framework.member.server.service.BusTicketPriceService;
import com.icicle.framework.member.server.service.FeedbackService;
import com.icicle.framework.member.server.service.FreeTravelHotelService;
import com.icicle.framework.member.server.service.FreeTravelOtherService;
import com.icicle.framework.member.server.service.FreeTravelService;
import com.icicle.framework.member.server.service.FreeTravelTrafficService;
import com.icicle.framework.member.server.service.HotNewsService;
import com.icicle.framework.member.server.service.QuestionAnswerService;
import com.icicle.framework.member.server.service.QuestionService;
import com.icicle.framework.member.server.service.UploadImageService;
import com.icicle.framework.member.server.service.WebSiteCommentService;
import com.icicle.framework.order.client.criteria.FeedbackCriteria;
import com.icicle.framework.order.client.criteria.FreeTravelCriteria;
import com.icicle.framework.order.client.criteria.WebSiteCommentCriteria;
import com.icicle.framework.order.client.enums.BusTicketSource;
import com.icicle.framework.order.client.models.BusTicketPrice;
import com.icicle.goldenfly.bus.client.criteria.BusTicketPriceCriteria;
public class HotNewsManagerEngine implements HotNewsManagerDriver {
private HotNewsService hotNewsService;
private WebSiteCommentService webSiteCommentService;
private QuestionService questionService;
private QuestionAnswerService questionAnswerService;
private FeedbackService feedbackService;
private BusTicketPriceService busTicketPriceService;
private FreeTravelService freeTravelService;
private UploadImageService uploadImageService;
private FreeTravelOtherService freeTravelOtherService;
private FreeTravelHotelService freeTravelHotelService;
private FreeTravelTrafficService freeTravelTrafficService;
public HotNewsManagerEngine(HotNewsService hotNewsService,
WebSiteCommentService webSiteCommentService,
QuestionService questionService,
QuestionAnswerService questionAnswerService,
FeedbackService feedbackService,
BusTicketPriceService busTicketPriceService,
FreeTravelService freeTravelService,
UploadImageService uploadImageService,
FreeTravelOtherService freeTravelOtherService,FreeTravelHotelService freeTravelHotelService,FreeTravelTrafficService freeTravelTrafficService) {
this.hotNewsService = hotNewsService;
this.webSiteCommentService = webSiteCommentService;
this.questionService = questionService;
this.questionAnswerService = questionAnswerService;
this.feedbackService = feedbackService;
this.busTicketPriceService = busTicketPriceService;
this.freeTravelService = freeTravelService;
this.uploadImageService = uploadImageService;
this.freeTravelOtherService = freeTravelOtherService;
this.freeTravelHotelService = freeTravelHotelService;
this.freeTravelTrafficService = freeTravelTrafficService;
}
public HotNewsManagerEngine() {
hotNewsService = (HotNewsService) ApplicationContextLoader
.getApplicationContext().getBean(Constants.HOTNEWS_SERVICE);
webSiteCommentService = (WebSiteCommentService) ApplicationContextLoader
.getApplicationContext().getBean(
Constants.WEBSITE_COMMENT_SERVICE);
questionService = (QuestionService) ApplicationContextLoader
.getApplicationContext().getBean(Constants.QUESTION_SERVICE);
questionAnswerService = (QuestionAnswerService) ApplicationContextLoader
.getApplicationContext().getBean(
Constants.QUESTION_ANSWER_SERVICE);
feedbackService = (FeedbackService) ApplicationContextLoader
.getApplicationContext().getBean(Constants.FEEDBACK_SERVICE);
busTicketPriceService = (BusTicketPriceService) ApplicationContextLoader
.getApplicationContext().getBean(
Constants.BUSTICKETPRICE_SERVICE);
freeTravelService = (FreeTravelService) ApplicationContextLoader
.getApplicationContext().getBean(Constants.FREETRAVEL_SERVICE);
uploadImageService = (UploadImageService) ApplicationContextLoader
.getApplicationContext().getBean(Constants.UPLOADIMAGE_SERVICE);
freeTravelOtherService = (FreeTravelOtherService) ApplicationContextLoader
.getApplicationContext().getBean(
Constants.FREETRAVELOTHER_SERVICE);
freeTravelHotelService = (FreeTravelHotelService) ApplicationContextLoader
.getApplicationContext().getBean(
Constants.FREETRAVELHOTEL_SERVICE);
freeTravelTrafficService = (FreeTravelTrafficService) ApplicationContextLoader
.getApplicationContext().getBean(
Constants.FREETRAVELTRAFFIC_SERVICE);
}
public ReturnResult<Long> addHotNews(HotNews hotNews, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
hotNewsService.save(hotNews);
return ReturnCode.NORMAL_OKAY.toResult(hotNews.getId());
}
public Long countHotNews(HotNewsCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return hotNewsService.count(criteria, HotNews.class);
}
public ReturnResult<?> deleteHotNews(Long newsId, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
hotNewsService.deleteHotNews(newsId);
return ReturnCode.NORMAL_OKAY.toResult();
}
public List<HotNews> findHotNews(HotNewsCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return hotNewsService.find(criteria, HotNews.class);
}
public GroupByResult statisticsHotNews(HotNewsCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return hotNewsService.group(criteria, HotNews.class);
}
public ReturnResult<?> updateHotNews(HotNews hotNews, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
hotNewsService.update(hotNews);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public ReturnResult<Long> addWebSiteComment(WebSiteComment comment,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
webSiteCommentService.save(comment);
return ReturnCode.NORMAL_OKAY.toResult(comment.getId());
}
@Override
public Long countWebSiteComment(WebSiteCommentCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return webSiteCommentService.count(criteria, WebSiteComment.class);
}
@Override
public ReturnResult<?> deleteWebSiteComment(Long commentId,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
webSiteCommentService.deleteComment(commentId);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public List<WebSiteComment> findWebSiteComment(
WebSiteCommentCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return webSiteCommentService.find(criteria, WebSiteComment.class);
}
@Override
public GroupByResult statisticsWebSiteComment(
WebSiteCommentCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return webSiteCommentService.group(criteria, WebSiteComment.class);
}
@Override
public ReturnResult<?> updateWebSiteComment(WebSiteComment comment,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
webSiteCommentService.update(comment);
return ReturnCode.NORMAL_OKAY.toResult();
}
public ReturnResult<Long> addQuestion(Question question, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
questionService.save(question);
return ReturnCode.NORMAL_OKAY.toResult(question.getId());
}
public ReturnResult<?> updateQuestion(Question question, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
questionService.update(question);
return ReturnCode.NORMAL_OKAY.toResult();
}
public Long countQuestion(QuestionCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return questionService.count(criteria, Question.class);
}
public ReturnResult<?> deleteQuestion(Long questionId, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
questionService.deleteQuestion(questionId);
return ReturnCode.NORMAL_OKAY.toResult();
}
public List<Question> findQuestion(QuestionCriteria criteria,
Boolean lazyLoad, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return questionService.findQuestion(criteria, lazyLoad);
}
public List<Question> findRelatedQuestions(Long questionId, Integer number,
Boolean lazyLoad, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return questionService.findRelatedQuestions(questionId, number,
lazyLoad);
}
public ReturnResult<Long> answerQuestion(Long quesetionId,
QuestionAnswer answer, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return questionService.answerQuestion(quesetionId, answer);
}
public Long countQuestionAnswer(QuestionAnswerCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return questionAnswerService.count(criteria, QuestionAnswer.class);
}
public ReturnResult<?> deleteQuestionAnswer(Long answerId,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
questionAnswerService.deleteQuestionAnswer(answerId);
return ReturnCode.NORMAL_OKAY.toResult();
}
public List<QuestionAnswer> findQuestionAnswer(
QuestionAnswerCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return questionAnswerService.find(criteria, QuestionAnswer.class);
}
@Override
public ReturnResult<Long> addFeedback(Feedback feedback, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
feedbackService.save(feedback);
return ReturnCode.NORMAL_OKAY.toResult(feedback.getId());
}
@Override
public Long countFeedback(FeedbackCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return feedbackService.count(criteria, Feedback.class);
}
public ReturnResult<Long> addFreeTravel(FreeTravel freeTravel,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
freeTravelService.save(freeTravel);
return ReturnCode.NORMAL_OKAY.toResult(freeTravel.getId());
}
public ReturnResult<Long> addUploadImage(UploadImages uploadImage,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
uploadImageService.save(uploadImage);
return ReturnCode.NORMAL_OKAY.toResult(uploadImage.getId());
}
public ReturnResult<Long> addFreeTravelOther(FreeTravelOther other, Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
freeTravelOtherService.save(other);
return ReturnCode.NORMAL_OKAY.toResult(other.getId());
}
public ReturnResult<Long> addFreeTravelHotel(FreeTravelHotel hotel, Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
freeTravelHotelService.save(hotel);
return ReturnCode.NORMAL_OKAY.toResult(hotel.getId());
}
public ReturnResult<Long> addFreeTravelTraffic(FreeTravelTraffic traffic, Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
freeTravelTrafficService.save(traffic);
return ReturnCode.NORMAL_OKAY.toResult(traffic.getId());
}
public Long countFreeTravel(FreeTravelCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return freeTravelService.count(criteria, FreeTravel.class);
}
@Override
public ReturnResult<?> deleteFeedback(Long feedbackId, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
feedbackService.deleteFeedback(feedbackId);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public ReturnResult<?> deleteFreeTravel(Long freeTravelId,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
freeTravelService.deleteFreeTravel(freeTravelId);
return ReturnCode.NORMAL_OKAY.toResult();
}
public ReturnResult<?> deleteUploadImage(Long imageId, Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
uploadImageService.deleteUploadImage(imageId);
return ReturnCode.NORMAL_OKAY.toResult();
}
public ReturnResult<?> deleteFreeTravelOther(Long otherId, Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
freeTravelOtherService.deleteFreeTravelOther(otherId);
return ReturnCode.NORMAL_OKAY.toResult();
}
public ReturnResult<?> deleteFreeTravelHotel(Long hotelId, Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
freeTravelHotelService.deleteFreeTravelHotel(hotelId);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public List<Feedback> findFeedbackByList(FeedbackCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return feedbackService.find(criteria, Feedback.class);
}
public List<FreeTravel> findFreeTravelByList(FreeTravelCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return freeTravelService.find(criteria, FreeTravel.class);
}
public FreeTravel findFreeTravelById(FreeTravel freeTravel, Long freeTravelId ,Principal principal) throws ClientGenericException
{
Principal.setInstance(principal);
return freeTravelService.getById(FreeTravel.class, freeTravelId);
}
/**
* 更新反饋信息
*
* @param feedback
* @param principal
* @return
* @throws ClientGenericException
*/
@Override
public ReturnResult<?> updateFreeTravel(FreeTravel freeTravel,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
freeTravelService.update(freeTravel);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public ReturnResult<?> updateFeedback(Feedback feedback, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
feedbackService.update(feedback);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public List<BusTicketPrice> findBusTicketPrice(
BusTicketPriceCriteria criteria, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
return busTicketPriceService.find(criteria, BusTicketPrice.class);
}
@Override
public ReturnResult<Integer> addBusTicketPrice(
BusTicketPrice busTicketPrice, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
busTicketPriceService.save(busTicketPrice);
return ReturnCode.NORMAL_OKAY.toResult(busTicketPrice.getId());
}
@Override
public Long countBusTicketPrice(BusTicketPriceCriteria criteria,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
return busTicketPriceService.count(criteria, BusTicketPrice.class);
}
@Override
public ReturnResult<?> deleteBusTicketPrice(Integer id, Principal principal)
throws ClientGenericException {
Principal.setInstance(principal);
BusTicketPrice bean = new BusTicketPrice();
bean.setId(id);
busTicketPriceService.delete(bean);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public ReturnResult<?> updateBusTicketPrice(BusTicketPrice busTicketPrice,
Principal principal) throws ClientGenericException {
Principal.setInstance(principal);
busTicketPriceService.update(busTicketPrice);
return ReturnCode.NORMAL_OKAY.toResult();
}
@Override
public String batchUpdateBusTicketPrice(
List<BusTicketPrice> busTicketPriceList, Principal principal) {
try {
Principal.setInstance(principal);
int s = 0, f = 0, t = 0;
String msg = "";
for (BusTicketPrice busTicketPrice : busTicketPriceList) {
BusTicketSource source = busTicketPrice.getSource();
String fromBusStop = busTicketPrice.getFromBusStop();
String toBusStop = busTicketPrice.getToBusStop();
if (source == null || source.getKey() == null) {
s++;
continue;
}
if (fromBusStop == null || "".equals(fromBusStop)) {
f++;
continue;
}
if (toBusStop == null || "".equals(toBusStop)) {
t++;
continue;
}
// 查詢
BusTicketPriceCriteria criteria = new BusTicketPriceCriteria();
criteria.setSource(SetRestriction.in(source));
criteria.setFromBusStop(fromBusStop);
criteria.setToBusStop(toBusStop);
List<BusTicketPrice> list = busTicketPriceService.find(
criteria, BusTicketPrice.class);
if (list != null && list.size() > 0) {
BusTicketPrice tempBean = list.get(0);
Integer id = tempBean.getId();
PropertyUtils.copyProperties(tempBean, busTicketPrice);
tempBean.setId(id);
busTicketPriceService.update(tempBean);
} else {
busTicketPriceService.save(busTicketPrice);
}
}
if (s > 0) {
msg += "有 " + s + " 條數據因為沒找到 [來源]字段信息導入失敗;";
}
if (f > 0) {
msg += "有 " + f + " 條數據因為沒找到 [起始站點代碼]字段信息導入失敗;";
}
if (t > 0) {
msg += "有 " + t + " 條數據因為沒找到 [目的站點代碼]字段信息導入失敗;";
}
return msg;
} catch (Exception e) {
e.printStackTrace();
return "程序異常";
}
}
}
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileTypeMap;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.icicle.framework.member.client.SendingEmailEnvelope;
import com.icicle.framework.member.client.SendingEmailEnvelope.Attachment;
public class SendingEmailUtilImpl implements SendingEmailUtil{
private static final Logger logger = Logger.getLogger(SendingEmailUtilImpl.class);
private String host;
private String emailUser;
private String displayUserName;
private String password;
private String port;
protected String switcher;
private MessageTemplate emailSubjectTemplate;
private MessageTemplate emailContentTemplate;
@Override
public void sendEmail(SendingEmailEnvelope envelope)
throws MessagingException {
logger.debug("Sending Subject" + envelope.getSubject());
logger.debug("Sending Message " + envelope.getContent());
if (envelope.getRecipients().size() == 0 ) {
logger.error("List of recipients is null");
return;
}
Properties props = new Properties();
/**自己郵件服務器配置
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", host);
props.setProperty("mail.user", emailUser);
props.setProperty("mail.password", password);
*/
//QQ郵件服務器
props.put("mail.smtp.host", host);
props.put("mail.smtp.port",port );
props.put("mail.smtp.starttls.enable","true" );
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.socketFactory.port", "993");
// switcher
if(switcher != null && switcher.equals("on")){
//Session mailSession = Session.getDefaultInstance(props, null);//自己郵件服務不需要驗證
//QQ郵件服務器,需要驗證
Session mailSession = Session.getDefaultInstance(props,new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(emailUser, password);
}
});
/**替換QQ郵件服務器時注釋
Transport transport = null;
transport = mailSession.getTransport();
*/
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(displayUserName + "<" + emailUser + ">"));
message.setSentDate(new Date());
try {
message.setSubject(MimeUtility.encodeText(envelope.getSubject(), "UTF-8", "B"));
} catch (UnsupportedEncodingException e) {
logger.error("", e);
}
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(envelope.getContent(), "text/html; charset=\"UTF-8\"");
messageBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
multipart.addBodyPart(messageBodyPart);
if(envelope.getAttachments() != null){
logger.debug("Sending Attachments " + envelope.getAttachments().size());
for(Attachment attachment : envelope.getAttachments()){
String fileName = attachment.getName();
byte[] bytes = attachment.getFile();
logger.debug("Sending Attached file " + fileName);
if(StringUtils.isEmpty(fileName) ||
bytes == null || bytes.length == 0){
continue;
}
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.setFileName(fileName);
ByteArrayDataSource dataSource = new ByteArrayDataSource();
dataSource.setName(fileName);
dataSource.setBytes(bytes);
String contentType =
FileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
dataSource.setContentType(contentType);
logger.info(new StringBuilder()
.append("FileName: ").append(fileName)
.append(" ContentType: ").append(contentType));
attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
multipart.addBodyPart(attachmentBodyPart);
}
}
message.setContent(multipart);
if(envelope.getRecipients() != null){
for (String recipient : envelope.getRecipients()) {
if (recipient != null && !recipient.trim().equals("")) {
logger.warn("Ready to send emails to recipient '" + recipient + "'.");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(recipient));
}
}
}
if(envelope.getCc() != null){
for (String recipient : envelope.getCc()) {
if (recipient != null && !recipient.trim().equals("")) {
logger.warn("Ready to send emails to Cc '" + recipient + "'.");
message.addRecipient(Message.RecipientType.CC,
new InternetAddress(recipient));
}
}
}
if(envelope.getBcc() != null){
for (String recipient : envelope.getBcc()) {
if (recipient != null && !recipient.trim().equals("")) {
logger.warn("Ready to send emails to Bcc '" + recipient + "'.");
message.addRecipient(Message.RecipientType.BCC,
new InternetAddress(recipient));
}
}
}
if (message.getAllRecipients() != null &&
message.getAllRecipients().length != 0) {
try {
logger.info("Sending message.");
/**
transport.connect();替換QQ郵件服務器時注釋
transport.sendMessage(message,
message.getAllRecipients());
*/
Transport.send(message,message.getAllRecipients());
logger.info("Message sent.");
} finally {
//transport.close();
}
} else {
logger.error("List of recipients is null");
return;
}
}
}
public void sendEmail(String subject, String content,
Map<String, byte[]> attachments, Boolean preview, String... recipients )
throws MessagingException {
SendingEmailEnvelope envelope = new SendingEmailEnvelope();
envelope.setSubject(subject);
envelope.setContent(content);
envelope.addRecipients(recipients);
if (attachments != null) {
for (String name : attachments.keySet()) {
byte[] file = attachments.get(name);
envelope.addAttachment(name, file);
}
}
if(StringUtils.isNotBlank(content) && preview == false){
sendEmail(envelope);
}
}
@Override
public SendingEmailEnvelope sendEmail(String subject, String templateName, Object[] args,
Map<String, byte[]> attachments, Boolean preview, String... recipients) throws MessagingException {
String subTemp = emailSubjectTemplate.getTemplate(subject, args);
if(subTemp != null){
subject = subTemp;
}
String content = emailContentTemplate.getTemplate(templateName, args);
SendingEmailEnvelope envelope = new SendingEmailEnvelope();
envelope.setSubject(subject);
envelope.setContent(content);
envelope.addRecipients(recipients);
if(attachments != null){
for(String name : attachments.keySet()){
byte[] file = attachments.get(name);
envelope.addAttachment(name, file);
}
}
if(StringUtils.isNotBlank(content) && preview == false){
this.sendEmail(envelope);
}
return envelope;
}
public void setHost(String host) {
this.host = host;
}
public void setEmailUser(String emailUser) {
this.emailUser = emailUser;
}
public void setDisplayUserName(String displayUserName) {
this.displayUserName = displayUserName;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmailSubjectTemplate(MessageTemplate emailSubjectTemplate) {
this.emailSubjectTemplate = emailSubjectTemplate;
}
public void setEmailContentTemplate(MessageTemplate emailContentTemplate) {
this.emailContentTemplate = emailContentTemplate;
}
public MessageTemplate getEmailSubjectTemplate() {
return emailSubjectTemplate;
}
public MessageTemplate getEmailContentTemplate() {
return emailContentTemplate;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public void setSwitcher(String switcher) {
this.switcher = switcher;
}
public static void main(String[] args) throws MessagingException, IOException{
System.out.println("-----send eMial start-----");
SendingEmailUtilImpl email = new SendingEmailUtilImpl();
email.setHost("smtp.exmail.qq.com");
email.setEmailUser("cs@517hk.com");
email.setPassword("szyl517hk");
email.setPort("465");
email.setDisplayUserName("517HK Customer Service");
email.setSwitcher("on");
SendingEmailEnvelope envelope = new SendingEmailEnvelope();
envelope.setSubject("hello");
envelope.setContent("hello");
envelope.addRecipients("82067130@qq.com","45424380@qq.com");
email.sendEmail(envelope);
System.out.println("-----send eMial end-----");
// Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>();
// InputStream in = new BufferedInputStream(new FileInputStream("C:\\temp\\HotelXo.pdf"));
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// try{
// byte[] buffer = new byte[512];
// int len = in.read(buffer);
// while(len >= 0){
// out.write(buffer, 0, len);
// len = in.read(buffer);
// }
// attachments.put("HotelXo.pdf", out.toByteArray());
// email.sendEmail("hello", "Hello World.", null, "charles.so@222m.net");
// }finally{
// in.close();
// out.close();
// }
}
}