⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mimeutil.java

📁 DbService数据库接口,测试规范?菘饨涌?测试规范数据库接口,测试规范
💻 JAVA
字号:
package com.rainbow.mas.plugin.dbplugin.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.MimeType;
import javax.activation.MimeTypeParseException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.sql.rowset.serial.SerialBlob;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.rainbow.mas.web.dto.MmsContent;

public class MIMEUtil {

	static Logger logger = LogManager.getLogger(MIMEUtil.class);

	/**
	 * 将contentType转换成文件后缀名. Content Type 参见RFC 2045 and 2046.
	 * 
	 * @param contentType
	 * @return
	 */
	public static String getFileExtension(MimeType contentType) {
		if (contentType == null) {
			return null;
		}
		String pType = contentType.getPrimaryType();
		String sType = contentType.getSubType();
		if (pType.equalsIgnoreCase("application")) {
			if (sType.equalsIgnoreCase("smil")) {
				return "smil";
			}
		} else if (pType.equalsIgnoreCase("image")) {
			if (sType.equalsIgnoreCase("jpeg")) {
				return "jpeg";
			} else if (sType.equalsIgnoreCase("gif")) {
				return "gif";
			} else if (sType.equalsIgnoreCase("png")) {
				return "png";
			} else if (sType.equalsIgnoreCase("vnd.wap.wbmp")) {
				return "wbmp";
			}
		} else if (pType.equalsIgnoreCase("text")) {
			if (sType.equalsIgnoreCase("plain")) {
				return "txt";
			} else if (sType.equalsIgnoreCase("xml")) {
				return "xml";
			} else if (sType.equalsIgnoreCase("i-melody")) {
				return "imy";
			} else if (sType.equalsIgnoreCase("e-melody")) {
				return "emy";
			}
		} else if (pType.equalsIgnoreCase("audio")) {
			if (sType.equalsIgnoreCase("amr")) {
				return "amr";
			} else if (sType.equalsIgnoreCase("midi")) {
				return "mid";
			}
		}
		return null;
	}

	/**
	 * 根据文件后缀名提取出相应的content type(例如:application/smil)
	 * @param ext
	 * @return
	 */
	public static String getMimeType(String ext) {
		if (ext == null || ext.trim().length() == 0) {
			return null;
		}
		if (ext.equalsIgnoreCase("smil")) {
			return "application/smil";
		} else if (ext.equalsIgnoreCase("gif")) {
			return "image/gif";
		} else if (ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg")) {
			return "image/jpeg";
		} else if (ext.equalsIgnoreCase("png")) {
			return "image/png";
		} else if (ext.equalsIgnoreCase("wbmp")) {
			return "image/vnd.wap.wbmp";
		} else if (ext.equalsIgnoreCase("amr")) {
			return "audio/amr";
		} else if (ext.equalsIgnoreCase("mid") || ext.equalsIgnoreCase("midi")) {
			return "audio/midi";
		} else if (ext.equalsIgnoreCase("txt")) {
			//由于彩信内容表中没有保存字符编码信息,所以默认全部是使用utf8
			//如果使用gbk或者其他类型编码就会出现乱码现象
			return "text/plain;charset='utf-8';";
		} else if (ext.equalsIgnoreCase("xml")) {
			return "text/xml";
		} else if (ext.equalsIgnoreCase("imy")) {
			return "text/i-melody";
		} else if (ext.equalsIgnoreCase("emy")) {
			return "text/e-melody";
		}
		return null;
	}

	/**
	 * 从一个InputStream中构建一个Dummy MimeMessage
	 * 主要用于从MmsOutbox中的messagecontent中提取附件信息
	 * @param in
	 * @return
	 */
	public static MimeMessage compose(InputStream in) {

		if (in == null) {
			return null;
		}

		Properties props = System.getProperties();
		//smtp.21cn.com   使用邮件服务器 可用
		props.put("mail.host", "smtp.dummydomain.com");
		props.put("mail.transport.protocol", "smtp");

		Session mailSession = Session.getDefaultInstance(props, null);

		MimeMessage message = null;
		try {
			message = new MimeMessage(mailSession, in);
		} catch (MessagingException e) {
			e.printStackTrace();
			logger.error("decode from inputstream failed!", e);
		}

		return message;
	}

