文档章节

Java parsing XML file

Nathans
 Nathans
发布于 2016/08/30 15:28
字数 1123
阅读 7
收藏 0

XML introduction

  XML 指可扩展标记语言,XML 被设计用来传输和存储数据。

  基于XML解析方式有两种:

    SAX:基于事件流的解析;
    DOM:基于XML文档树结构的解析;
New to XML basics:http://www.ibm.com/developerworks/cn/xml/x-newxml/

 

Email xml profile:

<?xml version="1.0" encoding="UTF-8"?>
<mails>
	<mail domain="@163.com" serverType="POP3" starttls="true">
		<incoming>
			<server>pop.163.com</server>
			<port>110</port>
			<ssl>false</ssl>
		</incoming>
		<outgoing>
			<server>smtp.163.com</server>
			<port>465</port>
			<ssl>true</ssl>
		</outgoing>
		<test>
			<account>xxxxxx@163.com</account>
			<password>******</password>
		</test>
	</mail>
	<mail domain="@126.com" serverType="IMAP" starttls="false">
		<incoming>
			<server>imap.126.com</server>
			<port>995</port>
			<ssl>true</ssl>
		</incoming>
		<outgoing>
			<server>smtp.126.com</server>
			<port>465</port>
			<ssl>true</ssl>
		</outgoing>
		<test>
			<account>xxxxxxx@126.com</account>
			<password>******</password>
		</test>
	</mail>
	<mail domain="@sina.com" serverType="POP3">
		<incoming>
			<server>pop.sina.com</server>
			<port>110</port>
			<ssl>false</ssl>
		</incoming>
		<outgoing>
			<server>smtp.pop.com</server>
			<port>465</port>
			<ssl>true</ssl>
		</outgoing>
	</mail>
	<mail domain="@yahoo.com" serverType="Exchange">
 		<server>somewhere@yahoo.com</server>
	</mail>
</mails>

 

DOM parsing XML core objects is as follows:

java.xml.parse.DocumentBuilderFactory:Create abstract DocmentBuilderFactory.

java.xml.parse.DocumentBuilder:get document builder from DocumentBuilderFactory.

org.w3c.dom.Document:a document xml.

org.w3c.dom.Node:a node.

 

Use DOM Parse xml code:

