Java parsing XML file

XML introduction

  XML 指可擴展標記語言,XML 被設計用來傳輸和存儲數據。java

  基於XML解析方式有兩種:node

    SAX:基於事件流的解析;
    DOM:基於XML文檔樹結構的解析;
New to XML basics:http://www.ibm.com/developerworks/cn/xml/x-newxml/服務器

 

Email xml profile:session

<?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:dom

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

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

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

org.w3c.dom.Node:a node.ui

 

Use DOM Parse xml code:this

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.

相關文章
相關標籤/搜索