1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
| package com.example.dao;
import java.io.File;
import java.io.StringReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.example.model.User;
public class UserDAOXML implements UserDAO {
// Constants
// ----------------------------------------------------------------------------------
private static final String XPATH_FIND_BY_ID = "//user[id=$id]";
private static final String XPATH_FIND_BY_EMAIL_AND_PASSWORD = "//user[email=$email and password=$password]";
private static final String XPATH_LIST = "//user";
private static final String XPATH_UPDATE = "//user[id=$id]";
private static final String XPATH_DELETE = "//user[id=$id]";
private static final String XPATH_EXIST_EMAIL = "//user[email=$email]";
private static final String XPATH_CHANGE_PASSWORD = "//user[id=$id]/password";
private static final String XPATH_MAX_VALUE = "//user/id";
// Vars
// ---------------------------------------------------------------------------------------
private File xmlFile = null;
private DAOFactory daoFactory = null;
// Constructors
// -------------------------------------------------------------------------------
public UserDAOXML(DAOFactory daoFactory) {
// Getting the XML file name at the initialization
this.xmlFile = new File("C:/Temp.", "users.xml");
this.daoFactory = daoFactory;
}
// Actions
// ------------------------------------------------------------------------------------
public User find(Long id) throws DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Getting the user
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "id"), id);
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(resolver);
XPathExpression xpe = xPath.compile(XPATH_FIND_BY_ID);
Node userNode = (Node) xpe.evaluate(document, XPathConstants.NODE);
User user = mapUser(userNode);
return user;
}
} catch (Exception ex) {
throw new DAOException(ex);
}
return null;
}
public User find(String email, String password) throws DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Getting the user
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "email"), email);
resolver.addVariable(new QName(null, "password"), password);
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(resolver);
XPathExpression xpe = xPath.compile(XPATH_FIND_BY_EMAIL_AND_PASSWORD);
Node userNode = (Node) xpe.evaluate(document, XPathConstants.NODE);
User user = mapUser(userNode);
return user;
}
} catch (Exception ex) {
throw new DAOException(ex);
}
return null;
}
public List<User> list() throws DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Getting all users
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xpe = xPath.compile(XPATH_LIST);
NodeList listUserNode = (NodeList) xpe.evaluate(document, XPathConstants.NODESET);
List<User> listUser = new ArrayList<User>();
// Iterate through all users
for (int i = 0; i < listUserNode.getLength(); i++) {
Node userNode = listUserNode.item(i);
User user = mapUser(userNode);
listUser.add(user);
}
return listUser;
}
} catch (Exception ex) {
throw new DAOException(ex);
}
return null;
}
public void create(User user) throws IllegalArgumentException, DAOException {
try {
UserXMLTransformer xmlTransformer = new UserXMLTransformer();
// Checking if the file exist
if (!xmlFile.exists()) {
// If file does not exist in the database path, create and store
// an empty User node
xmlTransformer.writeFile(xmlFile, new ArrayList<User>());
}
// Create the XML document by loading the file
List<User> listUser = xmlTransformer.xmlToObject(xmlFile);
// Getting the maximum Id based on the XML data already stored
String xml = xmlTransformer.objectToXml(listUser);
long maxId = getMaxValue(xml);
// Adding Id column. Auto generated column
user.setId(maxId + 1);
listUser.add(user);
// Saving the file after adding the new user node
xmlTransformer.writeFile(xmlFile, listUser);
} catch (XPathExpressionException ex) {
throw new DAOException(ex);
}
}
public void update(User user) throws IllegalArgumentException, DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Then get the node using the standard javax.xml.xpath APIs.
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "id"), user.getId());
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(resolver);
XPathExpression xpe = xPath.compile(XPATH_UPDATE);
Node userNode = (Node) xpe.evaluate(document, XPathConstants.NODE);
if (userNode != null) {
userNode = updateNode(userNode, user);
// And then use the javax.xml.transform APIs to write it
// back out.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(xmlFile));
}
} else {
throw new Exception("Database file does not exist in the folder");
}
} catch (Exception ex) {
throw new DAOException(ex);
}
}
public void delete(User user) throws DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Then get the node using the standard javax.xml.xpath APIs.
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "id"), user.getId());
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(resolver);
XPathExpression xpe = xPath.compile(XPATH_DELETE);
Node userNode = (Node) xpe.evaluate(document, XPathConstants.NODE);
if (userNode != null) {
userNode.getParentNode().removeChild(userNode);
// And then use the javax.xml.transform APIs to write it
// back out.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(xmlFile));
}
} else {
throw new Exception("Database file does not exist in the folder");
}
} catch (Exception ex) {
throw new DAOException(ex);
}
}
public boolean existEmail(String email) throws DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Getting the user
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "email"), email);
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(resolver);
XPathExpression xpe = xPath.compile(XPATH_EXIST_EMAIL);
Node userNode = (Node) xpe.evaluate(document, XPathConstants.NODE);
return (userNode != null) ? true : false;
}
} catch (Exception ex) {
throw new DAOException(ex);
}
return false;
}
public void changePassword(User user) throws DAOException {
try {
// Checking if the file exist
if (xmlFile.exists()) {
// Use the standard org.w3c.dom APIs to get a DOM.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document document = dbf.newDocumentBuilder().parse(xmlFile);
// Then get the node using the standard javax.xml.xpath APIs.
SimpleVariableResolver resolver = new SimpleVariableResolver();
resolver.addVariable(new QName(null, "id"), user.getId());
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(resolver);
XPathExpression xpe = xPath.compile(XPATH_CHANGE_PASSWORD);
Node passwordNode = (Node) xpe.evaluate(document, XPathConstants.NODE);
if (passwordNode != null) {
passwordNode.setTextContent(user.getPassword());
// And then use the javax.xml.transform APIs to write it
// back out.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(new DOMSource(document), new StreamResult(xmlFile));
}
} else {
throw new Exception("Database file does not exist in the folder");
}
} catch (Exception ex) {
throw new DAOException(ex);
}
}
private long getMaxValue(String xml) throws XPathExpressionException {
long maxId = 0;
InputSource source = new InputSource(new StringReader(xml));
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xpe = xPath.compile(XPATH_MAX_VALUE);
NodeList listUserNode = (NodeList) xpe.evaluate(source, XPathConstants.NODESET);
for (int i = 0; i < listUserNode.getLength(); i++) {
Node employeeIdNode = listUserNode.item(i);
String strId = employeeIdNode.getTextContent();
long id = Long.parseLong(strId);
maxId = (id > maxId) ? id : maxId;
}
return maxId;
}
private Node updateNode(Node userNode, User user) {
// Iterate through all properties of an employee
NodeList children = userNode.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node node = children.item(j);
if (node.getNodeName().equals("email")) {
node.setTextContent(user.getEmail());
} else if (node.getNodeName().equals("password")) {
node.setTextContent(user.getPassword());
} else if (node.getNodeName().equals("firstname")) {
node.setTextContent(user.getFirstname());
} else if (node.getNodeName().equals("lastname")) {
node.setTextContent(user.getLastname());
} else if (node.getNodeName().equals("birthdate")) {
node.setTextContent((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z")).format(user.getBirthdate()));
}
}
return userNode;
}
private User mapUser(Node userNode) throws ParseException {
User user = new User();
// Iterate through all properties of a user
NodeList children = userNode.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node node = children.item(j);
if (node.getNodeName().equals("id")) {
user.setId(Long.parseLong(node.getTextContent()));
} else if (node.getNodeName().equals("email")) {
user.setEmail(node.getTextContent());
} else if (node.getNodeName().equals("password")) {
user.setPassword(node.getTextContent());
} else if (node.getNodeName().equals("firstname")) {
user.setFirstname(node.getTextContent());
} else if (node.getNodeName().equals("lastname")) {
user.setLastname(node.getTextContent());
} else if (node.getNodeName().equals("birthdate")) {
user.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse(node.getTextContent()));
}
}
return user;
}
} |
Partager