public List<Y7MessageMailSettings> parseMailProfile(String path) {
		List<Y7MessageMailSettings> mailSettingsLis = new ArrayList<Y7MessageMailSettings>();
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document document = documentBuilder.parse(new FileInputStream(path));
			NodeList mails = document.getElementsByTagName("mail");
			for (int i = 0; i < mails.getLength(); i++) {
				Element mail = (Element) mails.item(i);
				//此处值得注意,在DOM解析时会将所有回车都视为 n 节点的子节点。 mail.hasChildNodes()
				if (StringUtils.isBlank(mail.getAttribute("domain"))) throw new IllegalArgumentException(String.format("Article %s mail property '%s'  value must not null", i + 1 , MailProfileElement.domain.name()));
				if (StringUtils.isBlank(mail.getAttribute("serverType"))) throw new IllegalArgumentException(String.format("Article %s mail property '%s'  value must not null", i + 1 , MailProfileElement.serverType.name()));
				Y7MessageMailSettings mailSetting = new Y7MessageMailSettings(mail.getAttribute(MailProfileElement.domain.name()), mail.getAttribute(MailProfileElement.serverType.name()), Boolean.valueOf(mail.getAttribute(MailProfileElement.starttls.name())));
				if (MailServerType.POP3.name().equalsIgnoreCase(mail.getAttribute("serverType")) || 
						MailServerType.IMAP.name().equalsIgnoreCase(mail.getAttribute("serverType")))
					pasePOP3OrIMAP(mail, mailSetting);
				else if(MailServerType.EXCHANGE.name().equalsIgnoreCase(mail.getAttribute("serverType")))
					parseExchange(mail, mailSetting);
				if (StringUtils.isBlank(mailSetting.getServer())) throw new IllegalArgumentException(String.format("Article %s mail property '%s'  value must not null", i + 1 , MailProfileElement.server.name()));
				mailSettingsLis.add(mailSetting);
			}
			log.debug("Analytical results");
			for (Y7MessageMailSettings mailSetting : mailSettingsLis)
				log.debug(mailSetting.toString());
			
			return mailSettingsLis;
		} catch (ParserConfigurationException e) {
			log.error(e.getMessage(), e);
		} catch (FileNotFoundException e) {
			log.error(e.getMessage(), e);
		} catch (SAXException e) {
			log.error(e.getMessage(), e);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		} catch (IllegalArgumentException e){
			log.error(e.getMessage(), e);
		}
		return mailSettingsLis;
	}
	
	public List<Y7MessageMailSettings> validateMailConfiguration(List<Y7MessageMailSettings> mailSettingsLis) {
		Map<String, Y7MessageMailSettings> domainMaps = new HashMap<String, Y7MessageMailSettings>();
		for (Y7MessageMailSettings mailSettings : mailSettingsLis) {
			if (!mailSettings.isTestMail()) {
				if (!domainMaps.containsKey(mailSettings.getDomain())) domainMaps.put(mailSettings.getDomain(), mailSettings);
				continue;
			}
			try {
				testConnectMail(mailSettings);
				sendTestEmail(mailSettings);
				mailSettings.setValidate(true);
				if (domainMaps.containsKey(mailSettings.getDomain())) {
					Y7MessageMailSettings sameDomainmailSetting = domainMaps.get(mailSettings.getDomain());
					if (sameDomainmailSetting.isValidate()) continue;
				}
				domainMaps.put(mailSettings.getDomain(), mailSettings);
			} catch (Exception e) {
				if (!domainMaps.containsKey(mailSettings.getDomain())) domainMaps.put(mailSettings.getDomain(), mailSettings);
				log.error("validate user {} failed:", mailSettings.getAccount());
				log.error(e.getMessage(), e);
			}
		}
		return new ArrayList<Y7MessageMailSettings>(domainMaps.values());
	}
	
	public static void sendTestEmail(Y7MessageMailSettings mailSettings) {
		try{
			Session session = createSession(mailSettings);
			
			MimeMessage message = createMessage(mailSettings.getAccount(), session);
	        
	        String host = null;
			if (!mailSettings.getServerType().toUpperCase().equals(String.valueOf(MailServerType.EXCHANGE))) host = mailSettings.getSmtp();
			else host = mailSettings.getServer();
			
			Transport transport = session.getTransport("smtp");
			transport.connect(host, mailSettings.getAccount(), mailSettings.getPassword());
			transport.send(message);
			log.debug("测试邮箱 {} 发送测试邮件成功!", mailSettings.getAccount());
		} catch (Exception e) {
			log.error("测试邮箱" + mailSettings.getAccount() + "发送邮件出错:"+e.getMessage(), e);
			throw new RuntimeException("send email failed.");
		}
	}

	private static MimeMessage createMessage(String account, Session session) throws AddressException, MessagingException {
		InternetAddress fromAddress = new InternetAddress(account);
		MimeMessage message = new MimeMessage(session);
		message.setFrom(fromAddress);
		message.addRecipient(RecipientType.TO, fromAddress); // 将所有接收者地址都添加到邮件接收者属性中
		message.setSubject("测试邮件");
		message.setSentDate(Calendar.getInstance().getTime());
		
		Multipart multipart = new MimeMultipart();
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setContent(CommonUtils.convertNewLine("测试邮件SMTP服务器"), MESSAGE_TYPE);
		multipart.addBodyPart(contentPart);
		message.setContent(multipart);
		return message;
	}
	
	public static Session createSession(Y7MessageMailSettings mailSettings) {
		Properties props = new Properties();
		String host = null;
		if (!mailSettings.getServerType().toUpperCase().equals(String.valueOf(MailServerType.EXCHANGE))) host = mailSettings.getSmtp();
		else host = mailSettings.getServer();
		props.put("mail.smtp.host", host);
		if (!mailSettings.isSmtpSSL()) {
			if (mailSettings.isStarttls()) {
				props.put("mail.smtp.socketFactory.class","com.y7tech.y7message.common.ExchangeSSLSocketFactory");
				props.put("mail.smtp.ssl.trust", host);
				props.put("mail.smtp.starttls.enable", mailSettings.isStarttls());
			}
		} else if(mailSettings.isSmtpSSL()) {
			props.put("mail.smtp.ssl.enable",mailSettings.isSmtpSSL());
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		}
		
		if (!mailSettings.getServerType().toUpperCase().equals(String.valueOf(MailServerType.EXCHANGE)))
			props.put("mail.smtp.port", mailSettings.getSmtpPort());
		props.put("mail.smtp.auth", true);
		props.put("mail.debug", false);
		log.debug("mail parms [" + props.toString() + "]");
		return Session.getInstance(props, new MyAuthenticator(mailSettings.getAccount(), mailSettings.getPassword()));
	}
	
	static class MyAuthenticator extends Authenticator{
		String userName="";
		String password="";
		public MyAuthenticator(){
			
		}
		public MyAuthenticator(String userName,String password){
			this.userName=userName;
			this.password=password;
		}
		 protected PasswordAuthentication getPasswordAuthentication(){   
			return new PasswordAuthentication(userName, password);   
		 } 
	}
	
	public static void testConnectMail(Y7MessageMailSettings mailSettings) throws ServiceException {
		MailFetcher fetcher = null;
		if (mailSettings.getServerType().toUpperCase().equals(String.valueOf(MailServerType.IMAP))
				|| mailSettings.getServerType().toUpperCase().equals(String.valueOf(MailServerType.EXCHANGE))) {
			fetcher = new MailFetcherIMAP();
		} else {
			fetcher = new MailFetcherPOP3();
		}
		Properties props = fetcher.getProperties(mailSettings);
		Session session = null;
		Store store = null;
		session = Session.getInstance(props);
		try {
			store = session.getStore(fetcher.getProtocol());
			store.connect(mailSettings.getAccount(), mailSettings.getPassword());
		} catch (Exception e) {
			log.error("test connect {} failed, email configuration {}", mailSettings.getAccount(), props.toString());
			log.error("set user mail settings error:" + e.getMessage(), e);
			throw new RuntimeException("test connect mail failed.");
		}
	}
	
	private static void parseExchange(Element mail, Y7MessageMailSettings mailSettings) {
		NodeList mailPropertys = mail.getChildNodes();
		for (int j = 0; j < mailPropertys.getLength(); j++) {
			Node mailProperty = mailPropertys.item(j);
			if (mailProperty.getNodeType() != Node.ELEMENT_NODE) continue;
			if (mailProperty.getNodeName().equals(MailProfileElement.server.lowerCase()))
				if (mailProperty.getFirstChild() != null) mailSettings.setServer(mailProperty.getFirstChild().getNodeValue());
			for (Node node = mailProperty.getFirstChild(); node != null; node = node.getNextSibling()) {  
				if (node.getNodeType() != Node.ELEMENT_NODE) continue;
				if (mailProperty.getNodeName().equals(MailProfileElement.test.lowerCase())) {
					if (node.getFirstChild() == null) throw new IllegalArgumentException(String.format("param %s mut not null", MailProfileElement.test.lowerCase()));
					String value = node.getFirstChild().getNodeValue();
					if (MailProfileElement.account.lowerCase().equals(node.getNodeName())) mailSettings.setAccount(value);
	            	else if(MailProfileElement.password.lowerCase().equals(node.getNodeName())) mailSettings.setPassword(value);
				}
				if (mailSettings.getAccount()!=null && mailSettings.getPassword() != null) mailSettings.setTestMail(Boolean.TRUE);
			}
			
		}
	}

	private static void pasePOP3OrIMAP(Element mail, Y7MessageMailSettings mailSettings) {
		NodeList mailPropertys = mail.getChildNodes();
		for (int j = 0; j < mailPropertys.getLength(); j++) {
			Node mailProperty = mailPropertys.item(j);
			if (mailProperty.getNodeType() != Node.ELEMENT_NODE) continue;
			for (Node node = mailProperty.getFirstChild(); node != null; node = node.getNextSibling()) {  
		        if (node.getNodeType() == Node.ELEMENT_NODE) {  
		            String name = node.getNodeName();  
		            if (node.getFirstChild() ==null) {
		            	throw new IllegalArgumentException(String.format("Article %s mail property '%s'  value must not null", i + 1 , ));
		            	continue;
		            }
		            String value = node.getFirstChild().getNodeValue();  
		            if (MailProfileElement.incoming.lowerCase().equals(mailProperty.getNodeName())) {
		            	if (MailProfileElement.server.lowerCase().equals(name)) mailSettings.setServer(value);
		            	else if(MailProfileElement.port.lowerCase().equals(name)) mailSettings.setServerPort(value);
		            	else if(MailProfileElement.ssl.lowerCase().equals(name)) mailSettings.setServerSSL(Boolean.valueOf(value));
		            } else if (MailProfileElement.outgoing.lowerCase().equals(mailProperty.getNodeName())) {
		            	if (MailProfileElement.server.lowerCase().equals(name)) mailSettings.setSmtp(value);
		            	else if(MailProfileElement.port.lowerCase().equals(name)) mailSettings.setSmtpPort(value);
		            	else if(MailProfileElement.ssl.lowerCase().equals(name)) mailSettings.setSmtpSSL(Boolean.valueOf(value));
		            } else if(MailProfileElement.test.lowerCase().equals(mailProperty.getNodeName())) {
		            	if (MailProfileElement.account.lowerCase().equals(name)) mailSettings.setAccount(value);
		            	else if (MailProfileElement.password.lowerCase().equals(name)) mailSettings.setPassword(value);
		            }
		            if (mailSettings.getAccount()!=null && mailSettings.getPassword() !=null) mailSettings.setTestMail(Boolean.TRUE);
		        }  
		    }  
		}
	}

