关闭

彩信管理控制类

489人阅读 评论(0) 收藏 举报
分类:
package com.hereis.bos.action;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.management.RuntimeErrorException;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.io.XMLWriter;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.hereis.base.entity.PageComponent;
import com.hereis.bos.entity.BosAp;
import com.hereis.bos.entity.BosUser;
import com.hereis.bos.entity.BosUserType;
import com.hereis.bos.entity.CmsMms;
import com.hereis.bos.entity.CmsMmsContent;
import com.hereis.bos.entity.CmsMsAPMapping;
import com.hereis.bos.entity.CmsSmsTypeKey;
import com.hereis.bos.service.CmsCustomerService;
import com.hereis.bos.service.CmsMMSService;
import com.hereis.bos.service.CmsRuleService;
import com.hereis.bos.service.CmsSMSService;
import com.hereis.constant.Constant;
import com.hereis.util.Base64Utils;
import com.hereis.util.SystemParameter;
import com.hereis.util.Utils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;


public class CmsMMSAction extends ActionSupport {

	private static final long serialVersionUID = 9023918183631423404L;
	private static final Log log = LogFactory.getLog(CmsMMSAction.class);
	private static final int MAX_WIDTH = 176; 
	private static final int MAX_HEIGHT = 220;
	
	private File uploadImg;
	private File uploadAudio;
	private String filePath;
	//private String saveFilePath;//相对路径
	private String send_id;//彩信ID
	private String content;
	private String title;
	private String apid;
	private String usertype;
	private String startTime;
	private String endTime;
	//查询时用的时间
	private String begintime;
	private String endtime;
	private String status;
	//分页
	private Integer pageNo=1;
	private Integer maxResult=10; 
	private PageComponent pageComponent;
	
	private List<CmsSmsTypeKey> typeKeys;
	
	private List<BosUserType> userTypeList;
	private List<BosAp> apList;
	private List<Object> availableMMSList;
	
	private CmsMms mms;
	private String myContentList;
	
	@Resource(name="CmsCustomerServiceImpl")
	private CmsCustomerService cmsCustomerService;
	@Resource(name="CmsSMSServiceImpl")
	private CmsSMSService cmsSMSService;
	@Resource(name="CmsMMSServiceImpl")
	private CmsMMSService cmsMMSService;
	
	// 返回的JSON信息
	private Map<String, Object> store = null;
	
	private static String path;
	private static  String imgMaxSize;
	private static  String audioMaxSize;
	private static  String frameDuration;
	private static String cmsPath;
	
	static{
		SystemParameter sp = new SystemParameter();
		path = sp.getValue("config/config.properties", "path");
		imgMaxSize = sp.getValue("config/config.properties", "imgMaxSize");
		audioMaxSize = sp.getValue("config/config.properties", "audioMaxSize");
		frameDuration = sp.getValue("config/config.properties", "frameDuration");
	}

	public String toQueryMMS()
	{
		return queryMMS();
	}
	@Resource
	private CmsRuleService cmsRuleService;
	public String toAddMMS()
	{
		apList = getBosUserAP();
		//客户类别
//		userTypeList = cmsCustomerService.getUserTypes();
		if(apList!=null&&apList.size()>0){
			userTypeList = cmsRuleService.selButbyApid(apList.get(0).getApid());
		}
		return SUCCESS;
	}
	public String changeAP(){
		userTypeList = cmsRuleService.selButbyApid(apid);
		store = new HashMap<String, Object>();
		store.put("userTypeList", userTypeList);
		store.put("typeKeys", typeKeys);
		store.put("send_id", send_id);
		return SUCCESS;
	}
	/**
	 * 彩信查询
	 */
	public String queryMMS()
	{
		try
		{
			//客户类别

			apList = getBosUserAP();
			BosUser user = (BosUser) ActionContext.getContext().getSession().get(Constant.LOGIN_USER);
			
//			userTypeList = cmsCustomerService.getUserTypes();
			BosUserType bosUserType = new BosUserType();
			bosUserType.setCustomerid(user.getCustomerid());
			userTypeList = cmsCustomerService.getMaxUserType(bosUserType);
			if(!Utils.isNullOrEmpty(begintime))
			{
				begintime+=" 00:00:00";
			}else
			{
				begintime="1970-01-01 00:00:00";
			}
			if(!Utils.isNullOrEmpty(endtime))
			{
				endtime+=" 23:59:59";
			}else
			{
				endtime="2170-12-31 23:59:59";
			}
			pageComponent = cmsMMSService.queryMMSForList(apid,begintime,endtime,user,pageNo,maxResult);
			//查询有效期内的彩信
			availableMMSList = cmsMMSService.getAvailableMMS(apid,begintime,endtime,user);
			/*if(begintime.equals("1970-01-01 00:00:00"))
			{
				begintime = null;
			}
			if(endtime.equals("2170-12-31 23:59:59"))
			{
				endtime = null;
			}*/
			//用户对应的客户类别
			CmsSmsTypeKey cmsSmsType = new CmsSmsTypeKey();
			cmsSmsType.setCustomerid(user.getCustomerid());
			typeKeys = cmsSMSService.getCmsSmsTypes(cmsSmsType);
			
			begintime = null;
			endtime = null;
		}catch (Exception e) {
			e.printStackTrace();
			log.error("查询彩信出错!");
			return ERROR;
		}	
		return SUCCESS;
	}
	
