1.POM文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.iteye.xujava</groupId> <artifactId>account-persist</artifactId> <version>1.0.0</version> <packaging>jar</packaging> <name>account-persist</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <springframework.version>2.5.6</springframework.version> </properties> <dependencies> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${springframework.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> <scope>test</scope> </dependency> </dependencies> <build> <testResources> <testResource> <directory>src/test/resources</directory> <filtering>true</filtering> </testResource> </testResources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
2.在src/main/java中包com.iteye.xujava.account.persist下创建以下四个Java文件
package com.iteye.xujava.account.persist;
public class Account {
private String id;
private String name;
private String email;
private String password;
private boolean activated;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
}
package com.iteye.xujava.account.persist;
public class AccountPersistException extends Exception {
private static final long serialVersionUID = 7208989305935509389L;
public AccountPersistException(String message) {
super(message);
}
public AccountPersistException(String message, Throwable throwable) {
super(message, throwable);
}
}
package com.iteye.xujava.account.persist;
public interface AccountPersistService {
Account createAccount(Account account) throws AccountPersistException;
Account readAccount(String id) throws AccountPersistException;
Account updateAccount(Account account) throws AccountPersistException;
void deleteAccount(String id) throws AccountPersistException;
}
package com.iteye.xujava.account.persist;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class AccountPersistServiceImpl implements AccountPersistService {
private String file;
private SAXReader reader = new SAXReader();
private static final String ELEMENT_ROOT = "account-persist";
private static final String ELEMENT_ACCOUNTS = "accounts";
private static final String ELEMENT_ACCOUNT = "account";
private static final String ELEMENT_ACCOUNT_ID = "id";
private static final String ELEMENT_ACCOUNT_NAME = "name";
private static final String ELEMENT_ACCOUNT_EMAIL = "email";
private static final String ELEMENT_ACCOUNT_PASSWORD = "password";
private static final String ELEMENT_ACCOUNT_ACTIVATED = "activated";
public Account createAccount(Account account) throws AccountPersistException {
Document doc = readDocument();
Element accountsEle = doc.getRootElement().element(ELEMENT_ACCOUNTS);
accountsEle.add(buildAccountElement(account));
writeDocument(doc);
return account;
}
@SuppressWarnings("unchecked")
public Account readAccount(String id) throws AccountPersistException {
Document doc = readDocument();
Element accountsEle = doc.getRootElement().element(ELEMENT_ACCOUNTS);
for (Element accountEle : (List<Element>) accountsEle.elements()) {
if (accountEle.elementText(ELEMENT_ACCOUNT_ID).equals(id)) {
return buildAccount(accountEle);
}
}
return null;
}
public Account updateAccount(Account account) throws AccountPersistException {
if (readAccount(account.getId()) != null) {
deleteAccount(account.getId());
return createAccount(account);
}
return null;
}
@SuppressWarnings("unchecked")
public void deleteAccount(String id) throws AccountPersistException {
Document doc = readDocument();
Element accountsEle = doc.getRootElement().element(ELEMENT_ACCOUNTS);
for (Element accountEle : (List<Element>) accountsEle.elements()) {
if (accountEle.elementText(ELEMENT_ACCOUNT_ID).equals(id)) {
accountEle.detach();
writeDocument(doc);
return;
}
}
}
private Account buildAccount(Element element) {
Account account = new Account();
account.setId(element.elementText(ELEMENT_ACCOUNT_ID));
account.setName(element.elementText(ELEMENT_ACCOUNT_NAME));
account.setEmail(element.elementText(ELEMENT_ACCOUNT_EMAIL));
account.setPassword(element.elementText(ELEMENT_ACCOUNT_PASSWORD));
account.setActivated(element.elementText(ELEMENT_ACCOUNT_ACTIVATED).equals("true") ? true : false);
return account;
}
private Element buildAccountElement(Account account) {
Element element = DocumentFactory.getInstance().createElement(ELEMENT_ACCOUNT);
element.addElement(ELEMENT_ACCOUNT_ID).setText(account.getId());
element.addElement(ELEMENT_ACCOUNT_NAME).setText(account.getName());
element.addElement(ELEMENT_ACCOUNT_EMAIL).setText(account.getEmail());
element.addElement(ELEMENT_ACCOUNT_PASSWORD).setText(account.getPassword());
element.addElement(ELEMENT_ACCOUNT_ACTIVATED).setText(account.isActivated() ? "true" : "false");
return element;
}
private Document readDocument() throws AccountPersistException {
File dataFile = new File(file);
if (!dataFile.exists()) {
dataFile.getParentFile().mkdirs();
Document doc = DocumentFactory.getInstance().createDocument();
Element rootEle = doc.addElement(ELEMENT_ROOT);
rootEle.addElement(ELEMENT_ACCOUNTS);
writeDocument(doc);
}
try {
return reader.read(new File(file));
} catch (DocumentException e) {
throw new AccountPersistException("不能读取xml文件", e);
}
}
private void writeDocument(Document doc) throws AccountPersistException {
Writer out = null;
try {
out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
writer.write(doc);
} catch (IOException e) {
throw new AccountPersistException("不能写入xml文件", e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
throw new AccountPersistException("不能关闭xml文件", e);
}
}
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
}
3.在src/main/resources目录下创建以下两个文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:service.properties" /> </bean> <bean id="accountPersistService" class="com.iteye.xujava.account.persist.AccountPersistServiceImpl"> <property name="file" value="${persist.file}" /> </bean> </beans>
persist.file=E:/mavenspace/account-persist/target/test-classes/persist-data.xml
4.在src/test/java中包com.iteye.xujava.account.persist下创建
package com.iteye.xujava.account.persist;
import static org.junit.Assert.*;
import java.io.File;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AccountPersistServiceTest
{
private AccountPersistService service;
@Before
public void prepare()
throws Exception
{
File persistDataFile = new File ( "target/test-classes/persist-data.xml" );
if ( persistDataFile.exists() )
{
persistDataFile.delete();
}
ApplicationContext ctx = new ClassPathXmlApplicationContext( "account-persist.xml" );
service = (AccountPersistService) ctx.getBean( "accountPersistService" );
Account account = new Account();
account.setId("xuj");
account.setName("Xuj");
account.setEmail("xuj@changeme.com");
account.setPassword("this_should_be_encrypted");
account.setActivated(true);
service.createAccount(account);
}
@Test
public void testReadAccount()
throws Exception
{
Account account = service.readAccount( "xuj" );
assertNotNull( account );
assertEquals( "xuj", account.getId() );
assertEquals( "Xuj", account.getName() );
assertEquals( "xuj@changeme.com", account.getEmail() );
assertEquals( "this_should_be_encrypted", account.getPassword() );
assertTrue( account.isActivated() );
}
@Test
public void testDeleteAccount()
throws Exception
{
assertNotNull( service.readAccount( "xuj" ) );
service.deleteAccount( "xuj" );
assertNull( service.readAccount( "xuj" ) );
}
@Test
public void testCreateAccount()
throws Exception
{
assertNull( service.readAccount( "mike" ) );
Account account = new Account();
account.setId("mike");
account.setName("Mike");
account.setEmail("mike@changeme.com");
account.setPassword("this_should_be_encrypted");
account.setActivated(true);
service.createAccount(account);
assertNotNull( service.readAccount( "mike" ));
}
@Test
public void testUpdateAccount()
throws Exception
{
Account account = service.readAccount( "xuj" );
account.setName("Xuj 1");
account.setEmail("xuj1@changeme.com");
account.setPassword("this_still_should_be_encrypted");
account.setActivated(false);
service.updateAccount( account );
account = service.readAccount( "xuj" );
assertEquals( "Xuj 1", account.getName() );
assertEquals( "xuj1@changeme.com", account.getEmail() );
assertEquals( "this_still_should_be_encrypted", account.getPassword() );
assertFalse( account.isActivated() );
}
}
5.运行mvn clean test
6.运行mvn clean install