Analytical sibling node:

for (Node node = currentNode.getFirstChild(); node != null; node = node.getNextSibling()){
  //TODO do something
}

For example, when parentNode is <mails> element, then node.getNextSibling () get all the <mail> element.

© 著作权归作者所有

Nathans
粉丝 7
博文 18
码字总数 28409
作品 0
成都
程序员
私信 提问
Java SAX tutorial

Java SAX tutorial shows how to use Java SAX API to read and validate XML documents. SAX SAX (Simple API for XML) is an event-driven algorithm for parsing XML documents. SAX is a......

HelloRookie
2018/09/12
0
0
java.lang.IllegalStateException: Failed to load ApplicationContext

用junit4进行单元测试一直报错,我快疯啦,跪求指导~~~~ 2017-06-07-16-37-29 [INFO] [main] [XmlBeanDefinitionReader_316] - Loading XML bean definitions from class path resource [app......

爱新觉罗扈
2017/06/07
3.5K
3
spring依赖注入失败,找不到applicationContext,实在找不到原因了,网上说的我都看了,还是没用

具体错误: java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLo......

麦秆菊
2016/12/28
671
3
Apache POI 3.5 发布

这是一个主要的发行版本,值得关注的变化包括: POI-SS - Java API To Access Microsoft Excel Format Files * This common interface allows access to HSSF (binary file format, .xls) an......

红薯
2009/10/06
2.1K
0
PMD 5.4.3 和 5.3.8 发布,Java 程序代码检查工具

PMD 5.4.3 和 5.3.8 发布了,PMD 是一款采用 BSD 协议发布的 Java 程序代码检查工具。该工具可以做到检查 Java 代码中是否含有未使用的变量、是否含有空的抓取块、是否含有不必要的对象等。该...

局长
2016/11/05
1K
2

没有更多内容

加载失败,请刷新页面

加载更多

JWT学习总结

官方 https://jwt.io 英文原版 https://www.ietf.org/rfc/rfc7519.txt 或 https://tools.ietf.org/html/rfc7519 中文翻译 https://www.jianshu.com/p/10f5161dd9df 1. 概述 JSON Web Token(......

冷基
27分钟前
2
0
AOP的学习(1)

AOP 理解AOP编程思想(面向方法、面向切面) spring AOP的概念 方面 -- 功能 目标 -- 原有方法 通知 -- 对原有方法增强的方法 连接点 -- 可以用来连接通知的地方(方法) 切入点 -- 将用来插入...

太猪-YJ
今天
4
0
一张图看懂亮度、明度、光度、光亮度、明亮度

亮度、明度、光亮度,Luminance和Brightness、lightness其实都是一个意思,只是起名字太难了。 提出一个颜色模型后,由于明度的取值与别人的不同,为了表示区别所以就另想一个词而已。 因此在...

linsk1998
昨天
8
0
Python应用:python链表示例

前言 python链表应用源码示例,需要用到python os模块方法、函数和类的应用。 首先,先简单的来了解下什么是链表?链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是...

python小白1
昨天
4
0
Source Insight加载源码

Source Insight是一个图形化的源代码查看工具(当然也可以作为编译工具)。如果一个项目的源代码较多,此工具可以很方便地查找到源代码自建的依赖关系。 1.创建工程 下图为Snort源代码的文件...

天王盖地虎626
昨天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部