	/**
	 * 预览彩信时获取彩信内容 
	 */
	public String getContentByMMSId()
	{
		store = new HashMap<String, Object>();
		List<CmsMmsContent> content =null;
		if(!Utils.isNullOrEmpty(send_id))
		{
			try
			{
				content = cmsMMSService.getContentByMMSId(send_id);
			}catch(Exception e)
			{
				store.put("message", "预览彩信时发生错误!");
				log.error("预览彩信时获取彩信内容 失败!");
				e.printStackTrace();
				return SUCCESS;
			}
			
			if(content != null)
			{
				store.put("content", content);
			}else
			{
				store.put("message", "预览彩信时发生错误!");
				log.error("预览彩信时获取彩信内容 失败!彩信内容为空!");
			}
		}else
		{
			store.put("message", "预览彩信时发生错误!");
			log.error("预览彩信时获取彩信内容 失败!彩信ID为空!");
		}
		return SUCCESS;
	}
	
	/**
	 * 更新彩信状态,是否可用	
	 */
	public String updateMMSStatus(){
		store = new HashMap<String, Object>();
		if(!Utils.isNullOrEmpty(send_id) && !Utils.isNullOrEmpty(status))
		{
			try
			{
				cmsMMSService.updateMMSStatus(send_id,status);
				store.put("message", "修改彩信状态成功!");
			}
			catch(Exception e)
			{
				store.put("message", "修改彩信状态时发生错误!");
				log.error("修改彩信状态 失败!");
				e.printStackTrace();
				return SUCCESS;
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 彩信删除	
	 */
	public String deleteMMS()
	{
		store = new HashMap<String, Object>();
		boolean isOK;
		if(!Utils.isNullOrEmpty(send_id) && !Utils.isNullOrEmpty(apid))
		{
			try
			{
				isOK = cmsMMSService.deleteMMSByID(send_id,true);
			}catch(Exception e)
			{
				store.put("message", "预览彩信时发生错误!");
				log.error("预览彩信时获取彩信内容 失败!");
				e.printStackTrace();
				return SUCCESS;
			}
			
			if(isOK)
			{
				store.put("message", "删除彩信成功!");
			}else
			{
				store.put("message", "删除彩信时发生错误!");
				log.error("删除彩信 失败!");
			}
		}else
		{
			store.put("message", "删除彩信时发生错误!");
			log.error("删除彩信 失败!彩信ID或AP ID为空!");
		}
		return SUCCESS;
	}
	
	/**
	 * 进入彩信修改页面
	 */
	public String toUpdateMMS()
	{
		if(!Utils.isNullOrEmpty(send_id))
		{
			//客户类别
//			userTypeList = cmsCustomerService.getUserTypes();
			userTypeList = cmsRuleService.selButbyApid(apid);
			BosUser  bosUser=(BosUser) ActionContext.getContext().getSession().get(Constant.LOGIN_USER);
			CmsSmsTypeKey cmsSmsType = new CmsSmsTypeKey();
			cmsSmsType.setCustomerid(bosUser.getCustomerid());
			typeKeys = cmsSMSService.getCmsSmsTypes(cmsSmsType);
			apList = getBosUserAP();
			mms = cmsMMSService.getMMSById(send_id);
			List<CmsMmsContent> list = cmsMMSService.getContentByMMSId(send_id);
			JSONArray array = JSONArray.fromObject(list);
			myContentList = array.toString();
			System.out.println(myContentList);
			//彩信对应的客户类别
			List<BosUserType> typeList= cmsMMSService.getUserTypeByMMSId(send_id);
			//彩信对应的AP
			List<BosAp> _apList= cmsMMSService.getAPByMMSId(send_id);
			if(typeList!= null && typeList.size() >0 && userTypeList!=null && userTypeList.size()>0)
			{
				if(userTypeList.size() == typeList.size())
				{
					mms.setUsertypeName("all");
				}else
				{
					mms.setUsertypeName(typeList.get(0).getTypename());
				}
			}
			if(apList!= null && apList.size() >0 && _apList!=null && _apList.size()>0)
			{
				if(_apList.size() == apList.size())
				{
					mms.setApArea("all");
				}else
				{
					mms.setApArea(_apList.get(0).getDescription());
				}
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 彩信修改
	 */
	public String updateMMS()
	{
		store = new HashMap<String, Object>();
		if(!Utils.isNullOrEmpty(send_id) && !Utils.isNullOrEmpty(content) && !Utils.isNullOrEmpty(title) &&  !Utils.isNullOrEmpty(apid) &&
				!Utils.isNullOrEmpty(startTime) && !Utils.isNullOrEmpty(endTime) && !Utils.isNullOrEmpty(usertype))
		{
			log.info("彩信内容是---->"+content);
			cmsPath = ServletActionContext.getRequest().getRealPath("");
			//content = content.replace("\"", "\\\"");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String uploadPath = ServletActionContext.getRequest().getRealPath(path);
			
			List<ContentBean> frameList = new ArrayList<ContentBean>();
			JSONArray jArray = null;
			try{
				jArray = JSONArray.fromObject(content+"");
			}catch(Exception e)
			{
				e.printStackTrace();
			}
			
			//彩信帧数 数组
			Object[] jObjArray = (Object[]) JSONArray.toArray(jArray);
			//待压缩文件列表
			File[] fileArray = new File[jObjArray.length+1];
			for(int i=0;i<jObjArray.length;i++)
			{
				ContentBean cb = new ContentBean(); 
				String type = ((net.sf.ezmorph.bean.MorphDynaBean)jObjArray[i]).get("contentType").toString();
				String value = ((net.sf.ezmorph.bean.MorphDynaBean)jObjArray[i]).get("value").toString();
				if(type.equals("text"))
				{
					String s = newDirPath();
					log.info("生成TXT路径是----->"+uploadPath+"/"+s);
					File f = new File(uploadPath+"/"+s);
					if(!f.exists())
					{
						f.mkdirs();
					}
					FileWriter fw = null;
					String fileName = newFileName()+"_"+(i+1);
					log.info("TXT文件名----->"+fileName);
					String path = uploadPath+"/"+s +fileName+".txt";
					try {
						fw = new FileWriter(new File(path));
						//如果有<br>换行符的话,则替换为\n
						fw.write(value.replace("<br>", "\n"));
						fw.close();
					} catch (FileNotFoundException e) {
						store.put("success", false);
						store.put("message", "修改彩信失败!");
						log.error("生成TXT时未能找到对应的目录");
						e.printStackTrace();
						return SUCCESS;
					} catch (IOException e) {
						store.put("success", false);
						log.error("生成TXT失败");
						store.put("message", "修改彩信失败!");
						e.printStackTrace();
						return SUCCESS;
					}
					cb.type = type;
					cb.textValue = value;
					cb.filePath = path;
					cb.fileName = fileName;
					frameList.add(cb);
					fileArray[i] = new File(path);
				}else
				{
					cb.type = type;
					cb.filePath = cmsPath+"/"+value;
					int index  = value.lastIndexOf(".");
					if(index > -1)
					{
						cb.fileName = value.substring(index-14, value.length());
					}
					frameList.add(cb);
					fileArray[i] = new File(cb.filePath);
				}
			}
			String zipPath =null;
			try {
			//生成彩信smil xml文件
				String s = newDirPath();
				String xmlPath = createXML(frameList,uploadPath+"/"+s);
				fileArray[fileArray.length -1 ] = new File(xmlPath);
			//生成彩信ZIP
				zipPath = ZipFiles(fileArray, uploadPath+"/"+s);
			} catch (Exception e) {
				e.printStackTrace();
				store.put("success", false);
				store.put("message", "修改彩信失败!");
				return SUCCESS;
			}
			//将彩信保存至数据库
			CmsMms mms = new CmsMms();
			mms.setSend_id(send_id);
			mms.setSend_content(zipPath.replace(cmsPath, "").replace("\\", "/"));
			
			//base64编码
			String content = Base64Utils.encodeBASE64File(zipPath);
			mms.setMmscontent(content);
			mms.setTitle(title);
			try {
				mms.setStarttime(sdf.parse(startTime+" 00:00:00"));
				mms.setStoptime(sdf.parse(endTime+" 23:59:59"));
			} catch (ParseException e) {
				e.printStackTrace();
				store.put("success", false);
				store.put("message", "修改彩信失败!");
				return SUCCESS;
			}
			mms.setApid("not use now");
			try {
				cmsMMSService.updateTables(send_id,mms,frameList,apList,apid,usertype, frameDuration);
				store.put("success", true);
				store.put("message", "修改彩信成功!");
			} catch (Exception e) {
				store.put("success", false);
				store.put("message", "修改彩信失败!");
			}
		}else
		{
			store.put("success", false);
			store.put("message", "参数不能为空!");
		}
		return SUCCESS;
	}
	
	//上传图片
	public String uploadImg()
	{
		store = new HashMap<String, Object>();
		String uploadPath = ServletActionContext.getRequest().getRealPath(path);
		String s = newDirPath();
		log.info("上传路径是----->"+uploadPath+"/"+s);
		File f = new File(uploadPath+"/"+s);
		if(!f.exists())
		{
			f.mkdirs();
		}
		FileInputStream fis = null;
		FileOutputStream fos  = null;
		String suffix=null;//.jpg
		String fileName = newFileName();
		log.info("IMG文件名----->"+fileName);
		if(uploadImg != null)
		{
			try {
				fis = new FileInputStream(uploadImg);
				int index  = filePath.lastIndexOf(".");
				if(index > -1)
				{
					suffix = filePath.substring(index, filePath.length());
				}
				if(uploadImg.length() > new Long(Long.parseLong(imgMaxSize.trim())))
				{
					store.put("success", false);
					store.put("message", "上传的图片大小超过8m!");
					return SUCCESS;
				}
				BufferedImage img = ImageIO.read(fis);
				//等比缩放
				int imgWidth = img.getWidth();
				int imgHeight = img.getHeight();
				int newWidth = 0;
				int newHeight = 0;
				double rate1 = (double)imgWidth/(double)MAX_WIDTH;
				double rate2 = (double)imgHeight/(double)MAX_HEIGHT;
				double rate = rate1 > rate2 ? rate1:rate2;
				newWidth = (int) (imgWidth/rate);
				newHeight = (int) (imgHeight/rate);
				if(newWidth >= MAX_WIDTH)
				{
					newWidth = MAX_WIDTH;
				}
				if(newHeight >= MAX_HEIGHT)
				{
					newHeight = MAX_HEIGHT;
				}
//				if(newWidth <= imgWidth && imgWidth <= MAX_WIDTH)
//				{
//					newWidth = imgWidth;
//				}
//				if(newHeight <= imgHeight && imgHeight <= MAX_HEIGHT)
//				{
//					newHeight = imgHeight;
//				}
				if(imgWidth <= MAX_WIDTH && imgHeight <= MAX_HEIGHT)
				{
					newWidth = imgWidth;
					newHeight = imgHeight;
				}
				BufferedImage newImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);   
				newImg.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);  
				fos = new FileOutputStream(new File(uploadPath+"/"+s + File.separator+fileName+suffix));
				// JPEGImageEncoder可适用于其他图片类型的转换   
	            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
	            encoder.encode(newImg); 
				fis.close();
				fos.flush();
				fos.close();
				store.put("success", true);
				store.put("saveFilePath",path.replace("/", "").trim()+"/"+s+fileName+suffix);
				store.put("imgWidth", newWidth);
				store.put("imgHeight", newHeight);
				store.put("message", "上传成功!");
			} catch (FileNotFoundException e) {
				store.put("success", false);
				store.put("message", "没有找到相应的文件!");
				e.printStackTrace();
			} catch (IOException e) {
				store.put("success", false);
				store.put("message", "上传失败!");
				e.printStackTrace();
			}finally
			{
				try {
					if(fis != null)
					{
						fis.close();
					}
					if(fos != null)
					{
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return SUCCESS;
	}
	
	//上传音频
	public String uploadAudio()
	{
		store = new HashMap<String, Object>();
		String uploadPath = ServletActionContext.getRequest().getRealPath(path);
		String s = newDirPath();
		log.info("上传路径是----->"+uploadPath+"/"+s);
		File f = new File(uploadPath+"/"+s);
		if(!f.exists())
		{
			f.mkdirs();
		}
		FileInputStream fis = null;
		FileOutputStream fos  = null;
		String suffix=null;//.mid
		String fileName = newFileName();
		log.info("音频文件名----->"+fileName);
		if(uploadAudio != null)
		{
			try {
				fis = new FileInputStream(uploadAudio);
				int index  = filePath.lastIndexOf(".");
				if(index > -1)
				{
					suffix = filePath.substring(index, filePath.length());
				}
				if(uploadAudio.length() > new Long(Long.parseLong(audioMaxSize.trim())))
				{
					store.put("success", false);
					store.put("message", "上传的音频大小超过100KB!");
					return SUCCESS;
				}
				fos = new FileOutputStream(new File(uploadPath+"/"+s +File.separator+fileName+suffix));
				byte[] b = new byte[1024];
				int len = 0;
				while( (len= fis.read(b))> 0)
				{
					fos.write(b, 0, len);
				}
				fis.close();
				fos.flush();
				fos.close();
				store.put("success", true);
				store.put("saveFilePath",path.replace("/", "").trim()+"/"+s+fileName+suffix);
				store.put("message", "上传成功!");
			} catch (FileNotFoundException e) {
				store.put("success", false);
				store.put("message", "没有找到相应的文件!");
				e.printStackTrace();
			} catch (IOException e) {
				store.put("success", false);
				store.put("message", "上传失败!");
				e.printStackTrace();
			}finally
			{
				try {
					if(fis != null)
					{
						fis.close();
					}
					if(fos != null)
					{
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return SUCCESS;
	}

	private String newFileName() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		return sdf.format(new Date());
	}
	
	private String newDirPath() {
		Calendar cal = Calendar.getInstance();
		int month = cal.get(Calendar.MONTH)+1;
		int day = cal.get(Calendar.DATE);
		int hour = cal.get(Calendar.HOUR_OF_DAY);
		return month+"/"+day+"/"+hour+"/";
	}
	
	/**
	 * 获取登录商户的ap
	 * @return
	 */
	public List<BosAp> getBosUserAP(){
		List<BosAp> list = new ArrayList<BosAp>();
		BosUser  bosUser=(BosUser) ActionContext.getContext().getSession().get(Constant.LOGIN_USER);
		list = cmsSMSService.getBosUserAP(bosUser);
		return list;
	}
	
	//保存彩信
	public String saveMMS()
	{
		store = new HashMap<String, Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		cmsPath = ServletActionContext.getRequest().getRealPath("");
		if(!Utils.isNullOrEmpty(content) && !Utils.isNullOrEmpty(title) &&  !Utils.isNullOrEmpty(apid) &&
				!Utils.isNullOrEmpty(startTime) && !Utils.isNullOrEmpty(endTime) && !Utils.isNullOrEmpty(usertype) )
		{
			log.info("彩信内容是---->"+content);
			//content = content.replace("\"", "\\\"");
			String uploadPath = ServletActionContext.getRequest().getRealPath(path);
			
			List<ContentBean> frameList = new ArrayList<ContentBean>();
			JSONArray jArray = null;
			try{
				jArray = JSONArray.fromObject(content+"");
			}catch(Exception e)
			{
				e.printStackTrace();
			}
			
			//彩信帧数 数组
			Object[] jObjArray = (Object[]) JSONArray.toArray(jArray);
			//待压缩文件列表
			File[] fileArray = new File[jObjArray.length+1];
			for(int i=0;i<jObjArray.length;i++)
			{
				ContentBean cb = new ContentBean(); 
				String type = ((net.sf.ezmorph.bean.MorphDynaBean)jObjArray[i]).get("contentType").toString();
				String value = ((net.sf.ezmorph.bean.MorphDynaBean)jObjArray[i]).get("value").toString();
				if(type.equals("text"))
				{
					String s = newDirPath();
					log.info("生成TXT路径是----->"+uploadPath+"/"+s);
					File f = new File(uploadPath+"/"+s);
					if(!f.exists())
					{
						f.mkdirs();
					}
					FileWriter fw = null;
					String fileName = newFileName()+"_"+(i+1);
					log.info("TXT文件名----->"+fileName);
					String path = uploadPath+"/"+s +fileName+".txt";
					try {
						fw = new FileWriter(new File(path));
						//如果有<br>换行符的话,则替换为\n
						fw.write(value.replace("<br>", "\n"));
						fw.close();
					} catch (FileNotFoundException e) {
						store.put("success", false);
						store.put("message", "保存失败!");
						log.error("生成TXT时未能找到对应的目录");
						e.printStackTrace();
						return SUCCESS;
					} catch (IOException e) {
						store.put("success", false);
						log.error("生成TXT失败");
						store.put("message", "保存失败!");
						e.printStackTrace();
						return SUCCESS;
					}
					cb.type = type;
					cb.textValue = value;
					cb.filePath = path;
					cb.fileName = fileName;
					frameList.add(cb);
					fileArray[i] = new File(path);
				}else
				{
					cb.type = type;
					cb.filePath = cmsPath+"/"+value;
					int index  = value.lastIndexOf(".");
					if(index > -1)
					{
						cb.fileName = value.substring(index-14, value.length());
					}
					frameList.add(cb);
					fileArray[i] = new File(cb.filePath);
				}
			}
			String zipPath =null;
			try {
			//生成彩信smil xml文件
				String s = newDirPath();
				String xmlPath = createXML(frameList,uploadPath+"/"+s);
				fileArray[fileArray.length -1 ] = new File(xmlPath);
			//生成彩信ZIP
				zipPath = ZipFiles(fileArray, uploadPath+"/"+s);
			} catch (Exception e) {
				e.printStackTrace();
				store.put("success", false);
				store.put("message", "发布彩信失败!");
				return SUCCESS;
			}
			//base64编码
			String content = Base64Utils.encodeBASE64File(zipPath);
			//转换为Clob
//			Clob clob = null;
//			try {
//				clob = new SerialClob(content.toCharArray());
//			} catch (SerialException e1) {
//				e1.printStackTrace();
//			} catch (SQLException e1) {
//				e1.printStackTrace();
//			}
			//将彩信保存至数据库
			CmsMms mms = new CmsMms();
			String mmsId = Utils.createID();
			mms.setSend_id(mmsId);
			mms.setSend_content(zipPath.replace(cmsPath, "").replace("\\", "/"));
			mms.setMmscontent(content);
			mms.setTitle(title);
			try {
				mms.setStarttime(sdf.parse(startTime+" 00:00:00"));
				mms.setStoptime(sdf.parse(endTime+" 23:59:59"));
			} catch (ParseException e) {
				e.printStackTrace();
				store.put("success", false);
				store.put("message", "发布彩信失败!");
				return SUCCESS;
			}
			mms.setApid("not use now");
			//保存数据
			try {
				cmsMMSService.saveTables(mms,frameList,apid,apList,usertype,frameDuration);
				store.put("success", true);
				store.put("message", "发布彩信成功!");
			} catch (Exception e) {
				store.put("success", false);
				store.put("message", "发布彩信失败!");
			}
		}else
		{
			store.put("success", false);
			store.put("message", "参数不能为空!");
		}
		return SUCCESS;
	}
	
	private void batchSaveMMSContent(CmsMms mms,List<ContentBean> frameList)
	{
		List<CmsMmsContent> contentList = new ArrayList<CmsMmsContent>();
		cmsPath = ServletActionContext.getRequest().getRealPath("");
		if(mms != null && !Utils.isNullOrEmpty(mms.getSend_id()) && frameList != null && frameList.size() > 0)
		{
			int count = 1;
			for(ContentBean cb : frameList)
			{
				CmsMmsContent con = new CmsMmsContent();
				con.setContent_id(Utils.createID());
				con.setSend_id(mms.getSend_id());
				con.setFrame(count);
				if(cb.type.equals("text"))
				{
					con.setText(cb.textValue.replace("<br>", "\n"));
				}else if(cb.type.equals("img"))
				{
					con.setPic(cb.filePath.replace(cmsPath, ""));
				}else
				{
					con.setMedia(cb.filePath.replace(cmsPath, ""));
				}
				con.setDuration(Integer.parseInt(frameDuration.replace("ms", "")));
				contentList.add(con);
				count++;
			}
			if(contentList.size() >0)
			{
				cmsMMSService.batchSaveMMSContent(contentList);
			}
		}
	}
	
	/**
	 * 生成彩信smil xml文件
	 * @param frameList 帧礼拜
	 * @param outputPath 生成文件的路径
	 * @return 生成的XML文件 的绝对路径,如c:\1.xml
	 */
	private String createXML(List<ContentBean> frameList,String outputPath)
	{
		String name = null;
		// 创建xml doc   
		 Document document = DocumentHelper.createDocument();
		 document.addDocType("smil", "-//W3C//DTD SMIL 2.0//EN", "http://www.w3.org/2001/SMIL20/SMIL20.dtd");
		 //根节点
		 Element smil = document.addElement(new QName("smil",new Namespace(null, "http://www.w3.org/2001/SMIL20/Language") ));
		 Element head = smil.addElement("head");
		 Element layout = head.addElement("layout");
		 Element rootlayout = layout.addElement("root-layout");
		 rootlayout.addAttribute("width", "128");
		 rootlayout.addAttribute("height", "128");
		 Element region = rootlayout.addElement("region");
		 region.addAttribute("id", "Image");
		 region.addAttribute("height", "128");
		 region.addAttribute("width", "128");
		 region.addAttribute("top", "0");
		 region.addAttribute("left", "0");
		 Element region2 = rootlayout.addElement("region");
		 region2.addAttribute("id", "Text");
		 region2.addAttribute("height", "128");
		 region2.addAttribute("width", "128");
		 region2.addAttribute("top", "0");
		 region2.addAttribute("left", "0");
		 Element body = smil.addElement("body");
		 for(int i=0;i<frameList.size();i++)
		 {
			 ContentBean cb = frameList.get(i);
			 Element par = body.addElement("par");
			 par.addAttribute("dur", frameDuration);
			 if(cb.type.equals("text"))
			 {
				 Element text = par.addElement("text");
				 text.addAttribute("src", cb.fileName+".txt");
				 text.addAttribute("region", "Text");
			 }else if(cb.type.equals("img"))
			 {
				 Element img = par.addElement("img");
				 img.addAttribute("src", cb.fileName);
				 img.addAttribute("region", "Image");
			 }else{
				 Element audio = par.addElement("audio");
				 audio.addAttribute("src", cb.fileName);
			 }
		 }
		 try {
			name = newFileName();
			System.out.println(document.asXML());
			XMLWriter writer = new XMLWriter(new FileOutputStream(new File(outputPath+"/"+name+".xml")));
			writer.write(document);
			writer.close();
			log.info("彩信smil文件成功生成.");
		} catch (UnsupportedEncodingException e) {
			log.info("彩信smil文件生成失败.");
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			log.info("彩信smil文件生成失败.");
			e.printStackTrace();
		} catch (IOException e) {
			log.info("彩信smil文件生成失败.");
			e.printStackTrace();
		}
		return outputPath+"/"+name+".xml";
	}
	
	/**
	 * zip压缩文件
	 * @param srcfile FilePath[] 需要压缩的文件列表
	 */
	private  String ZipFiles(File[] srcfile,String path) {
	    byte[] buf = new byte[1024];
	    String name = newFileName();
	    try {
	      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(path+name+".zip"));
	      //开始压缩
	      for (int i = 0; i < srcfile.length; i++) {
	        FileInputStream in = new FileInputStream(srcfile[i]);
	        out.putNextEntry(new ZipEntry(srcfile[i].getName()));
	        int len = 0;
	        while( (len = in.read(buf)) > 0) {
	          out.write(buf, 0, len);
	        }
	        out.closeEntry();
	        in.close();
	      }
	      out.close();
	      log.info("彩信ZIP压缩完成.");
	    }
	    catch (IOException e) {
	      log.error("彩信ZIP压缩失败.");
	      e.printStackTrace();
	    }
	    return  path+name+".zip";
	}
	
	/**
	 * 彩信内容实体类
	 *
	 */
	public class ContentBean{
		public String textValue;
		public String type;//类型
		public String filePath;//文件路径
		public String fileName;
	}

	public void setUploadImg(File uploadImg) {
		this.uploadImg = uploadImg;
	}

	public File getUploadImg() {
		return uploadImg;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setStore(Map<String, Object> store) {
		this.store = store;
	}

	public Map<String, Object> getStore() {
		return store;
	}

	public void setUploadAudio(File uploadAudio) {
		this.uploadAudio = uploadAudio;
	}

	public File getUploadAudio() {
		return uploadAudio;
	}

	public void setApList(List<BosAp> apList) {
		this.apList = apList;
	}

	public List<BosAp> getApList() {
		return apList;
	}

	public void setUserTypeList(List<BosUserType> userTypeList) {
		this.userTypeList = userTypeList;
	}

	public List<BosUserType> getUserTypeList() {
		return userTypeList;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getContent() {
		return content;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setApid(String apid) {
		this.apid = apid;
	}

	public String getApid() {
		return apid;
	}

	public void setUsertype(String usertype) {
		this.usertype = usertype;
	}

	public String getUsertype() {
		return usertype;
	}

	public void setStartTime(String startTime) {
		this.startTime = startTime;
	}

	public String getStartTime() {
		return startTime;
	}

	public void setEndTime(String endTime) {
		this.endTime = endTime;
	}

	public String getEndTime() {
		return endTime;
	}

	public void setBegintime(String begintime) {
		this.begintime = begintime;
	}

	public String getBegintime() {
		return begintime;
	}

	public void setEndtime(String endtime) {
		this.endtime = endtime;
	}

	public String getEndtime() {
		return endtime;
	}

	public void setPageComponent(PageComponent pageComponent) {
		this.pageComponent = pageComponent;
	}

	public PageComponent getPageComponent() {
		return pageComponent;
	}

	public void setPageNo(Integer pageNo) {
		this.pageNo = pageNo;
	}

	public Integer getPageNo() {
		return pageNo;
	}

	public void setMaxResult(Integer maxResult) {
		this.maxResult = maxResult;
	}

	public Integer getMaxResult() {
		return maxResult;
	}

	public void setAvailableMMSList(List<Object> availableMMSList) {
		this.availableMMSList = availableMMSList;
	}

	public List<Object> getAvailableMMSList() {
		return availableMMSList;
	}

	public void setSend_id(String send_id) {
		this.send_id = send_id;
	}

	public String getSend_id() {
		return send_id;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getStatus() {
		return status;
	}

	public void setMms(CmsMms mms) {
		this.mms = mms;
	}

	public CmsMms getMms() {
		return mms;
	}

	public void setMyContentList(String myContentList) {
		this.myContentList = myContentList;
	}

	public String getMyContentList() {
		return myContentList;
	}

	public void setTypeKeys(List<CmsSmsTypeKey> typeKeys) {
		this.typeKeys = typeKeys;
	}

	public List<CmsSmsTypeKey> getTypeKeys() {
		return typeKeys;
	}

	
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2494次
    • 积分:84
    • 等级:
    • 排名:千里之外
    • 原创:6篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档