	/**
	 * 从MmsContents中重新组建一个MimeMessage
	 * @param contents
	 * @return
	 */
	public static MimeMessage composeDummy(Set<MmsContent> contents) {

		if (contents == null) {
			return null;
		}

		Properties props = System.getProperties();
		props.put("mail.host", "smtp.dummydomain.com");
		props.put("mail.transport.protocol", "smtp");

		Session mailSession = Session.getDefaultInstance(props, null);

		MimeMessage msg = null;
		try {
			msg = new MimeMessage(mailSession);
			msg.setFrom(new InternetAddress("from@dummy.com"));
			InternetAddress[] address = { new InternetAddress("to@dummy.com") };
			msg.setRecipients(Message.RecipientType.TO, address);
			msg.setSubject("Dummy Message");
			msg.setSentDate(new Date());

			// 增加附件
			MimeMultipart mp = new MimeMultipart();
			mp.setSubType("related");
			Iterator<MmsContent> it = contents.iterator();
			while (it.hasNext()) {
				MmsContent content = it.next();
				String name = content.getAttachmentName();
				String ext = content.getFileType();
				String type = getMimeType(ext);
				MimeBodyPart mbp = new MimeBodyPart();
				mbp.setFileName(name);

				Blob b = content.getContent();
				if (b == null)
					continue;
				try {
					ByteArrayDataSource source = new ByteArrayDataSource(b
							.getBinaryStream(), type);
					DataHandler dh = new DataHandler(source);
					mbp.setDataHandler(dh);
//					mbp.setContent(dh, type);
				} catch (Exception e) {
					logger.error("exception", e);
				}
				String ctype = mbp.getContentType();
				mp.addBodyPart(mbp);
			}
			msg.setContent(mp);

		} catch (MessagingException e) {
			logger.error("exception", e);
		}

		return msg;
	}

	/**
	 * 解析MimeMessage,提取其中的附件
	 * 
	 * @param part
	 * @return
	 * @throws IOException
	 * @throws MessagingException
	 */
	public static Set<MmsContent> parse(Part part) throws IOException,
			MessagingException {
		Set<MmsContent> set = new HashSet<MmsContent>();
		Object o = null;

		if (part instanceof Message) {
			o = part.getContent();
			if (o instanceof Multipart) {
				Multipart mp = (Multipart) o;
				int count;
				count = mp.getCount();
				for (int i = 0; i < count; i++) {
					Set<MmsContent> subset = parse(mp.getBodyPart(i));
					set.addAll(subset);
				}
			} else if (o instanceof MimeBodyPart) {
				part = (Part) o;
			}
		}
		if (part instanceof MimeBodyPart) {
			MimeBodyPart mbp = (MimeBodyPart) part;
			String ctype = part.getContentType();
			String cid = mbp.getContentID();   //文件名
			String filename = mbp.getFileName();
			String fileExt = null;
			MimeType type;
			try {
				type = new MimeType(ctype);
				fileExt = MIMEUtil.getFileExtension(type);
			} catch (MimeTypeParseException e) {
				logger.error("can't supported mime type!", e);
			}

			MmsContent content = new MmsContent();
			if(filename != null && filename.length() > 0)
			    content.setAttachmentName(filename);
			else
				content.setAttachmentName(cid);
			content.setFileType(fileExt);

			DataHandler handler = mbp.getDataHandler();
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			handler.writeTo(outStream);

			Blob b = null;
			try {
				b = new SerialBlob(outStream.toByteArray());
			} catch (Exception e) {
				logger.error("new Blob failed!", e);
			}
			content.setContent(b);
			set.add(content);
		}
		return set;
	}

	public static void main(String[] args) {

	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -