Java parsing XML file

原创
2016/08/30 15:28
阅读数 10

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.

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部