From b8ece51dbe531449e372d8377a92a68e66f44c27 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 8 Jun 2012 09:47:44 -0700 Subject: [PATCH 01/87] Initial commit --- .gitignore | 6 ++++++ README.md | 4 ++++ 2 files changed, 10 insertions(+) create mode 100644 .gitignore create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..0f182a034 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +*.class + +# Package Files # +*.jar +*.war +*.ear diff --git a/README.md b/README.md new file mode 100644 index 000000000..816af7f1a --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +ch.eitchnet.java.xmlpers +======================== + +Generic Java XML persistence layer. Implemented to be light-weight and simple to use \ No newline at end of file From 49569253290f57a2f78ccf1cc15b52c7050fed83 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 8 Jun 2012 19:04:35 +0200 Subject: [PATCH 02/87] [New] Initial commit of the XML Persistence implementation This is a rudimentary implementation which works in that objects can be written to the DB, read back and helper methods like keySet, size are also implemented --- .gitignore | 3 + config/log4j.properties | 12 + src/ch/eitchnet/xmlpers/XmlDao.java | 66 +++ src/ch/eitchnet/xmlpers/XmlDaoFactory.java | 20 + src/ch/eitchnet/xmlpers/XmlFilePersister.java | 428 ++++++++++++++++++ .../xmlpers/XmlPersistenceExecption.java | 23 + .../xmlpers/XmlPersistenceHandler.java | 120 +++++ .../xmlpers/XmlPersistencePathBuilder.java | 144 ++++++ .../xmlpers/XmlPersistenceTransaction.java | 300 ++++++++++++ .../xmlpers/test/XmlPersistenceTest.java | 311 +++++++++++++ .../plugin/xmlpers/test/impl/MyClass.java | 106 +++++ .../plugin/xmlpers/test/impl/MyClassDao.java | 126 ++++++ .../xmlpers/test/impl/MyDaoFactory.java | 34 ++ 13 files changed, 1693 insertions(+) create mode 100644 config/log4j.properties create mode 100644 src/ch/eitchnet/xmlpers/XmlDao.java create mode 100644 src/ch/eitchnet/xmlpers/XmlDaoFactory.java create mode 100644 src/ch/eitchnet/xmlpers/XmlFilePersister.java create mode 100644 src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java create mode 100644 src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java create mode 100644 src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java create mode 100644 src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java create mode 100644 test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java create mode 100644 test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java create mode 100644 test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java create mode 100644 test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java diff --git a/.gitignore b/.gitignore index 0f182a034..c77d8a98c 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ *.jar *.war *.ear + +# Project files +tmp diff --git a/config/log4j.properties b/config/log4j.properties new file mode 100644 index 000000000..a745f967b --- /dev/null +++ b/config/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger = info, stdout, file + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n + +log4j.appender.file=org.apache.log4j.RollingFileAppender +log4j.appender.file.File=${user.dir}/logs/app.log +log4j.appender.file.MaxFileSize=10000KB +log4j.appender.file.MaxBackupIndex=0 +log4j.appender.file.layout=org.apache.log4j.PatternLayout +log4j.appender.file.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n \ No newline at end of file diff --git a/src/ch/eitchnet/xmlpers/XmlDao.java b/src/ch/eitchnet/xmlpers/XmlDao.java new file mode 100644 index 000000000..d1dd3c456 --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlDao.java @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2010 - 2011 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ +package ch.eitchnet.xmlpers; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.ContentHandler; + +/** + * @author Robert von Burg + * + */ +public interface XmlDao { + + /** + * @param object + * @return + */ + public String getType(T object); + + /** + * @param object + * @return + */ + public String getSubType(T object); + + /** + * @param object + * @return + */ + public String getId(T object); + + /** + * + * @param object + * @param domImplementation + * @return + */ + // XXX think about returning a document, instead of an element, or use document as input + public Document serializeToDom(T object, DOMImplementation domImplementation); + + /** + * @param element + * @return + */ + public T parseFromDom(Element element); + + /** + * @param object + * @param contentHandler + */ + // XXX Use the XMLSerializer object for serializing to SAX... + public void serializeToSax(T object, ContentHandler contentHandler); + + // XXX parse from SAX is missing... + +} diff --git a/src/ch/eitchnet/xmlpers/XmlDaoFactory.java b/src/ch/eitchnet/xmlpers/XmlDaoFactory.java new file mode 100644 index 000000000..81f929572 --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlDaoFactory.java @@ -0,0 +1,20 @@ +/* + * Copyright (c) 2010 - 2011 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ +package ch.eitchnet.xmlpers; + +/** + * @author Robert von Burg + * + */ +public interface XmlDaoFactory { + + public XmlDao getDao(String type); +} diff --git a/src/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/ch/eitchnet/xmlpers/XmlFilePersister.java new file mode 100644 index 000000000..c02acfb25 --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlFilePersister.java @@ -0,0 +1,428 @@ +package ch.eitchnet.xmlpers; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; + +import org.apache.log4j.Logger; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import ch.eitchnet.utils.helper.FileHelper; + +import com.sun.org.apache.xml.internal.serialize.OutputFormat; +import com.sun.org.apache.xml.internal.serialize.XMLSerializer; + +/** + *@author Robert von Burg + * + */ +public class XmlFilePersister { + + // + private static final String XML_DEFAULT_ENCODING = "UTF-8"; + + private static final Logger logger = Logger.getLogger(XmlFilePersister.class); + + private boolean verbose; + private XmlPersistencePathBuilder xmlPathHelper; + + /** + * @param xmlPathHelper + * @param verbose + */ + public XmlFilePersister(XmlPersistencePathBuilder xmlPathHelper, boolean verbose) { + this.xmlPathHelper = xmlPathHelper; + this.verbose = verbose; + } + + /** + * @param type + * @param subType + * @param id + * @param document + */ + public void saveOrUpdate(String type, String subType, String id, Document document) { + + File pathF; + if (subType != null) + pathF = xmlPathHelper.getPathF(type, subType, id); + else + pathF = xmlPathHelper.getPathF(type, id); + + // if this is a new file, then check create parents, if the don't exist + if (!pathF.exists()) { + File parentFile = pathF.getParentFile(); + if (!parentFile.exists() && !parentFile.mkdirs()) { + throw new XmlPersistenceExecption("Could not create path for " + type + " / " + subType + " / " + id + + " at " + pathF.getAbsolutePath()); + } + } + + if (verbose) + logger.info("Persisting " + type + " / " + subType + " / " + id + " to " + pathF.getAbsolutePath() + "..."); + + BufferedOutputStream outStream = null; + try { + + outStream = new BufferedOutputStream(new FileOutputStream(pathF)); + + OutputFormat outputFormat = new OutputFormat("XML", XML_DEFAULT_ENCODING, true); + outputFormat.setIndent(1); + outputFormat.setIndenting(true); + //of.setDoctype(null, null); + + XMLSerializer serializer = new XMLSerializer(outStream, outputFormat); + serializer.asDOMSerializer(); + serializer.serialize(document); + outStream.flush(); + + } catch (Exception e) { + throw new XmlPersistenceExecption("Could not persist object " + type + " / " + subType + " / " + id + + " to " + pathF.getAbsolutePath(), e); + } finally { + if (outStream != null) { + try { + outStream.close(); + } catch (IOException e) { + logger.error(e, e); + } + } + } + + if (verbose) + logger.info("Done."); + } + + /** + * @param type + * @param subType + * @param id + */ + public void remove(String type, String subType, String id) { + + File pathF; + if (subType != null) + pathF = xmlPathHelper.getPathF(type, subType, id); + else + pathF = xmlPathHelper.getPathF(type, id); + + if (verbose) + logger.info("Remove persistence file for " + type + " / " + subType + " / " + id + " from " + + pathF.getAbsolutePath() + "..."); + + if (!pathF.exists()) { + logger.error("Persistence file for " + type + " / " + subType + " / " + id + " does not exist at " + + pathF.getAbsolutePath()); + } else if (!pathF.delete()) { + throw new XmlPersistenceExecption("Could not delete persistence file for " + type + " / " + subType + " / " + + id + " at " + pathF.getAbsolutePath()); + } + + if (verbose) + logger.info("Done."); + } + + /** + * @param type + * @param subType + */ + public void removeAll(String type, String subType) { + + File pathF; + if (subType == null) + pathF = xmlPathHelper.getPathF(type); + else + pathF = xmlPathHelper.getPathF(type, subType); + + if (!pathF.exists()) { + if (subType == null) + logger.error("Path for " + type + " at " + pathF.getAbsolutePath() + + " does not exist, so removing not possible!"); + else + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so removing not possible!"); + + } else { + + File[] filesToRemove = pathF.listFiles(); + boolean removed = FileHelper.deleteFiles(filesToRemove, verbose); + + if (!removed) { + if (subType == null) + throw new XmlPersistenceExecption("Could not delete persistence files for " + type + " at " + + pathF.getAbsolutePath()); + + throw new XmlPersistenceExecption("Could not delete persistence files for " + type + " / " + subType + + " at " + pathF.getAbsolutePath()); + } + } + } + + /** + * + * @param type + * @param subType + * + * @return + */ + public Set queryKeySet(String type, String subType) { + + // if a sub type is required, then it's simple: + if (subType != null) { + + File pathF = this.xmlPathHelper.getPathF(type, subType); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so no objects exist!"); + return Collections.emptySet(); + } + + Set keySet = new HashSet(); + for (File f : pathF.listFiles()) { + String name = f.getName(); + keySet.add(name.substring(0, name.length() - XmlPersistencePathBuilder.FILE_EXT.length())); + } + + if (verbose) + logger.info("Found " + keySet.size() + " elements for " + type + " / " + subType); + + return keySet; + } + + // otherwise we need to iterate any existing subTypes and create a combined key set + File pathF = this.xmlPathHelper.getPathF(type); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so no objects exist!"); + return Collections.emptySet(); + } + + Set keySet = new HashSet(); + + File[] subTypeFiles = pathF.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isFile()) { + keySet.add(xmlPathHelper.getId(subTypeFile.getName())); + } else { + + for (File f : subTypeFile.listFiles()) { + keySet.add(xmlPathHelper.getId(f.getName())); + } + } + } + + if (verbose) + logger.info("Found " + keySet.size() + " elements for " + type); + + return keySet; + } + + /** + * + * @param type + * @param subType + * + * @return + */ + public long querySize(String type, String subType) { + + // if a sub type is required, then it's simple: + if (subType != null) { + + File pathF = this.xmlPathHelper.getPathF(type, subType); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so no objects exist!"); + return 0l; + } + + int length = pathF.listFiles().length; + + if (verbose) + logger.info("Found " + length + " elements for " + type + " / " + subType); + + return length; + } + + // otherwise we need to iterate any existing sub types and + // return the size of the combined collection + + File pathF = this.xmlPathHelper.getPathF(type); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so no objects exist!"); + return 0l; + } + + long numberOfFiles = 0l; + + File[] subTypeFiles = pathF.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isFile()) { + numberOfFiles++; + } else { + numberOfFiles += subTypeFile.listFiles().length; + } + } + + if (verbose) + logger.info("Found " + numberOfFiles + " elements for " + type); + + return numberOfFiles; + } + +// XXX think about allowing paged loading... +// /** +// * @param type +// * @param subType +// * @param firstResult +// * @param maxResults +// * +// * @return +// */ +// public List queryFrom(String type, String subType, int firstResult, int maxResults) { +// +// File pathF = this.xmlPathHelper.getPathF(type, subType); +// if (!pathF.exists()) { +// logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() +// + " does not exist, so no objects exist!"); +// return Collections.emptyList(); +// } +// +// File[] listFiles = pathF.listFiles(); +// Arrays.sort(listFiles, new Comparator() { +// +// @Override +// public int compare(File file1, File file2) { +// return file1.getName().compareTo(file2.getName()); +// } +// }); +// +// // make sure positions are not illegal +// int size = listFiles.length; +// if (firstResult >= size) +// return Collections.emptyList(); +// +// if ((firstResult + maxResults) > size) +// maxResults = size - firstResult; +// +// File[] result = Arrays.copyOfRange(listFiles, firstResult, firstResult + maxResults); +// +// List list = new ArrayList(); +// for (File f : result) { +// list.add(loadObject(clazz, f)); +// } +// +// return list; +// } + + /** + * + * @param type + * @param subType + * + * @return + */ + public List queryAll(String type, String subType, DocumentBuilder docBuilder) { + + // if a sub type is required, then it's simple: + if (subType != null) { + + File pathF = this.xmlPathHelper.getPathF(type, subType); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so no objects exist!"); + return Collections.emptyList(); + } + + List list = new ArrayList(); + for (File subTypeF : pathF.listFiles()) { + list.add(parseFile(subTypeF, docBuilder)); + } + + if (verbose) + logger.info("Loaded " + list.size() + " elements for " + type + " / " + subType); + + return list; + } + + // otherwise we need to iterate any existing sub types and + // return those elements as well + + File pathF = this.xmlPathHelper.getPathF(type); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + + " does not exist, so no objects exist!"); + return Collections.emptyList(); + } + + List list = new ArrayList(); + + File[] subTypeFiles = pathF.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isFile()) { + list.add(parseFile(subTypeFile, docBuilder)); + + } else { + for (File subTypeF : subTypeFile.listFiles()) { + list.add(parseFile(subTypeF, docBuilder)); + } + } + } + + if (verbose) + logger.info("Loaded " + list.size() + " elements for " + type); + + return list; + } + + /** + * + * @param type + * @param subType + * @param id + * + * @return + */ + public Element queryById(String type, String subType, String id, DocumentBuilder docBuilder) { + + File pathF = this.xmlPathHelper.getPathF(type, subType, id); + if (!pathF.exists()) { + logger.error("Path for " + type + " / " + subType + " / " + id + " at " + pathF.getAbsolutePath() + + " does not exist, so object does not exist!"); + return null; + } + + return parseFile(pathF, docBuilder); + } + + /** + * @param subTypeF + * @return + */ + private Element parseFile(File subTypeF, DocumentBuilder docBuilder) { + try { + + Document document = docBuilder.parse(subTypeF); + return document.getDocumentElement(); + + } catch (SAXException e) { + throw new XmlPersistenceExecption("Failed to parse file " + subTypeF.getAbsolutePath(), e); + } catch (IOException e) { + throw new XmlPersistenceExecption("Failed to read file " + subTypeF.getAbsolutePath(), e); + } + } +} diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java b/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java new file mode 100644 index 000000000..868f7d83f --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java @@ -0,0 +1,23 @@ +package ch.eitchnet.xmlpers; + +/** + * @author Robert von Burg + */ +public class XmlPersistenceExecption extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** + * @param message + * @param cause + */ + public XmlPersistenceExecption(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message + */ + public XmlPersistenceExecption(String message) { + super(message); + } +} diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java new file mode 100644 index 000000000..0681a2c2a --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java @@ -0,0 +1,120 @@ +package ch.eitchnet.xmlpers; + +import org.apache.log4j.Logger; + +import ch.eitchnet.utils.helper.SystemHelper; +import ch.eitchnet.utils.objectfilter.ITransactionObject; +import ch.eitchnet.utils.objectfilter.ObjectFilter; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceHandler { + + /** + * + */ + public static final String CONFIG_VERBOSE = "ch.eitchnet.xmlpers.config.verbose"; + + /** + * + */ + public static final String CONFIG_BASEPATH = "ch.eitchnet.xmlpers.config.basepath"; + + /** + * + */ + public static final String CONFIG_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers.config.daoFactoryClass"; + + protected static final Logger logger = Logger.getLogger(XmlPersistenceHandler.class); + + protected boolean verbose; + protected ThreadLocal xmlPersistenceTxThreadLocal; + protected XmlFilePersister persister; + protected XmlDaoFactory xmlDaoFactory; + + /** + * + */ + public void initialize() { + + String basePath = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), CONFIG_BASEPATH, null); + verbose = SystemHelper.getPropertyBool(XmlPersistenceHandler.class.getSimpleName(), CONFIG_VERBOSE, + Boolean.FALSE).booleanValue(); + + // get class to use as transaction + String daoFactoryClassName = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), + CONFIG_DAO_FACTORY_CLASS, null); + try { + @SuppressWarnings("unchecked") + Class xmlDaoFactoryClass = (Class) Class.forName(daoFactoryClassName); + + xmlDaoFactory = xmlDaoFactoryClass.newInstance(); + + } catch (ClassNotFoundException e) { + throw new XmlPersistenceExecption("XmlDaoFactory class does not exist " + daoFactoryClassName, e); + } catch (Exception e) { + throw new XmlPersistenceExecption("Failed to load class " + daoFactoryClassName, e); + } + + XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(basePath); + persister = new XmlFilePersister(pathBuilder, verbose); + + // initialize the Thread local object which is used per transaction + xmlPersistenceTxThreadLocal = new ThreadLocal(); + } + + /** + * + */ + public XmlPersistenceTransaction openTx() { + + if (verbose) + logger.info("Opening new transaction..."); + + // make sure no previous filter exists + XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); + if (xmlPersistenceTx != null) + throw new XmlPersistenceExecption("Previous transaction not properly closed"); + + // set a new persistence transaction object + ObjectFilter objectFilter = new ObjectFilter(); + xmlPersistenceTx = new XmlPersistenceTransaction(); + xmlPersistenceTx.initialize(persister, xmlDaoFactory, objectFilter, verbose); + + this.xmlPersistenceTxThreadLocal.set(xmlPersistenceTx); + + return xmlPersistenceTx; + } + + /** + * + */ + public XmlPersistenceTransaction getTx() { + XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); + if (xmlPersistenceTx == null) + throw new XmlPersistenceExecption("No transaction currently open!"); + + return xmlPersistenceTx; + } + + /** + * + */ + public void commitTx() { + + if (verbose) + logger.info("Committing transaction..."); + + try { + XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); + if (xmlPersistenceTx == null) + throw new XmlPersistenceExecption("No transaction currently open!"); + + xmlPersistenceTx.commitTx(); + } finally { + this.xmlPersistenceTxThreadLocal.set(null); + } + } +} diff --git a/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java new file mode 100644 index 000000000..a8ed1d638 --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java @@ -0,0 +1,144 @@ +package ch.eitchnet.xmlpers; + +import java.io.File; +import java.io.IOException; + +import org.apache.log4j.Logger; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistencePathBuilder { + private static final Logger logger = Logger.getLogger(XmlPersistencePathBuilder.class); + + /** + * + */ + public static final String FILE_EXT = ".xml"; + + /** + * + */ + public static final int EXT_LENGTH = FILE_EXT.length(); + + private String basePath; + + /** + * @param basePath + */ + public XmlPersistencePathBuilder(String basePath) { + File basePathF = new File(basePath); + if (!basePathF.exists()) + throw new XmlPersistenceExecption("The database store path does not exist at " + + basePathF.getAbsolutePath()); + if (!basePathF.canWrite()) + throw new XmlPersistenceExecption("The database store path is not writeable at " + + basePathF.getAbsolutePath()); + + try { + this.basePath = basePathF.getCanonicalPath(); + } catch (IOException e) { + throw new XmlPersistenceExecption("Failed to build canonical path from " + basePath, e); + } + + logger.info("Using base path " + basePath); + } + + /** + * @param id + * @return + */ + public String getFilename(String id) { + return id.concat(FILE_EXT); + } + + /** + * @param filename + * @return + */ + public String getId(String filename) { + if (filename.charAt(filename.length() - EXT_LENGTH) != '.') + throw new XmlPersistenceExecption("The filename does not have a . at index " + + (filename.length() - EXT_LENGTH)); + + return filename.substring(0, filename.length() - EXT_LENGTH); + } + + /** + * @param type + * + * @return + */ + public String getPath(String type) { + + StringBuilder sb = new StringBuilder(basePath); + sb.append("/"); + sb.append(type); + + return sb.toString(); + } + + /** + * @param type + * + * @return + */ + public File getPathF(String type) { + return new File(getPath(type)); + } + + /** + * @param type + * @param subType + * @return + */ + public String getPath(String type, String subType) { + + StringBuilder sb = new StringBuilder(basePath); + sb.append("/"); + sb.append(type); + sb.append("/"); + sb.append(subType); + + return sb.toString(); + } + + /** + * @param type + * @param subType + * @return + */ + public File getPathF(String type, String subType) { + return new File(getPath(type, subType)); + } + + /** + * @param type + * @param subType + * @param id + * @return + */ + public String getPath(String type, String subType, String id) { + + StringBuilder sb = new StringBuilder(basePath); + sb.append("/"); + sb.append(type); + sb.append("/"); + sb.append(subType); + sb.append("/"); + sb.append(getFilename(id)); + + return sb.toString(); + } + + /** + * @param type + * @param subType + * @param id + * @return + */ + public File getPathF(String type, String subType, String id) { + return new File(getPath(type, subType, id)); + } +} diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java new file mode 100644 index 000000000..1e3dfeba8 --- /dev/null +++ b/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2010 - 2011 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ +package ch.eitchnet.xmlpers; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.log4j.Logger; +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import ch.eitchnet.utils.objectfilter.ITransactionObject; +import ch.eitchnet.utils.objectfilter.ObjectFilter; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceTransaction { + + private static final Logger logger = Logger.getLogger(XmlPersistenceTransaction.class); + + private boolean verbose; + private XmlFilePersister persister; + private XmlDaoFactory xmlDaoFactory; + private ObjectFilter objectFilter; + private DocumentBuilder docBuilder; + private DOMImplementation domImplementation; + + /** + * @param persister + * @param xmlDaoFactory + * @param objectFilter + */ + public void initialize(XmlFilePersister persister, XmlDaoFactory xmlDaoFactory, + ObjectFilter objectFilter, boolean verbose) { + this.persister = persister; + this.xmlDaoFactory = xmlDaoFactory; + this.objectFilter = objectFilter; + this.verbose = verbose; + } + + private DocumentBuilder getDocBuilder() { + if (docBuilder == null) { + try { + docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new XmlPersistenceExecption("Failed to load document builder: " + e.getLocalizedMessage(), e); + } + } + return docBuilder; + } + + /** + * @return + */ + protected DOMImplementation getDomImpl() { + if (domImplementation == null) + domImplementation = getDocBuilder().getDOMImplementation(); + return domImplementation; + } + + /* + * modifying methods + */ + + /** + * @param object + */ + public void add(ITransactionObject object) { + this.objectFilter.add(object); + } + + /** + * @param objects + */ + public void addAll(List objects) { + this.objectFilter.addAll(objects); + } + + /** + * @param object + */ + public void update(ITransactionObject object) { + this.objectFilter.update(object); + } + + /** + * @param objects + */ + public void updateAll(List objects) { + this.objectFilter.updateAll(objects); + } + + /** + * @param object + */ + public void remove(ITransactionObject object) { + this.objectFilter.remove(object); + } + + /** + * @param objects + */ + public void removeAll(List objects) { + this.objectFilter.removeAll(objects); + } + + /* + * querying methods + */ + + /** + * @param type + * @return + */ + public Set queryKeySet(String type) { + return queryKeySet(type, null); + } + + /** + * @param type + * @param subType + * @return + */ + public Set queryKeySet(String type, String subType) { + return this.persister.queryKeySet(type, subType); + } + + /** + * @param type + * @return + */ + public long querySize(String type) { + return querySize(type, null); + } + + /** + * @param type + * @param subType + * @return + */ + public long querySize(String type, String subType) { + return this.persister.querySize(type, subType); + } + + /** + * @param type + * @return + */ + public List queryAll(String type) { + return queryAll(type, null); + } + + /** + * @param type + * @param subType + * @return + */ + public List queryAll(String type, String subType) { + + // XXX ok, this is very ugly, but for starters it will have to do + XmlDao dao = xmlDaoFactory.getDao(type); + + List elements = this.persister.queryAll(type, subType, getDocBuilder()); + List objects = new ArrayList(elements.size()); + + for (Element element : elements) { + @SuppressWarnings("unchecked") + T object = (T) dao.parseFromDom(element); + objects.add(object); + } + + return objects; + } + + /** + * @param type + * @param id + * @return + */ + public T queryById(String type, String id) { + return queryById(type, null, id); + } + + /** + * @param type + * @param subType + * @param id + * @return + */ + public T queryById(String type, String subType, String id) { + + XmlDao dao = xmlDaoFactory.getDao(type); + + Element element = this.persister.queryById(type, subType, id, getDocBuilder()); + if (element == null) + throw new XmlPersistenceExecption("No object exists for " + type + " / " + subType + " / " + id); + + @SuppressWarnings("unchecked") + T object = (T) dao.parseFromDom(element); + + return object; + } + + /* + * committing + */ + + /** + * + */ + void commitTx() { + + if (verbose) + logger.info("Committing..."); + + Set keySet = objectFilter.keySet(); + if (keySet.isEmpty()) + return; + + for (String key : keySet) { + + XmlDao dao = xmlDaoFactory.getDao(key); + + List removed = objectFilter.getRemoved(key); + if (removed.isEmpty()) { + if (verbose) + logger.info("No objects removed in this tx."); + } else { + if (verbose) + logger.info(removed.size() + " objects removed in this tx."); + + for (ITransactionObject object : removed) { + + String type = dao.getType(object); + String subType = dao.getSubType(object); + String id = dao.getId(object); + + persister.remove(type, subType, id); + } + } + + List updated = objectFilter.getUpdated(key); + if (updated.isEmpty()) { + if (verbose) + logger.info("No objects updated in this tx."); + } else { + if (verbose) + logger.info(updated.size() + " objects updated in this tx."); + + for (ITransactionObject object : updated) { + + String type = dao.getType(object); + String subType = dao.getSubType(object); + String id = dao.getId(object); + + Document asDom = dao.serializeToDom(object, getDomImpl()); + persister.saveOrUpdate(type, subType, id, asDom); + } + } + + List added = objectFilter.getAdded(key); + if (added.isEmpty()) { + if (verbose) + logger.info("No objects added in this tx."); + } else { + if (verbose) + logger.info(updated.size() + " objects added in this tx."); + + for (ITransactionObject object : added) { + + String type = dao.getType(object); + String subType = dao.getSubType(object); + String id = dao.getId(object); + + Document asDom = dao.serializeToDom(object, getDomImpl()); + persister.saveOrUpdate(type, subType, id, asDom); + } + } + } + + objectFilter.clearCache(); + logger.info("Completed TX"); + } +} diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java new file mode 100644 index 000000000..be194acbe --- /dev/null +++ b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2010 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ + +/** + * + */ +package ch.eitchnet.featherlite.plugin.xmlpers.test; + +import java.io.File; +import java.util.List; +import java.util.Set; + +import org.apache.log4j.Logger; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.eitchnet.featherlite.plugin.xmlpers.test.impl.MyClass; +import ch.eitchnet.featherlite.plugin.xmlpers.test.impl.MyDaoFactory; +import ch.eitchnet.utils.helper.Log4jConfigurator; +import ch.eitchnet.utils.objectfilter.ITransactionObject; +import ch.eitchnet.xmlpers.XmlPersistenceExecption; +import ch.eitchnet.xmlpers.XmlPersistenceHandler; +import ch.eitchnet.xmlpers.XmlPersistenceTransaction; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceTest { + + private static final Logger logger = Logger.getLogger(XmlPersistenceTest.class.getName()); + + private static XmlPersistenceHandler persistenceHandler; + + /** + * @throws Exception + * if something goes wrong + */ + @BeforeClass + public static void init() throws Exception { + + try { + // set up log4j + Log4jConfigurator.configure(); + + String userDir = System.getProperty("user.dir"); + String basePath = userDir + "/tmp/testdb"; + File basePathF = new File(basePath); + if (!basePathF.exists() && !basePathF.mkdirs()) + Assert.fail("Could not create temporaray database store in " + basePathF.getAbsolutePath()); + + System.setProperty(XmlPersistenceHandler.CONFIG_BASEPATH, "tmp/testdb"); + System.setProperty(XmlPersistenceHandler.CONFIG_VERBOSE, "true"); + System.setProperty(XmlPersistenceHandler.CONFIG_DAO_FACTORY_CLASS, MyDaoFactory.class.getName()); + + persistenceHandler = new XmlPersistenceHandler(); + persistenceHandler.initialize(); + + logger.info("Initialized persistence handler."); + + } catch (Exception e) { + logger.error(e, e); + + throw new RuntimeException("Initialization failed: " + e.getLocalizedMessage(), e); + } + } + + /** + * + */ + @Test + public void testCreate() { + + try { + logger.info("Trying to create..."); + + // new instance + MyClass myClass = new MyClass("@id", "@name", "@subtype"); + + // persist instance + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + tx.add(myClass); + persistenceHandler.commitTx(); + + logger.info("Done creating."); + + } catch (Exception e) { + logger.error(e, e); + Assert.fail("Failed: " + e.getLocalizedMessage()); + } + } + + /** + * + */ + @Test + public void testRead() { + + try { + logger.info("Trying to read..."); + + // query MyClass with id @id + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); + logger.info("Found MyClass: " + myClass); + persistenceHandler.commitTx(); + + logger.info("Done reading."); + + } catch (Exception e) { + logger.error(e, e); + Assert.fail("Failed: " + e.getLocalizedMessage()); + } + } + + /** + * + */ + @Test + public void testUpdate() { + + try { + logger.info("Trying to update an object..."); + + // query the instance + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); + logger.info("Found MyClass: " + myClass); + + // modify the instance + myClass.setName("@name_modified"); + + // update the instance + tx.update(myClass); + persistenceHandler.commitTx(); + + logger.info("Done updating."); + + } catch (Exception e) { + logger.error(e, e); + Assert.fail("Failed: " + e.getLocalizedMessage()); + } + } + + /** + * + */ + @Test + public void testRemove() { + + logger.info("Trying to remove..."); + + // query the instance + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); + logger.info("Found MyClass: " + myClass); + + tx.remove(myClass); + persistenceHandler.commitTx(); + + logger.info("Done removing."); + } + + /** + * + */ + @Test(expected = XmlPersistenceExecption.class) + public void testQueryFail() { + + try { + logger.info("Trying to query removed object..."); + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); + logger.info("Found MyClass: " + myClass); + logger.info("Done querying removed object"); + } finally { + persistenceHandler.commitTx(); + } + } + + /** + * + */ + @Test + public void testReCreate() { + + try { + logger.info("Trying to recreate..."); + + // new instance + MyClass myClass = new MyClass("@id", "@name", "@subtype"); + + // persist instance + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + tx.add(myClass); + persistenceHandler.commitTx(); + + logger.info("Done creating."); + + } catch (Exception e) { + logger.error(e, e); + Assert.fail("Failed: " + e.getLocalizedMessage()); + } + } + +// /** +// * +// */ +// @Test +// public void testQueryFromTo() { +// Assert.fail("Not yet implemented"); +// } + + /** + * + */ + @Test + public void testQueryAll() { + + try { + + logger.info("Trying to query all..."); + + // query all + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + List list = tx.queryAll(MyClass.class.getName()); + Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); + + // also with subtype + list = tx.queryAll(MyClass.class.getName(), "@subtype"); + Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); + + // and now something useless + list = tx.queryAll(MyClass.class.getName(), "@inexistant"); + Assert.assertTrue("Expected no objects, found " + list.size(), list.size() == 0); + + logger.info("Done querying."); + + } finally { + persistenceHandler.commitTx(); + } + } + + /** + * + */ + @Test + public void testKeySet() { + + try { + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + + Set keySet = tx.queryKeySet(MyClass.class.getName()); + Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); + + // also with subtype + keySet = tx.queryKeySet(MyClass.class.getName(), "@subtype"); + Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); + + // and now something useless + keySet = tx.queryKeySet(MyClass.class.getName(), "@inexistant"); + Assert.assertTrue("Expected no keys, found " + keySet, keySet.size() == 0); + + } finally { + persistenceHandler.commitTx(); + } + } + + /** + * + */ + @Test + public void testRemoveAll() { + + try { + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + + List objects = tx.queryAll(MyClass.class.getName(), "@subType"); + tx.removeAll(objects); + + } finally { + persistenceHandler.commitTx(); + } + } + + /** + * + */ + @Test + public void testSize() { + + try { + XmlPersistenceTransaction tx = persistenceHandler.openTx(); + + long size = tx.querySize(MyClass.class.getName(), "@subType"); + Assert.assertTrue("Expected size = 0, found: " + size, size == 0); + + } finally { + persistenceHandler.commitTx(); + } + } +} diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java new file mode 100644 index 000000000..9b333a08e --- /dev/null +++ b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2010 - 2011 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ +package ch.eitchnet.featherlite.plugin.xmlpers.test.impl; + +import ch.eitchnet.utils.objectfilter.ITransactionObject; + +/** + * @author Robert von Burg + * + */ +public class MyClass implements ITransactionObject { + + private long txId; + private String id; + private String name; + private String type; + + /** + * @param id + * @param name + * @param type + */ + public MyClass(String id, String name, String type) { + super(); + this.id = id; + this.name = name; + this.type = type; + } + + /** + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return this.name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the type + */ + public String getType() { + return this.type; + } + + /** + * @param type + * the type to set + */ + public void setType(String type) { + this.type = type; + } + + /** + * @see ch.eitchnet.utils.objectfilter.ITransactionObject#setTransactionID(long) + */ + @Override + public void setTransactionID(long id) { + this.txId = id; + } + + /** + * @see ch.eitchnet.utils.objectfilter.ITransactionObject#getTransactionID() + */ + @Override + public long getTransactionID() { + return this.txId; + } + + /** + * @see ch.eitchnet.utils.objectfilter.ITransactionObject#resetTransactionID() + */ + @Override + public void resetTransactionID() { + this.txId = ITransactionObject.UNSET; + } +} diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java new file mode 100644 index 000000000..ec148642d --- /dev/null +++ b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2010 - 2011 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ +package ch.eitchnet.featherlite.plugin.xmlpers.test.impl; + +import org.w3c.dom.DOMImplementation; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Text; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.AttributesImpl; + +import ch.eitchnet.xmlpers.XmlDao; + +/** + * @author Robert von Burg + * + */ +public class MyClassDao implements XmlDao { + + /** + * @see ch.eitchnet.xmlpers.XmlDao#getType(java.lang.Object) + */ + @Override + public String getType(MyClass object) { + return MyClass.class.getName(); + } + + /** + * @see ch.eitchnet.xmlpers.XmlDao#getSubType(java.lang.Object) + */ + @Override + public String getSubType(MyClass object) { + return object.getType(); + } + + /** + * @see ch.eitchnet.xmlpers.XmlDao#getId(java.lang.Object) + */ + @Override + public String getId(MyClass object) { + return object.getId(); + } + + /** + * @see ch.eitchnet.xmlpers.XmlDao#serializeToDom(java.lang.Object, org.w3c.dom.DOMImplementation) + */ + @Override + public Document serializeToDom(MyClass object, DOMImplementation domImplementation) { + + Document document = domImplementation.createDocument(null, null, null); + Element element = document.createElement("MyClass"); + document.appendChild(element); + + element.setAttribute("id", object.getId()); + element.setAttribute("type", object.getType()); + + Element nameElement = document.createElement("Name"); + element.appendChild(nameElement); + Text textNode = document.createTextNode(object.getName()); + nameElement.appendChild(textNode); + + return document; + } + + /** + * @see ch.eitchnet.xmlpers.XmlDao#parseFromDom(org.w3c.dom.Element) + */ + @Override + public MyClass parseFromDom(Element element) { + + String id = element.getAttribute("id"); + String type = element.getAttribute("type"); + Element nameElement = (Element) element.getElementsByTagName("Name").item(0); + String name = nameElement.getTextContent(); + + MyClass myClass = new MyClass(id, name, type); + + return myClass; + } + + /** + * @see ch.eitchnet.xmlpers.XmlDao#serializeToSax(java.lang.Object, org.xml.sax.ContentHandler) + */ + @Override + public void serializeToSax(MyClass object, ContentHandler contentHandler) { + + try { + contentHandler.startDocument(); + + // MyClass element / root + { + AttributesImpl atts = new AttributesImpl(); + atts.addAttribute("", "", "id", "", object.getId()); + atts.addAttribute("", "", "type", "", object.getType()); + contentHandler.startElement("", "", "MyClass", atts); + + // name element + { + contentHandler.startElement("", "", "Name", null); + char[] nameArr = object.getName().toCharArray(); + contentHandler.characters(nameArr, 0, nameArr.length); + contentHandler.endElement("", "", "name"); + } + + // MyClass end + contentHandler.endElement("", "", "MyClass"); + } + + // end document + contentHandler.endDocument(); + + } catch (SAXException e) { + throw new RuntimeException("Failed to serialize " + object + " to SAX", e); + } + } + +} diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java new file mode 100644 index 000000000..1a2b4fcd7 --- /dev/null +++ b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2010 - 2011 + * + * Apixxo AG + * Hauptgasse 25 + * 4600 Olten + * + * All rights reserved. + * + */ +package ch.eitchnet.featherlite.plugin.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.XmlDao; +import ch.eitchnet.xmlpers.XmlDaoFactory; + +/** + * @author Robert von Burg + * + */ +public class MyDaoFactory implements XmlDaoFactory { + + /** + * @see ch.eitchnet.xmlpers.XmlDaoFactory#getDao(java.lang.String) + */ + @SuppressWarnings("unchecked") + @Override + public XmlDao getDao(String type) { + if (type.equals(MyClass.class.getName())) + return (XmlDao) new MyClassDao(); + + throw new RuntimeException("Class with type " + type + " is unknown!"); + } + +} From a3d73329bdd3c822f3aa746c9e4df4d2174006b3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 14 Jun 2012 23:40:29 +0200 Subject: [PATCH 03/87] [New] Added packaging information and files and licence This includes setting the licence to LGPL, setting the headers, adding a build script and testing the build --- COPYING | 674 ++++++++++++++++++ COPYING.LESSER | 165 +++++ build.xml | 73 ++ src/ch/eitchnet/xmlpers/XmlDao.java | 24 +- src/ch/eitchnet/xmlpers/XmlDaoFactory.java | 24 +- src/ch/eitchnet/xmlpers/XmlFilePersister.java | 24 + .../xmlpers/XmlPersistenceExecption.java | 24 + .../xmlpers/XmlPersistenceHandler.java | 24 + .../xmlpers/XmlPersistencePathBuilder.java | 24 + .../xmlpers/XmlPersistenceTransaction.java | 24 +- .../xmlpers/test/impl/MyDaoFactory.java | 34 - .../java}/test/XmlPersistenceTest.java | 26 +- .../java}/test/impl/MyClass.java | 28 +- .../java}/test/impl/MyClassDao.java | 28 +- .../xmlpers/java/test/impl/MyDaoFactory.java | 48 ++ 15 files changed, 1173 insertions(+), 71 deletions(-) create mode 100644 COPYING create mode 100644 COPYING.LESSER create mode 100644 build.xml delete mode 100644 test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java rename test/ch/eitchnet/{featherlite/plugin/xmlpers => xmlpers/java}/test/XmlPersistenceTest.java (89%) rename test/ch/eitchnet/{featherlite/plugin/xmlpers => xmlpers/java}/test/impl/MyClass.java (65%) rename test/ch/eitchnet/{featherlite/plugin/xmlpers => xmlpers/java}/test/impl/MyClassDao.java (78%) create mode 100644 test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java diff --git a/COPYING b/COPYING new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/COPYING.LESSER b/COPYING.LESSER new file mode 100644 index 000000000..65c5ca88a --- /dev/null +++ b/COPYING.LESSER @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/build.xml b/build.xml new file mode 100644 index 000000000..2fd58d18c --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cleaning build folder ${buildFolder} + + + + + + + Cleaning dist folder ${distFolder} + + + + + + + diff --git a/src/ch/eitchnet/xmlpers/XmlDao.java b/src/ch/eitchnet/xmlpers/XmlDao.java index d1dd3c456..998f81f04 100644 --- a/src/ch/eitchnet/xmlpers/XmlDao.java +++ b/src/ch/eitchnet/xmlpers/XmlDao.java @@ -1,11 +1,25 @@ /* - * Copyright (c) 2010 - 2011 + * Copyright (c) 2012 * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten + * Robert von Burg * - * All rights reserved. + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/ch/eitchnet/xmlpers/XmlDaoFactory.java b/src/ch/eitchnet/xmlpers/XmlDaoFactory.java index 81f929572..338aa5e3f 100644 --- a/src/ch/eitchnet/xmlpers/XmlDaoFactory.java +++ b/src/ch/eitchnet/xmlpers/XmlDaoFactory.java @@ -1,11 +1,25 @@ /* - * Copyright (c) 2010 - 2011 + * Copyright (c) 2012 * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten + * Robert von Burg * - * All rights reserved. + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/ch/eitchnet/xmlpers/XmlFilePersister.java index c02acfb25..f4f71f44b 100644 --- a/src/ch/eitchnet/xmlpers/XmlFilePersister.java +++ b/src/ch/eitchnet/xmlpers/XmlFilePersister.java @@ -1,3 +1,27 @@ +/* + * Copyright (c) 2012 + * + * Robert von Burg + * + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ package ch.eitchnet.xmlpers; import java.io.BufferedOutputStream; diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java b/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java index 868f7d83f..cdf49b88a 100644 --- a/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java +++ b/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java @@ -1,3 +1,27 @@ +/* + * Copyright (c) 2012 + * + * Robert von Burg + * + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ package ch.eitchnet.xmlpers; /** diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java index 0681a2c2a..81796a96e 100644 --- a/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java +++ b/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java @@ -1,3 +1,27 @@ +/* + * Copyright (c) 2012 + * + * Robert von Burg + * + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ package ch.eitchnet.xmlpers; import org.apache.log4j.Logger; diff --git a/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java index a8ed1d638..28df70a79 100644 --- a/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java +++ b/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java @@ -1,3 +1,27 @@ +/* + * Copyright (c) 2012 + * + * Robert von Burg + * + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ package ch.eitchnet.xmlpers; import java.io.File; diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java index 1e3dfeba8..de6bbc607 100644 --- a/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ b/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -1,11 +1,25 @@ /* - * Copyright (c) 2010 - 2011 + * Copyright (c) 2012 * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten + * Robert von Burg * - * All rights reserved. + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java b/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java deleted file mode 100644 index 1a2b4fcd7..000000000 --- a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyDaoFactory.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2010 - 2011 - * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten - * - * All rights reserved. - * - */ -package ch.eitchnet.featherlite.plugin.xmlpers.test.impl; - -import ch.eitchnet.xmlpers.XmlDao; -import ch.eitchnet.xmlpers.XmlDaoFactory; - -/** - * @author Robert von Burg - * - */ -public class MyDaoFactory implements XmlDaoFactory { - - /** - * @see ch.eitchnet.xmlpers.XmlDaoFactory#getDao(java.lang.String) - */ - @SuppressWarnings("unchecked") - @Override - public XmlDao getDao(String type) { - if (type.equals(MyClass.class.getName())) - return (XmlDao) new MyClassDao(); - - throw new RuntimeException("Class with type " + type + " is unknown!"); - } - -} diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java b/test/ch/eitchnet/xmlpers/java/test/XmlPersistenceTest.java similarity index 89% rename from test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java rename to test/ch/eitchnet/xmlpers/java/test/XmlPersistenceTest.java index be194acbe..a380e56a5 100644 --- a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/XmlPersistenceTest.java +++ b/test/ch/eitchnet/xmlpers/java/test/XmlPersistenceTest.java @@ -1,18 +1,28 @@ /* - * Copyright (c) 2010 + * Copyright (c) 2012 * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten - * - * All rights reserved. + * Robert von Burg * */ -/** +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . * */ -package ch.eitchnet.featherlite.plugin.xmlpers.test; +package ch.eitchnet.java.xmlpers.test; import java.io.File; import java.util.List; diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java b/test/ch/eitchnet/xmlpers/java/test/impl/MyClass.java similarity index 65% rename from test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java rename to test/ch/eitchnet/xmlpers/java/test/impl/MyClass.java index 9b333a08e..903f947c9 100644 --- a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClass.java +++ b/test/ch/eitchnet/xmlpers/java/test/impl/MyClass.java @@ -1,14 +1,28 @@ /* - * Copyright (c) 2010 - 2011 + * Copyright (c) 2012 * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten - * - * All rights reserved. + * Robert von Burg * */ -package ch.eitchnet.featherlite.plugin.xmlpers.test.impl; + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ +package ch.eitchnet.java.xmlpers.test.impl; import ch.eitchnet.utils.objectfilter.ITransactionObject; diff --git a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java b/test/ch/eitchnet/xmlpers/java/test/impl/MyClassDao.java similarity index 78% rename from test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java rename to test/ch/eitchnet/xmlpers/java/test/impl/MyClassDao.java index ec148642d..6468b2710 100644 --- a/test/ch/eitchnet/featherlite/plugin/xmlpers/test/impl/MyClassDao.java +++ b/test/ch/eitchnet/xmlpers/java/test/impl/MyClassDao.java @@ -1,14 +1,28 @@ /* - * Copyright (c) 2010 - 2011 + * Copyright (c) 2012 * - * Apixxo AG - * Hauptgasse 25 - * 4600 Olten - * - * All rights reserved. + * Robert von Burg * */ -package ch.eitchnet.featherlite.plugin.xmlpers.test.impl; + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ +package ch.eitchnet.java.xmlpers.test.impl; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; diff --git a/test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java b/test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java new file mode 100644 index 000000000..9114f1ce4 --- /dev/null +++ b/test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012 + * + * Robert von Burg + * + */ + +/* + * This file is part of ch.eitchnet.java.xmlpers + * + * Privilege is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Privilege is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Privilege. If not, see . + * + */ +package ch.eitchnet.java.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.XmlDao; +import ch.eitchnet.xmlpers.XmlDaoFactory; + +/** + * @author Robert von Burg + * + */ +public class MyDaoFactory implements XmlDaoFactory { + + /** + * @see ch.eitchnet.xmlpers.XmlDaoFactory#getDao(java.lang.String) + */ + @SuppressWarnings("unchecked") + @Override + public XmlDao getDao(String type) { + if (type.equals(MyClass.class.getName())) + return (XmlDao) new MyClassDao(); + + throw new RuntimeException("Class with type " + type + " is unknown!"); + } + +} From 10b8cb407115c3f0a2744530aac66e4565e52ff9 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 28 Jul 2012 15:37:24 +0200 Subject: [PATCH 04/87] [Major] rebuilt project to use Maven. - Now a "mvn compile" will build the project downloading dependencies as needed - Note: as ch.eitchnet.utils is a dependency, it must be installed first by using "mvn install" --- .gitignore | 12 +- config/log4j.properties | 12 -- pom.xml | 171 ++++++++++++++++++ .../java}/ch/eitchnet/xmlpers/XmlDao.java | 0 .../ch/eitchnet/xmlpers/XmlDaoFactory.java | 0 .../ch/eitchnet/xmlpers/XmlFilePersister.java | 0 .../xmlpers/XmlPersistenceExecption.java | 0 .../xmlpers/XmlPersistenceHandler.java | 0 .../xmlpers/XmlPersistencePathBuilder.java | 0 .../xmlpers/XmlPersistenceTransaction.java | 0 src/main/resources/log4j.properties | 12 ++ .../xmlpers}/test/XmlPersistenceTest.java | 7 +- .../eitchnet/xmlpers}/test/impl/MyClass.java | 2 +- .../xmlpers}/test/impl/MyClassDao.java | 2 +- .../xmlpers}/test/impl/MyDaoFactory.java | 2 +- 15 files changed, 197 insertions(+), 23 deletions(-) delete mode 100644 config/log4j.properties create mode 100644 pom.xml rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlDao.java (100%) rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlDaoFactory.java (100%) rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlFilePersister.java (100%) rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlPersistenceExecption.java (100%) rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlPersistenceHandler.java (100%) rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java (100%) rename src/{ => main/java}/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java (100%) create mode 100644 src/main/resources/log4j.properties rename {test/ch/eitchnet/xmlpers/java => src/test/java/ch/eitchnet/xmlpers}/test/XmlPersistenceTest.java (97%) rename {test/ch/eitchnet/xmlpers/java => src/test/java/ch/eitchnet/xmlpers}/test/impl/MyClass.java (98%) rename {test/ch/eitchnet/xmlpers/java => src/test/java/ch/eitchnet/xmlpers}/test/impl/MyClassDao.java (98%) rename {test/ch/eitchnet/xmlpers/java => src/test/java/ch/eitchnet/xmlpers}/test/impl/MyDaoFactory.java (96%) diff --git a/.gitignore b/.gitignore index c77d8a98c..8cbe22473 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,11 @@ *.class -# Package Files # -*.jar -*.war -*.ear +# Maven target +target/ # Project files -tmp +tmp/ +logs/ + +# External libraries +lib/ diff --git a/config/log4j.properties b/config/log4j.properties deleted file mode 100644 index a745f967b..000000000 --- a/config/log4j.properties +++ /dev/null @@ -1,12 +0,0 @@ -log4j.rootLogger = info, stdout, file - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n - -log4j.appender.file=org.apache.log4j.RollingFileAppender -log4j.appender.file.File=${user.dir}/logs/app.log -log4j.appender.file.MaxFileSize=10000KB -log4j.appender.file.MaxBackupIndex=0 -log4j.appender.file.layout=org.apache.log4j.PatternLayout -log4j.appender.file.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000..2dd69cbbb --- /dev/null +++ b/pom.xml @@ -0,0 +1,171 @@ + + 4.0.0 + ch.eitchnet + ch.eitchnet.xmlpers + jar + 1.0-SNAPSHOT + ch.eitchnet.xmlpers + https://github.com/eitch/ch.eitchnet.xmlpers + + + UTF-8 + + + + + 2011 + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl.html + repo + + + + eitchnet.ch + http://blog.eitchnet.ch + + + + eitch + Robert von Vurg + eitch@eitchnet.ch + http://blog.eitchnet.ch + eitchnet.ch + http://blog.eitchnet.ch + + architect + developer + + +1 + + http://localhost + + + + + + Github Issues + https://github.com/eitch/ch.eitchnet.xmlpers/issues + + + + + + scm:git:https://github.com/eitch/ch.eitchnet.xmlpers.git + scm:git:git@github.com:eitch/ch.eitchnet.xmlpers.git + https://github.com/eitch/ch.eitchnet.xmlpers + + + + + + + junit + junit + 4.10 + test + + + log4j + log4j + 1.2.17 + + + ch.eitchnet + ch.eitchnet.utils + 1.0-SNAPSHOT + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + true + true + + + + + + + + org.apache.maven.plugins + maven-site-plugin + 2.3 + + UTF-8 + + + + + + diff --git a/src/ch/eitchnet/xmlpers/XmlDao.java b/src/main/java/ch/eitchnet/xmlpers/XmlDao.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlDao.java rename to src/main/java/ch/eitchnet/xmlpers/XmlDao.java diff --git a/src/ch/eitchnet/xmlpers/XmlDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlDaoFactory.java rename to src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java diff --git a/src/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlFilePersister.java rename to src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlPersistenceExecption.java rename to src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlPersistenceHandler.java rename to src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java diff --git a/src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java rename to src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java diff --git a/src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java similarity index 100% rename from src/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java rename to src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties new file mode 100644 index 000000000..6aa19bb24 --- /dev/null +++ b/src/main/resources/log4j.properties @@ -0,0 +1,12 @@ +log4j.rootLogger = info, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n + +#log4j.appender.file=org.apache.log4j.RollingFileAppender +#log4j.appender.file.File=${user.dir}/logs/app.log +#log4j.appender.file.MaxFileSize=10000KB +#log4j.appender.file.MaxBackupIndex=0 +#log4j.appender.file.layout=org.apache.log4j.PatternLayout +#log4j.appender.file.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n diff --git a/test/ch/eitchnet/xmlpers/java/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java similarity index 97% rename from test/ch/eitchnet/xmlpers/java/test/XmlPersistenceTest.java rename to src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index a380e56a5..9296e4750 100644 --- a/test/ch/eitchnet/xmlpers/java/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -22,7 +22,7 @@ * along with Privilege. If not, see . * */ -package ch.eitchnet.java.xmlpers.test; +package ch.eitchnet.xmlpers.test; import java.io.File; import java.util.List; @@ -33,13 +33,14 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import ch.eitchnet.featherlite.plugin.xmlpers.test.impl.MyClass; -import ch.eitchnet.featherlite.plugin.xmlpers.test.impl.MyDaoFactory; import ch.eitchnet.utils.helper.Log4jConfigurator; import ch.eitchnet.utils.objectfilter.ITransactionObject; import ch.eitchnet.xmlpers.XmlPersistenceExecption; import ch.eitchnet.xmlpers.XmlPersistenceHandler; import ch.eitchnet.xmlpers.XmlPersistenceTransaction; +import ch.eitchnet.xmlpers.test.impl.MyClass; +import ch.eitchnet.xmlpers.test.impl.MyClassDao; +import ch.eitchnet.xmlpers.test.impl.MyDaoFactory; /** * @author Robert von Burg diff --git a/test/ch/eitchnet/xmlpers/java/test/impl/MyClass.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java similarity index 98% rename from test/ch/eitchnet/xmlpers/java/test/impl/MyClass.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java index 903f947c9..ec2692970 100644 --- a/test/ch/eitchnet/xmlpers/java/test/impl/MyClass.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java @@ -22,7 +22,7 @@ * along with Privilege. If not, see . * */ -package ch.eitchnet.java.xmlpers.test.impl; +package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.utils.objectfilter.ITransactionObject; diff --git a/test/ch/eitchnet/xmlpers/java/test/impl/MyClassDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java similarity index 98% rename from test/ch/eitchnet/xmlpers/java/test/impl/MyClassDao.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java index 6468b2710..771f8e115 100644 --- a/test/ch/eitchnet/xmlpers/java/test/impl/MyClassDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java @@ -22,7 +22,7 @@ * along with Privilege. If not, see . * */ -package ch.eitchnet.java.xmlpers.test.impl; +package ch.eitchnet.xmlpers.test.impl; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; diff --git a/test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java similarity index 96% rename from test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java index 9114f1ce4..c0ed22409 100644 --- a/test/ch/eitchnet/xmlpers/java/test/impl/MyDaoFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java @@ -22,7 +22,7 @@ * along with Privilege. If not, see . * */ -package ch.eitchnet.java.xmlpers.test.impl; +package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.XmlDao; import ch.eitchnet.xmlpers.XmlDaoFactory; From 50f2cba067b7b271de510f064a56a327e6a8b30a Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 28 Jul 2012 15:46:29 +0200 Subject: [PATCH 05/87] [Minor] Added eclipse settings file to .gitignore --- .gitignore | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.gitignore b/.gitignore index 8cbe22473..3487fb9f8 100644 --- a/.gitignore +++ b/.gitignore @@ -7,5 +7,10 @@ target/ tmp/ logs/ +# Eclipse settings +.classpath +.project +.settings/ + # External libraries lib/ From 61f6e6cdc406830a7a1a3503b9a6a0c05e1eaeec Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 28 Jul 2012 23:17:07 +0200 Subject: [PATCH 06/87] [Minor] change mvn eclipse configuration to load sources as well --- pom.xml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pom.xml b/pom.xml index 2dd69cbbb..d889c4f99 100644 --- a/pom.xml +++ b/pom.xml @@ -131,6 +131,16 @@ + + + org.apache.maven.plugins + maven-eclipse-plugin + 2.9 + + true + true + + org.apache.maven.plugins From 925623bc9394861642b80a5727b224e6e8ca235b Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 29 Jul 2012 18:28:22 +0200 Subject: [PATCH 07/87] [Minor] cleaned up copyright notices in all classes --- build.xml | 73 ------------------- pom.xml | 17 ++++- src/main/java/ch/eitchnet/xmlpers/XmlDao.java | 11 +-- .../ch/eitchnet/xmlpers/XmlDaoFactory.java | 11 +-- .../ch/eitchnet/xmlpers/XmlFilePersister.java | 11 +-- .../xmlpers/XmlPersistenceExecption.java | 11 +-- .../xmlpers/XmlPersistenceHandler.java | 11 +-- .../xmlpers/XmlPersistencePathBuilder.java | 11 +-- .../xmlpers/XmlPersistenceTransaction.java | 11 +-- .../xmlpers/test/XmlPersistenceTest.java | 12 +-- .../eitchnet/xmlpers/test/impl/MyClass.java | 11 +-- .../xmlpers/test/impl/MyClassDao.java | 11 +-- .../xmlpers/test/impl/MyDaoFactory.java | 11 +-- 13 files changed, 49 insertions(+), 163 deletions(-) delete mode 100644 build.xml diff --git a/build.xml b/build.xml deleted file mode 100644 index 2fd58d18c..000000000 --- a/build.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Cleaning build folder ${buildFolder} - - - - - - - Cleaning dist folder ${distFolder} - - - - - - - diff --git a/pom.xml b/pom.xml index d889c4f99..94901bab3 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ ch.eitchnet ch.eitchnet.xmlpers jar - 1.0-SNAPSHOT + 0.1.0-SNAPSHOT ch.eitchnet.xmlpers https://github.com/eitch/ch.eitchnet.xmlpers @@ -151,6 +151,21 @@ 1.6 + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + org.apache.maven.plugins diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlDao.java b/src/main/java/ch/eitchnet/xmlpers/XmlDao.java index 998f81f04..234c0a9ea 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlDao.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java index 338aa5e3f..90b469703 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java index f4f71f44b..f9d7bc4fd 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java index cdf49b88a..ff01fca32 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java index 81796a96e..7382d30c2 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java index 28df70a79..5a5fcf7d8 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java index de6bbc607..e844d3d4e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index 9296e4750..3c0220186 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers.test; @@ -39,7 +34,6 @@ import ch.eitchnet.xmlpers.XmlPersistenceExecption; import ch.eitchnet.xmlpers.XmlPersistenceHandler; import ch.eitchnet.xmlpers.XmlPersistenceTransaction; import ch.eitchnet.xmlpers.test.impl.MyClass; -import ch.eitchnet.xmlpers.test.impl.MyClassDao; import ch.eitchnet.xmlpers.test.impl.MyDaoFactory; /** diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java index ec2692970..a0c1d3e2c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java index 771f8e115..4686ba349 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java index c0ed22409..efa26d450 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java @@ -1,25 +1,20 @@ /* * Copyright (c) 2012 * - * Robert von Burg - * - */ - -/* * This file is part of ch.eitchnet.java.xmlpers * - * Privilege is free software: you can redistribute it and/or modify + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * Privilege is distributed in the hope that it will be useful, + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License - * along with Privilege. If not, see . + * along with ch.eitchnet.java.xmlpers. If not, see . * */ package ch.eitchnet.xmlpers.test.impl; From eec0b671352ad39670a0113fefa1374c0a740d75 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 4 Aug 2012 21:37:09 +0200 Subject: [PATCH 08/87] [Minor] updated dependency to ch.eitchnet.utils to 0.1.0 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 94901bab3..65b28f284 100644 --- a/pom.xml +++ b/pom.xml @@ -125,7 +125,7 @@ ch.eitchnet ch.eitchnet.utils - 1.0-SNAPSHOT + 0.1.0-SNAPSHOT From 38466685a04097f7f1410a26562fd2b59b5fb150 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 24 Nov 2012 13:23:24 +0100 Subject: [PATCH 09/87] [Major] refactored use of log4j to slf4j --- pom.xml | 22 ++++- .../ch/eitchnet/xmlpers/XmlFilePersister.java | 87 +++++++++-------- .../xmlpers/XmlPersistenceHandler.java | 27 +++--- .../xmlpers/XmlPersistencePathBuilder.java | 23 ++--- .../xmlpers/XmlPersistenceTransaction.java | 69 ++++++------- .../xmlpers/test/XmlPersistenceTest.java | 97 ++++++++++--------- 6 files changed, 171 insertions(+), 154 deletions(-) diff --git a/pom.xml b/pom.xml index 65b28f284..f43055b3e 100644 --- a/pom.xml +++ b/pom.xml @@ -117,16 +117,28 @@ 4.10 test - - log4j - log4j - 1.2.17 - ch.eitchnet ch.eitchnet.utils 0.1.0-SNAPSHOT + + ch.eitchnet + ch.eitchnet.log4j + 0.1.0-SNAPSHOT + test + + + org.slf4j + slf4j-api + 1.7.2 + + + org.slf4j + slf4j-log4j12 + 1.7.2 + test + diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java index f9d7bc4fd..8049a9946 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java @@ -31,7 +31,8 @@ import java.util.Set; import javax.xml.parsers.DocumentBuilder; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; @@ -50,7 +51,7 @@ public class XmlFilePersister { // private static final String XML_DEFAULT_ENCODING = "UTF-8"; - private static final Logger logger = Logger.getLogger(XmlFilePersister.class); + private static final Logger logger = LoggerFactory.getLogger(XmlFilePersister.class); private boolean verbose; private XmlPersistencePathBuilder xmlPathHelper; @@ -74,9 +75,9 @@ public class XmlFilePersister { File pathF; if (subType != null) - pathF = xmlPathHelper.getPathF(type, subType, id); + pathF = this.xmlPathHelper.getPathF(type, subType, id); else - pathF = xmlPathHelper.getPathF(type, id); + pathF = this.xmlPathHelper.getPathF(type, id); // if this is a new file, then check create parents, if the don't exist if (!pathF.exists()) { @@ -87,15 +88,15 @@ public class XmlFilePersister { } } - if (verbose) - logger.info("Persisting " + type + " / " + subType + " / " + id + " to " + pathF.getAbsolutePath() + "..."); + if (this.verbose) + XmlFilePersister.logger.info("Persisting " + type + " / " + subType + " / " + id + " to " + pathF.getAbsolutePath() + "..."); BufferedOutputStream outStream = null; try { outStream = new BufferedOutputStream(new FileOutputStream(pathF)); - OutputFormat outputFormat = new OutputFormat("XML", XML_DEFAULT_ENCODING, true); + OutputFormat outputFormat = new OutputFormat("XML", XmlFilePersister.XML_DEFAULT_ENCODING, true); outputFormat.setIndent(1); outputFormat.setIndenting(true); //of.setDoctype(null, null); @@ -113,13 +114,13 @@ public class XmlFilePersister { try { outStream.close(); } catch (IOException e) { - logger.error(e, e); + XmlFilePersister.logger.error(e.getMessage(), e); } } } - if (verbose) - logger.info("Done."); + if (this.verbose) + XmlFilePersister.logger.info("Done."); } /** @@ -131,24 +132,24 @@ public class XmlFilePersister { File pathF; if (subType != null) - pathF = xmlPathHelper.getPathF(type, subType, id); + pathF = this.xmlPathHelper.getPathF(type, subType, id); else - pathF = xmlPathHelper.getPathF(type, id); + pathF = this.xmlPathHelper.getPathF(type, id); - if (verbose) - logger.info("Remove persistence file for " + type + " / " + subType + " / " + id + " from " + if (this.verbose) + XmlFilePersister.logger.info("Remove persistence file for " + type + " / " + subType + " / " + id + " from " + pathF.getAbsolutePath() + "..."); if (!pathF.exists()) { - logger.error("Persistence file for " + type + " / " + subType + " / " + id + " does not exist at " + XmlFilePersister.logger.error("Persistence file for " + type + " / " + subType + " / " + id + " does not exist at " + pathF.getAbsolutePath()); } else if (!pathF.delete()) { throw new XmlPersistenceExecption("Could not delete persistence file for " + type + " / " + subType + " / " + id + " at " + pathF.getAbsolutePath()); } - if (verbose) - logger.info("Done."); + if (this.verbose) + XmlFilePersister.logger.info("Done."); } /** @@ -159,22 +160,22 @@ public class XmlFilePersister { File pathF; if (subType == null) - pathF = xmlPathHelper.getPathF(type); + pathF = this.xmlPathHelper.getPathF(type); else - pathF = xmlPathHelper.getPathF(type, subType); + pathF = this.xmlPathHelper.getPathF(type, subType); if (!pathF.exists()) { if (subType == null) - logger.error("Path for " + type + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " at " + pathF.getAbsolutePath() + " does not exist, so removing not possible!"); else - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so removing not possible!"); } else { File[] filesToRemove = pathF.listFiles(); - boolean removed = FileHelper.deleteFiles(filesToRemove, verbose); + boolean removed = FileHelper.deleteFiles(filesToRemove, this.verbose); if (!removed) { if (subType == null) @@ -201,7 +202,7 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type, subType); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so no objects exist!"); return Collections.emptySet(); } @@ -212,8 +213,8 @@ public class XmlFilePersister { keySet.add(name.substring(0, name.length() - XmlPersistencePathBuilder.FILE_EXT.length())); } - if (verbose) - logger.info("Found " + keySet.size() + " elements for " + type + " / " + subType); + if (this.verbose) + XmlFilePersister.logger.info("Found " + keySet.size() + " elements for " + type + " / " + subType); return keySet; } @@ -221,7 +222,7 @@ public class XmlFilePersister { // otherwise we need to iterate any existing subTypes and create a combined key set File pathF = this.xmlPathHelper.getPathF(type); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so no objects exist!"); return Collections.emptySet(); } @@ -232,17 +233,17 @@ public class XmlFilePersister { for (File subTypeFile : subTypeFiles) { if (subTypeFile.isFile()) { - keySet.add(xmlPathHelper.getId(subTypeFile.getName())); + keySet.add(this.xmlPathHelper.getId(subTypeFile.getName())); } else { for (File f : subTypeFile.listFiles()) { - keySet.add(xmlPathHelper.getId(f.getName())); + keySet.add(this.xmlPathHelper.getId(f.getName())); } } } - if (verbose) - logger.info("Found " + keySet.size() + " elements for " + type); + if (this.verbose) + XmlFilePersister.logger.info("Found " + keySet.size() + " elements for " + type); return keySet; } @@ -261,15 +262,15 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type, subType); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so no objects exist!"); return 0l; } int length = pathF.listFiles().length; - if (verbose) - logger.info("Found " + length + " elements for " + type + " / " + subType); + if (this.verbose) + XmlFilePersister.logger.info("Found " + length + " elements for " + type + " / " + subType); return length; } @@ -279,7 +280,7 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so no objects exist!"); return 0l; } @@ -296,8 +297,8 @@ public class XmlFilePersister { } } - if (verbose) - logger.info("Found " + numberOfFiles + " elements for " + type); + if (this.verbose) + XmlFilePersister.logger.info("Found " + numberOfFiles + " elements for " + type); return numberOfFiles; } @@ -361,7 +362,7 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type, subType); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so no objects exist!"); return Collections.emptyList(); } @@ -371,8 +372,8 @@ public class XmlFilePersister { list.add(parseFile(subTypeF, docBuilder)); } - if (verbose) - logger.info("Loaded " + list.size() + " elements for " + type + " / " + subType); + if (this.verbose) + XmlFilePersister.logger.info("Loaded " + list.size() + " elements for " + type + " / " + subType); return list; } @@ -382,7 +383,7 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() + " does not exist, so no objects exist!"); return Collections.emptyList(); } @@ -402,8 +403,8 @@ public class XmlFilePersister { } } - if (verbose) - logger.info("Loaded " + list.size() + " elements for " + type); + if (this.verbose) + XmlFilePersister.logger.info("Loaded " + list.size() + " elements for " + type); return list; } @@ -420,7 +421,7 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type, subType, id); if (!pathF.exists()) { - logger.error("Path for " + type + " / " + subType + " / " + id + " at " + pathF.getAbsolutePath() + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " / " + id + " at " + pathF.getAbsolutePath() + " does not exist, so object does not exist!"); return null; } diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java index 7382d30c2..c615795ac 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java @@ -19,7 +19,8 @@ */ package ch.eitchnet.xmlpers; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.SystemHelper; import ch.eitchnet.utils.objectfilter.ITransactionObject; @@ -46,7 +47,7 @@ public class XmlPersistenceHandler { */ public static final String CONFIG_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers.config.daoFactoryClass"; - protected static final Logger logger = Logger.getLogger(XmlPersistenceHandler.class); + protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandler.class); protected boolean verbose; protected ThreadLocal xmlPersistenceTxThreadLocal; @@ -58,18 +59,18 @@ public class XmlPersistenceHandler { */ public void initialize() { - String basePath = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), CONFIG_BASEPATH, null); - verbose = SystemHelper.getPropertyBool(XmlPersistenceHandler.class.getSimpleName(), CONFIG_VERBOSE, + String basePath = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), XmlPersistenceHandler.CONFIG_BASEPATH, null); + this.verbose = SystemHelper.getPropertyBool(XmlPersistenceHandler.class.getSimpleName(), XmlPersistenceHandler.CONFIG_VERBOSE, Boolean.FALSE).booleanValue(); // get class to use as transaction String daoFactoryClassName = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), - CONFIG_DAO_FACTORY_CLASS, null); + XmlPersistenceHandler.CONFIG_DAO_FACTORY_CLASS, null); try { @SuppressWarnings("unchecked") Class xmlDaoFactoryClass = (Class) Class.forName(daoFactoryClassName); - xmlDaoFactory = xmlDaoFactoryClass.newInstance(); + this.xmlDaoFactory = xmlDaoFactoryClass.newInstance(); } catch (ClassNotFoundException e) { throw new XmlPersistenceExecption("XmlDaoFactory class does not exist " + daoFactoryClassName, e); @@ -78,10 +79,10 @@ public class XmlPersistenceHandler { } XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(basePath); - persister = new XmlFilePersister(pathBuilder, verbose); + this.persister = new XmlFilePersister(pathBuilder, this.verbose); // initialize the Thread local object which is used per transaction - xmlPersistenceTxThreadLocal = new ThreadLocal(); + this.xmlPersistenceTxThreadLocal = new ThreadLocal(); } /** @@ -89,8 +90,8 @@ public class XmlPersistenceHandler { */ public XmlPersistenceTransaction openTx() { - if (verbose) - logger.info("Opening new transaction..."); + if (this.verbose) + XmlPersistenceHandler.logger.info("Opening new transaction..."); // make sure no previous filter exists XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); @@ -100,7 +101,7 @@ public class XmlPersistenceHandler { // set a new persistence transaction object ObjectFilter objectFilter = new ObjectFilter(); xmlPersistenceTx = new XmlPersistenceTransaction(); - xmlPersistenceTx.initialize(persister, xmlDaoFactory, objectFilter, verbose); + xmlPersistenceTx.initialize(this.persister, this.xmlDaoFactory, objectFilter, this.verbose); this.xmlPersistenceTxThreadLocal.set(xmlPersistenceTx); @@ -123,8 +124,8 @@ public class XmlPersistenceHandler { */ public void commitTx() { - if (verbose) - logger.info("Committing transaction..."); + if (this.verbose) + XmlPersistenceHandler.logger.info("Committing transaction..."); try { XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java index 5a5fcf7d8..b92107cfc 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java @@ -22,14 +22,15 @@ package ch.eitchnet.xmlpers; import java.io.File; import java.io.IOException; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * @author Robert von Burg * */ public class XmlPersistencePathBuilder { - private static final Logger logger = Logger.getLogger(XmlPersistencePathBuilder.class); + private static final Logger logger = LoggerFactory.getLogger(XmlPersistencePathBuilder.class); /** * @@ -39,7 +40,7 @@ public class XmlPersistencePathBuilder { /** * */ - public static final int EXT_LENGTH = FILE_EXT.length(); + public static final int EXT_LENGTH = XmlPersistencePathBuilder.FILE_EXT.length(); private String basePath; @@ -61,7 +62,7 @@ public class XmlPersistencePathBuilder { throw new XmlPersistenceExecption("Failed to build canonical path from " + basePath, e); } - logger.info("Using base path " + basePath); + XmlPersistencePathBuilder.logger.info("Using base path " + basePath); } /** @@ -69,7 +70,7 @@ public class XmlPersistencePathBuilder { * @return */ public String getFilename(String id) { - return id.concat(FILE_EXT); + return id.concat(XmlPersistencePathBuilder.FILE_EXT); } /** @@ -77,11 +78,11 @@ public class XmlPersistencePathBuilder { * @return */ public String getId(String filename) { - if (filename.charAt(filename.length() - EXT_LENGTH) != '.') + if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') throw new XmlPersistenceExecption("The filename does not have a . at index " - + (filename.length() - EXT_LENGTH)); + + (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); - return filename.substring(0, filename.length() - EXT_LENGTH); + return filename.substring(0, filename.length() - XmlPersistencePathBuilder.EXT_LENGTH); } /** @@ -91,7 +92,7 @@ public class XmlPersistencePathBuilder { */ public String getPath(String type) { - StringBuilder sb = new StringBuilder(basePath); + StringBuilder sb = new StringBuilder(this.basePath); sb.append("/"); sb.append(type); @@ -114,7 +115,7 @@ public class XmlPersistencePathBuilder { */ public String getPath(String type, String subType) { - StringBuilder sb = new StringBuilder(basePath); + StringBuilder sb = new StringBuilder(this.basePath); sb.append("/"); sb.append(type); sb.append("/"); @@ -140,7 +141,7 @@ public class XmlPersistencePathBuilder { */ public String getPath(String type, String subType, String id) { - StringBuilder sb = new StringBuilder(basePath); + StringBuilder sb = new StringBuilder(this.basePath); sb.append("/"); sb.append(type); sb.append("/"); diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java index e844d3d4e..5e9a2664b 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -27,7 +27,8 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -41,7 +42,7 @@ import ch.eitchnet.utils.objectfilter.ObjectFilter; */ public class XmlPersistenceTransaction { - private static final Logger logger = Logger.getLogger(XmlPersistenceTransaction.class); + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTransaction.class); private boolean verbose; private XmlFilePersister persister; @@ -64,23 +65,23 @@ public class XmlPersistenceTransaction { } private DocumentBuilder getDocBuilder() { - if (docBuilder == null) { + if (this.docBuilder == null) { try { - docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + this.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new XmlPersistenceExecption("Failed to load document builder: " + e.getLocalizedMessage(), e); } } - return docBuilder; + return this.docBuilder; } /** * @return */ protected DOMImplementation getDomImpl() { - if (domImplementation == null) - domImplementation = getDocBuilder().getDOMImplementation(); - return domImplementation; + if (this.domImplementation == null) + this.domImplementation = getDocBuilder().getDOMImplementation(); + return this.domImplementation; } /* @@ -183,7 +184,7 @@ public class XmlPersistenceTransaction { public List queryAll(String type, String subType) { // XXX ok, this is very ugly, but for starters it will have to do - XmlDao dao = xmlDaoFactory.getDao(type); + XmlDao dao = this.xmlDaoFactory.getDao(type); List elements = this.persister.queryAll(type, subType, getDocBuilder()); List objects = new ArrayList(elements.size()); @@ -214,7 +215,7 @@ public class XmlPersistenceTransaction { */ public T queryById(String type, String subType, String id) { - XmlDao dao = xmlDaoFactory.getDao(type); + XmlDao dao = this.xmlDaoFactory.getDao(type); Element element = this.persister.queryById(type, subType, id, getDocBuilder()); if (element == null) @@ -235,24 +236,24 @@ public class XmlPersistenceTransaction { */ void commitTx() { - if (verbose) - logger.info("Committing..."); + if (this.verbose) + XmlPersistenceTransaction.logger.info("Committing..."); - Set keySet = objectFilter.keySet(); + Set keySet = this.objectFilter.keySet(); if (keySet.isEmpty()) return; for (String key : keySet) { - XmlDao dao = xmlDaoFactory.getDao(key); + XmlDao dao = this.xmlDaoFactory.getDao(key); - List removed = objectFilter.getRemoved(key); + List removed = this.objectFilter.getRemoved(key); if (removed.isEmpty()) { - if (verbose) - logger.info("No objects removed in this tx."); + if (this.verbose) + XmlPersistenceTransaction.logger.info("No objects removed in this tx."); } else { - if (verbose) - logger.info(removed.size() + " objects removed in this tx."); + if (this.verbose) + XmlPersistenceTransaction.logger.info(removed.size() + " objects removed in this tx."); for (ITransactionObject object : removed) { @@ -260,17 +261,17 @@ public class XmlPersistenceTransaction { String subType = dao.getSubType(object); String id = dao.getId(object); - persister.remove(type, subType, id); + this.persister.remove(type, subType, id); } } - List updated = objectFilter.getUpdated(key); + List updated = this.objectFilter.getUpdated(key); if (updated.isEmpty()) { - if (verbose) - logger.info("No objects updated in this tx."); + if (this.verbose) + XmlPersistenceTransaction.logger.info("No objects updated in this tx."); } else { - if (verbose) - logger.info(updated.size() + " objects updated in this tx."); + if (this.verbose) + XmlPersistenceTransaction.logger.info(updated.size() + " objects updated in this tx."); for (ITransactionObject object : updated) { @@ -279,17 +280,17 @@ public class XmlPersistenceTransaction { String id = dao.getId(object); Document asDom = dao.serializeToDom(object, getDomImpl()); - persister.saveOrUpdate(type, subType, id, asDom); + this.persister.saveOrUpdate(type, subType, id, asDom); } } - List added = objectFilter.getAdded(key); + List added = this.objectFilter.getAdded(key); if (added.isEmpty()) { - if (verbose) - logger.info("No objects added in this tx."); + if (this.verbose) + XmlPersistenceTransaction.logger.info("No objects added in this tx."); } else { - if (verbose) - logger.info(updated.size() + " objects added in this tx."); + if (this.verbose) + XmlPersistenceTransaction.logger.info(updated.size() + " objects added in this tx."); for (ITransactionObject object : added) { @@ -298,12 +299,12 @@ public class XmlPersistenceTransaction { String id = dao.getId(object); Document asDom = dao.serializeToDom(object, getDomImpl()); - persister.saveOrUpdate(type, subType, id, asDom); + this.persister.saveOrUpdate(type, subType, id, asDom); } } } - objectFilter.clearCache(); - logger.info("Completed TX"); + this.objectFilter.clearCache(); + XmlPersistenceTransaction.logger.info("Completed TX"); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index 3c0220186..4ac22b6ee 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -23,7 +23,8 @@ import java.io.File; import java.util.List; import java.util.Set; -import org.apache.log4j.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; @@ -42,7 +43,7 @@ import ch.eitchnet.xmlpers.test.impl.MyDaoFactory; */ public class XmlPersistenceTest { - private static final Logger logger = Logger.getLogger(XmlPersistenceTest.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTest.class.getName()); private static XmlPersistenceHandler persistenceHandler; @@ -67,13 +68,13 @@ public class XmlPersistenceTest { System.setProperty(XmlPersistenceHandler.CONFIG_VERBOSE, "true"); System.setProperty(XmlPersistenceHandler.CONFIG_DAO_FACTORY_CLASS, MyDaoFactory.class.getName()); - persistenceHandler = new XmlPersistenceHandler(); - persistenceHandler.initialize(); + XmlPersistenceTest.persistenceHandler = new XmlPersistenceHandler(); + XmlPersistenceTest.persistenceHandler.initialize(); - logger.info("Initialized persistence handler."); + XmlPersistenceTest.logger.info("Initialized persistence handler."); } catch (Exception e) { - logger.error(e, e); + XmlPersistenceTest.logger.error(e.getMessage(), e); throw new RuntimeException("Initialization failed: " + e.getLocalizedMessage(), e); } @@ -86,20 +87,20 @@ public class XmlPersistenceTest { public void testCreate() { try { - logger.info("Trying to create..."); + XmlPersistenceTest.logger.info("Trying to create..."); // new instance MyClass myClass = new MyClass("@id", "@name", "@subtype"); // persist instance - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); tx.add(myClass); - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); - logger.info("Done creating."); + XmlPersistenceTest.logger.info("Done creating."); } catch (Exception e) { - logger.error(e, e); + XmlPersistenceTest.logger.error(e.getMessage(), e); Assert.fail("Failed: " + e.getLocalizedMessage()); } } @@ -111,18 +112,18 @@ public class XmlPersistenceTest { public void testRead() { try { - logger.info("Trying to read..."); + XmlPersistenceTest.logger.info("Trying to read..."); // query MyClass with id @id - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - logger.info("Found MyClass: " + myClass); - persistenceHandler.commitTx(); + XmlPersistenceTest.logger.info("Found MyClass: " + myClass); + XmlPersistenceTest.persistenceHandler.commitTx(); - logger.info("Done reading."); + XmlPersistenceTest.logger.info("Done reading."); } catch (Exception e) { - logger.error(e, e); + XmlPersistenceTest.logger.error(e.getMessage(), e); Assert.fail("Failed: " + e.getLocalizedMessage()); } } @@ -134,24 +135,24 @@ public class XmlPersistenceTest { public void testUpdate() { try { - logger.info("Trying to update an object..."); + XmlPersistenceTest.logger.info("Trying to update an object..."); // query the instance - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - logger.info("Found MyClass: " + myClass); + XmlPersistenceTest.logger.info("Found MyClass: " + myClass); // modify the instance myClass.setName("@name_modified"); // update the instance tx.update(myClass); - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); - logger.info("Done updating."); + XmlPersistenceTest.logger.info("Done updating."); } catch (Exception e) { - logger.error(e, e); + XmlPersistenceTest.logger.error(e.getMessage(), e); Assert.fail("Failed: " + e.getLocalizedMessage()); } } @@ -162,17 +163,17 @@ public class XmlPersistenceTest { @Test public void testRemove() { - logger.info("Trying to remove..."); + XmlPersistenceTest.logger.info("Trying to remove..."); // query the instance - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - logger.info("Found MyClass: " + myClass); + XmlPersistenceTest.logger.info("Found MyClass: " + myClass); tx.remove(myClass); - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); - logger.info("Done removing."); + XmlPersistenceTest.logger.info("Done removing."); } /** @@ -182,13 +183,13 @@ public class XmlPersistenceTest { public void testQueryFail() { try { - logger.info("Trying to query removed object..."); - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTest.logger.info("Trying to query removed object..."); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - logger.info("Found MyClass: " + myClass); - logger.info("Done querying removed object"); + XmlPersistenceTest.logger.info("Found MyClass: " + myClass); + XmlPersistenceTest.logger.info("Done querying removed object"); } finally { - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); } } @@ -199,20 +200,20 @@ public class XmlPersistenceTest { public void testReCreate() { try { - logger.info("Trying to recreate..."); + XmlPersistenceTest.logger.info("Trying to recreate..."); // new instance MyClass myClass = new MyClass("@id", "@name", "@subtype"); // persist instance - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); tx.add(myClass); - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); - logger.info("Done creating."); + XmlPersistenceTest.logger.info("Done creating."); } catch (Exception e) { - logger.error(e, e); + XmlPersistenceTest.logger.error(e.getMessage(), e); Assert.fail("Failed: " + e.getLocalizedMessage()); } } @@ -233,10 +234,10 @@ public class XmlPersistenceTest { try { - logger.info("Trying to query all..."); + XmlPersistenceTest.logger.info("Trying to query all..."); // query all - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); List list = tx.queryAll(MyClass.class.getName()); Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); @@ -248,10 +249,10 @@ public class XmlPersistenceTest { list = tx.queryAll(MyClass.class.getName(), "@inexistant"); Assert.assertTrue("Expected no objects, found " + list.size(), list.size() == 0); - logger.info("Done querying."); + XmlPersistenceTest.logger.info("Done querying."); } finally { - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); } } @@ -262,7 +263,7 @@ public class XmlPersistenceTest { public void testKeySet() { try { - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); Set keySet = tx.queryKeySet(MyClass.class.getName()); Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); @@ -276,7 +277,7 @@ public class XmlPersistenceTest { Assert.assertTrue("Expected no keys, found " + keySet, keySet.size() == 0); } finally { - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); } } @@ -287,13 +288,13 @@ public class XmlPersistenceTest { public void testRemoveAll() { try { - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); List objects = tx.queryAll(MyClass.class.getName(), "@subType"); tx.removeAll(objects); } finally { - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); } } @@ -304,13 +305,13 @@ public class XmlPersistenceTest { public void testSize() { try { - XmlPersistenceTransaction tx = persistenceHandler.openTx(); + XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); long size = tx.querySize(MyClass.class.getName(), "@subType"); Assert.assertTrue("Expected size = 0, found: " + size, size == 0); } finally { - persistenceHandler.commitTx(); + XmlPersistenceTest.persistenceHandler.commitTx(); } } } From e5c23a89241bb869e8e01a665467752ea3494e24 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 25 Nov 2012 00:46:19 +0100 Subject: [PATCH 10/87] [Minor] Removed dependency to ch.eitchnet.log4j and thus added log4j.xml The log4j.xml configuration file is in the test resources and now the project is completely free of a dependency to a concrete logging implementation as all logging of the sources is done over slf4j --- pom.xml | 6 ---- src/main/resources/log4j.properties | 12 -------- .../xmlpers/test/XmlPersistenceTest.java | 9 ++---- src/test/resources/log4j.xml | 29 +++++++++++++++++++ 4 files changed, 31 insertions(+), 25 deletions(-) delete mode 100644 src/main/resources/log4j.properties create mode 100644 src/test/resources/log4j.xml diff --git a/pom.xml b/pom.xml index f43055b3e..0cf9eb662 100644 --- a/pom.xml +++ b/pom.xml @@ -122,12 +122,6 @@ ch.eitchnet.utils 0.1.0-SNAPSHOT - - ch.eitchnet - ch.eitchnet.log4j - 0.1.0-SNAPSHOT - test - org.slf4j slf4j-api diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties deleted file mode 100644 index 6aa19bb24..000000000 --- a/src/main/resources/log4j.properties +++ /dev/null @@ -1,12 +0,0 @@ -log4j.rootLogger = info, stdout - -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n - -#log4j.appender.file=org.apache.log4j.RollingFileAppender -#log4j.appender.file.File=${user.dir}/logs/app.log -#log4j.appender.file.MaxFileSize=10000KB -#log4j.appender.file.MaxBackupIndex=0 -#log4j.appender.file.layout=org.apache.log4j.PatternLayout -#log4j.appender.file.layout.ConversionPattern=%d %5p [%t] %C{1} %M - %m%n diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index 4ac22b6ee..6e3f4912a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -23,13 +23,12 @@ import java.io.File; import java.util.List; import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import ch.eitchnet.utils.helper.Log4jConfigurator; import ch.eitchnet.utils.objectfilter.ITransactionObject; import ch.eitchnet.xmlpers.XmlPersistenceExecption; import ch.eitchnet.xmlpers.XmlPersistenceHandler; @@ -53,11 +52,7 @@ public class XmlPersistenceTest { */ @BeforeClass public static void init() throws Exception { - try { - // set up log4j - Log4jConfigurator.configure(); - String userDir = System.getProperty("user.dir"); String basePath = userDir + "/tmp/testdb"; File basePathF = new File(basePath); diff --git a/src/test/resources/log4j.xml b/src/test/resources/log4j.xml new file mode 100644 index 000000000..a35a3c351 --- /dev/null +++ b/src/test/resources/log4j.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 33df39c03cb74a45005687326d9a13da6f324db2 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 21 Jan 2013 18:16:21 +0100 Subject: [PATCH 11/87] Modified XmlDao to have a Document as input to create the DOM representation of the object. --- src/main/java/ch/eitchnet/xmlpers/XmlDao.java | 6 +-- .../ch/eitchnet/xmlpers/XmlFilePersister.java | 47 +++++-------------- .../xmlpers/XmlPersistenceTransaction.java | 13 +++-- .../xmlpers/test/XmlPersistenceTest.java | 4 +- .../xmlpers/test/impl/MyClassDao.java | 20 +------- 5 files changed, 26 insertions(+), 64 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlDao.java b/src/main/java/ch/eitchnet/xmlpers/XmlDao.java index 234c0a9ea..134f290b1 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlDao.java @@ -19,7 +19,6 @@ */ package ch.eitchnet.xmlpers; -import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.ContentHandler; @@ -51,11 +50,10 @@ public interface XmlDao { /** * * @param object - * @param domImplementation + * @param document * @return */ - // XXX think about returning a document, instead of an element, or use document as input - public Document serializeToDom(T object, DOMImplementation domImplementation); + public Element serializeToDom(T object, Document document); /** * @param element diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java index 8049a9946..b077cb1b5 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java @@ -19,9 +19,7 @@ */ package ch.eitchnet.xmlpers; -import java.io.BufferedOutputStream; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -38,19 +36,14 @@ import org.w3c.dom.Element; import org.xml.sax.SAXException; import ch.eitchnet.utils.helper.FileHelper; - -import com.sun.org.apache.xml.internal.serialize.OutputFormat; -import com.sun.org.apache.xml.internal.serialize.XMLSerializer; +import ch.eitchnet.utils.helper.XmlHelper; /** - *@author Robert von Burg + * @author Robert von Burg * */ public class XmlFilePersister { - // - private static final String XML_DEFAULT_ENCODING = "UTF-8"; - private static final Logger logger = LoggerFactory.getLogger(XmlFilePersister.class); private boolean verbose; @@ -89,34 +82,16 @@ public class XmlFilePersister { } if (this.verbose) - XmlFilePersister.logger.info("Persisting " + type + " / " + subType + " / " + id + " to " + pathF.getAbsolutePath() + "..."); + XmlFilePersister.logger.info("Persisting " + type + " / " + subType + " / " + id + " to " + + pathF.getAbsolutePath() + "..."); - BufferedOutputStream outStream = null; try { - outStream = new BufferedOutputStream(new FileOutputStream(pathF)); - - OutputFormat outputFormat = new OutputFormat("XML", XmlFilePersister.XML_DEFAULT_ENCODING, true); - outputFormat.setIndent(1); - outputFormat.setIndenting(true); - //of.setDoctype(null, null); - - XMLSerializer serializer = new XMLSerializer(outStream, outputFormat); - serializer.asDOMSerializer(); - serializer.serialize(document); - outStream.flush(); + XmlHelper.writeDocument(document, pathF); } catch (Exception e) { throw new XmlPersistenceExecption("Could not persist object " + type + " / " + subType + " / " + id + " to " + pathF.getAbsolutePath(), e); - } finally { - if (outStream != null) { - try { - outStream.close(); - } catch (IOException e) { - XmlFilePersister.logger.error(e.getMessage(), e); - } - } } if (this.verbose) @@ -137,12 +112,12 @@ public class XmlFilePersister { pathF = this.xmlPathHelper.getPathF(type, id); if (this.verbose) - XmlFilePersister.logger.info("Remove persistence file for " + type + " / " + subType + " / " + id + " from " - + pathF.getAbsolutePath() + "..."); + XmlFilePersister.logger.info("Remove persistence file for " + type + " / " + subType + " / " + id + + " from " + pathF.getAbsolutePath() + "..."); if (!pathF.exists()) { - XmlFilePersister.logger.error("Persistence file for " + type + " / " + subType + " / " + id + " does not exist at " - + pathF.getAbsolutePath()); + XmlFilePersister.logger.error("Persistence file for " + type + " / " + subType + " / " + id + + " does not exist at " + pathF.getAbsolutePath()); } else if (!pathF.delete()) { throw new XmlPersistenceExecption("Could not delete persistence file for " + type + " / " + subType + " / " + id + " at " + pathF.getAbsolutePath()); @@ -421,8 +396,8 @@ public class XmlFilePersister { File pathF = this.xmlPathHelper.getPathF(type, subType, id); if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " / " + id + " at " + pathF.getAbsolutePath() - + " does not exist, so object does not exist!"); + XmlFilePersister.logger.error("Path for " + type + " / " + subType + " / " + id + " at " + + pathF.getAbsolutePath() + " does not exist, so object does not exist!"); return null; } diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java index 5e9a2664b..fdf1c6a57 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -33,6 +33,7 @@ import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; +import ch.eitchnet.utils.helper.XmlHelper; import ch.eitchnet.utils.objectfilter.ITransactionObject; import ch.eitchnet.utils.objectfilter.ObjectFilter; @@ -279,8 +280,10 @@ public class XmlPersistenceTransaction { String subType = dao.getSubType(object); String id = dao.getId(object); - Document asDom = dao.serializeToDom(object, getDomImpl()); - this.persister.saveOrUpdate(type, subType, id, asDom); + Document doc = XmlHelper.createDocument(); + Element asDom = dao.serializeToDom(object, doc); + doc.appendChild(asDom); + this.persister.saveOrUpdate(type, subType, id, doc); } } @@ -298,8 +301,10 @@ public class XmlPersistenceTransaction { String subType = dao.getSubType(object); String id = dao.getId(object); - Document asDom = dao.serializeToDom(object, getDomImpl()); - this.persister.saveOrUpdate(type, subType, id, asDom); + Document doc = XmlHelper.createDocument(); + Element asDom = dao.serializeToDom(object, doc); + doc.appendChild(asDom); + this.persister.saveOrUpdate(type, subType, id, doc); } } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index 6e3f4912a..bd19e047c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -54,12 +54,12 @@ public class XmlPersistenceTest { public static void init() throws Exception { try { String userDir = System.getProperty("user.dir"); - String basePath = userDir + "/tmp/testdb"; + String basePath = userDir + "/target/testdb"; File basePathF = new File(basePath); if (!basePathF.exists() && !basePathF.mkdirs()) Assert.fail("Could not create temporaray database store in " + basePathF.getAbsolutePath()); - System.setProperty(XmlPersistenceHandler.CONFIG_BASEPATH, "tmp/testdb"); + System.setProperty(XmlPersistenceHandler.CONFIG_BASEPATH, "target/testdb"); System.setProperty(XmlPersistenceHandler.CONFIG_VERBOSE, "true"); System.setProperty(XmlPersistenceHandler.CONFIG_DAO_FACTORY_CLASS, MyDaoFactory.class.getName()); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java index 4686ba349..9e426d13a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java @@ -19,7 +19,6 @@ */ package ch.eitchnet.xmlpers.test.impl; -import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; @@ -35,39 +34,25 @@ import ch.eitchnet.xmlpers.XmlDao; */ public class MyClassDao implements XmlDao { - /** - * @see ch.eitchnet.xmlpers.XmlDao#getType(java.lang.Object) - */ @Override public String getType(MyClass object) { return MyClass.class.getName(); } - /** - * @see ch.eitchnet.xmlpers.XmlDao#getSubType(java.lang.Object) - */ @Override public String getSubType(MyClass object) { return object.getType(); } - /** - * @see ch.eitchnet.xmlpers.XmlDao#getId(java.lang.Object) - */ @Override public String getId(MyClass object) { return object.getId(); } - /** - * @see ch.eitchnet.xmlpers.XmlDao#serializeToDom(java.lang.Object, org.w3c.dom.DOMImplementation) - */ @Override - public Document serializeToDom(MyClass object, DOMImplementation domImplementation) { + public Element serializeToDom(MyClass object, Document document) { - Document document = domImplementation.createDocument(null, null, null); Element element = document.createElement("MyClass"); - document.appendChild(element); element.setAttribute("id", object.getId()); element.setAttribute("type", object.getType()); @@ -77,7 +62,7 @@ public class MyClassDao implements XmlDao { Text textNode = document.createTextNode(object.getName()); nameElement.appendChild(textNode); - return document; + return element; } /** @@ -131,5 +116,4 @@ public class MyClassDao implements XmlDao { throw new RuntimeException("Failed to serialize " + object + " to SAX", e); } } - } From 64e6111c5355a778468c0180100f03f151225ca7 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 21 Jan 2013 18:29:27 +0100 Subject: [PATCH 12/87] Fixed a log message about number of objects added in transaction --- .../java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java index fdf1c6a57..f3641a817 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -293,7 +293,7 @@ public class XmlPersistenceTransaction { XmlPersistenceTransaction.logger.info("No objects added in this tx."); } else { if (this.verbose) - XmlPersistenceTransaction.logger.info(updated.size() + " objects added in this tx."); + XmlPersistenceTransaction.logger.info(added.size() + " objects added in this tx."); for (ITransactionObject object : added) { From 1fbe3cb0908c59a9b0b0bf6a060558f087916f2f Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 30 Jan 2013 14:56:56 +0100 Subject: [PATCH 13/87] Update pom.xml Added distribution management to deploy to nexus.eitchnet.ch --- pom.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pom.xml b/pom.xml index 0cf9eb662..469d460cf 100644 --- a/pom.xml +++ b/pom.xml @@ -109,6 +109,19 @@ ... --> + + + + deployment + Internal Releases + http://nexus.eitchnet.ch/content/repositories/releases/ + + + deployment + Internal Releases + http://nexus.eitchnet.ch/nexus/content/repositories/snapshots/ + + From 8d893d87a0ce25a8e9bf8a74608aecf9b4c09b7c Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 30 Jan 2013 15:05:22 +0100 Subject: [PATCH 14/87] Update pom.xml Added distribution management to deploy to nexus.eitchnet.ch (fixed wrong URL) --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 469d460cf..9343932a7 100644 --- a/pom.xml +++ b/pom.xml @@ -119,7 +119,7 @@ deployment Internal Releases - http://nexus.eitchnet.ch/nexus/content/repositories/snapshots/ + http://nexus.eitchnet.ch/content/repositories/snapshots/ From 4723608d62333249ad613d6de1c1014c7d5ffec3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 24 Feb 2013 11:49:44 +0100 Subject: [PATCH 15/87] [Minor] fixed failing tests on Java 1.7 due to expected execution --- .../xmlpers/test/XmlPersistenceTest.java | 57 +++++++++++-------- 1 file changed, 33 insertions(+), 24 deletions(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index bd19e047c..12aeb4314 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -25,6 +25,7 @@ import java.util.Set; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,10 +77,25 @@ public class XmlPersistenceTest { } /** + * Tests the following story: + *
    + *
  • create object
  • + *
  • read object
  • + *
  • update object
  • + *
  • remove object
  • + *
* */ @Test - public void testCreate() { + public void testPersistenceStory() { + + createObject(); + readObject(); + updateObject(); + removeObject(); + } + + private void createObject() { try { XmlPersistenceTest.logger.info("Trying to create..."); @@ -100,11 +116,7 @@ public class XmlPersistenceTest { } } - /** - * - */ - @Test - public void testRead() { + private void readObject() { try { XmlPersistenceTest.logger.info("Trying to read..."); @@ -123,11 +135,7 @@ public class XmlPersistenceTest { } } - /** - * - */ - @Test - public void testUpdate() { + private void updateObject() { try { XmlPersistenceTest.logger.info("Trying to update an object..."); @@ -152,11 +160,7 @@ public class XmlPersistenceTest { } } - /** - * - */ - @Test - public void testRemove() { + private void removeObject() { XmlPersistenceTest.logger.info("Trying to remove..."); @@ -174,7 +178,7 @@ public class XmlPersistenceTest { /** * */ - @Test(expected = XmlPersistenceExecption.class) + @Test public void testQueryFail() { try { @@ -183,6 +187,10 @@ public class XmlPersistenceTest { MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); XmlPersistenceTest.logger.info("Found MyClass: " + myClass); XmlPersistenceTest.logger.info("Done querying removed object"); + } catch (XmlPersistenceExecption e) { + Assert.assertEquals("Wrong error message. Expected error that object does not exist", + "No object exists for ch.eitchnet.xmlpers.test.impl.MyClass / @subtype / @id", + e.getLocalizedMessage()); } finally { XmlPersistenceTest.persistenceHandler.commitTx(); } @@ -213,13 +221,14 @@ public class XmlPersistenceTest { } } -// /** -// * -// */ -// @Test -// public void testQueryFromTo() { -// Assert.fail("Not yet implemented"); -// } + /** + * + */ + @Test + @Ignore + public void testQueryFromTo() { + Assert.fail("Not yet implemented"); + } /** * From 3310a8d4711dbf9f8ad431e233f2f79779572254 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 13 Mar 2013 17:29:28 +0100 Subject: [PATCH 16/87] Update README.md Described the dependencies, features and how to build of XmlPers --- README.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 816af7f1a..2496f583d 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,35 @@ ch.eitchnet.java.xmlpers ======================== +Generic Java XML persistence layer. Implemented to be light-weight and simple to use -Generic Java XML persistence layer. Implemented to be light-weight and simple to use \ No newline at end of file +Dependencies +------------------------ +XmlPers is built by Maven3 and has very few external dependencies. The current dependencies are: +* the Java Runtime Environment 6 +* ch.eitchnet.utils +* slf4j 1.7.2 +* slf4j-log4j bindings (only during tests) +* JUnit 4.10 (only during tests) + +Features +------------------------ +The idea behind XmlPers is to have a very lightweight database where each object is saved in its own XML file. + +The model for XmlPers is that for each persistable class the following information is available: +* Type (e.g. the class name) +* Optional Sub Type (e.g. some type in your class) +* Id + +This is not forced on the model itself, but in the DAO. Persisting changes is done by delegating to XmlFilePersister and the DAO must convert the object to a XML Document. + +See the tests for a reference implementation. + +Building +------------------------ +*Prerequisites: + * JDK 6 is installed and JAVA_HOME is properly set and ../bin is in path + * Maven 3 is installed and MAVEN_HOME is properly set and ../bin is in path + * ch.eitchnet.utils is installed in your local Maven Repository +* Clone repository and change path to root +* Run maven: + * mvn clean install From 0605dd784f843c48da1eadfa9c40ca2a1d9f1195 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 7 Aug 2013 22:55:18 +0200 Subject: [PATCH 17/87] [Devel] reimplementing using visitor pattern Changing to the visitor pattern will make it easier to implement a SAX reader and writer --- pom.xml | 332 ++++++-------- .../xmlpers/FormattingXmlStreamWriter.java | 432 ++++++++++++++++++ src/main/java/ch/eitchnet/xmlpers/Main.java | 64 +++ .../ch/eitchnet/xmlpers/XmlSaxWriter.java | 31 ++ 4 files changed, 672 insertions(+), 187 deletions(-) create mode 100644 src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/Main.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java diff --git a/pom.xml b/pom.xml index 9343932a7..5394db648 100644 --- a/pom.xml +++ b/pom.xml @@ -1,115 +1,73 @@ - 4.0.0 - ch.eitchnet - ch.eitchnet.xmlpers - jar - 0.1.0-SNAPSHOT - ch.eitchnet.xmlpers - https://github.com/eitch/ch.eitchnet.xmlpers + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> + 4.0.0 + ch.eitchnet + ch.eitchnet.xmlpers + jar + 0.1.0-SNAPSHOT + ch.eitchnet.xmlpers + https://github.com/eitch/ch.eitchnet.xmlpers - - UTF-8 - + + UTF-8 + - + - 2011 - - - GNU Lesser General Public License - http://www.gnu.org/licenses/lgpl.html - repo - - - - eitchnet.ch - http://blog.eitchnet.ch - - - - eitch - Robert von Vurg - eitch@eitchnet.ch - http://blog.eitchnet.ch - eitchnet.ch - http://blog.eitchnet.ch - - architect - developer - - +1 - - http://localhost - - - + 2011 + + + GNU Lesser General Public License + http://www.gnu.org/licenses/lgpl.html + repo + + + + eitchnet.ch + http://blog.eitchnet.ch + + + + eitch + Robert von Vurg + eitch@eitchnet.ch + http://blog.eitchnet.ch + eitchnet.ch + http://blog.eitchnet.ch + + architect + developer + + +1 + + http://localhost + + + - - Github Issues - https://github.com/eitch/ch.eitchnet.xmlpers/issues - + + Github Issues + https://github.com/eitch/ch.eitchnet.xmlpers/issues + - - - - User List - user-subscribe@127.0.0.1 - user-unsubscribe@127.0.0.1 - user@127.0.0.1 - http://127.0.0.1/user/ - - http://base.google.com/base/1/127.0.0.1 - - - - --> + + scm:git:https://github.com/eitch/ch.eitchnet.xmlpers.git + scm:git:git@github.com:eitch/ch.eitchnet.xmlpers.git + https://github.com/eitch/ch.eitchnet.xmlpers + - - scm:git:https://github.com/eitch/ch.eitchnet.xmlpers.git - scm:git:git@github.com:eitch/ch.eitchnet.xmlpers.git - https://github.com/eitch/ch.eitchnet.xmlpers - + - - deployment @@ -123,93 +81,93 @@ - - - junit - junit - 4.10 - test - - - ch.eitchnet - ch.eitchnet.utils - 0.1.0-SNAPSHOT - - - org.slf4j - slf4j-api - 1.7.2 - - - org.slf4j - slf4j-log4j12 - 1.7.2 - test - - + + + junit + junit + 4.10 + test + + + ch.eitchnet + ch.eitchnet.utils + 0.1.0-SNAPSHOT + + + org.slf4j + slf4j-api + 1.7.2 + + + org.slf4j + slf4j-log4j12 + 1.7.2 + test + + - - - - - org.apache.maven.plugins - maven-eclipse-plugin - 2.9 - - true - true - - + + - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - + + org.apache.maven.plugins + maven-eclipse-plugin + 2.9 + + true + true + + - - org.apache.maven.plugins - maven-jar-plugin - 2.4 - - - - true - true - - - - - + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + - - org.apache.maven.plugins - maven-site-plugin - 2.3 - - UTF-8 - - + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + - - + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + true + true + + + + + + + + org.apache.maven.plugins + maven-site-plugin + 2.3 + + UTF-8 + + + + + diff --git a/src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java b/src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java new file mode 100644 index 000000000..b3ae34e91 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java @@ -0,0 +1,432 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * @author Robert von Burg + */ +public class FormattingXmlStreamWriter implements XMLStreamWriter { + + private final XMLStreamWriter writer; + + /** + * + * @param writer + */ + public FormattingXmlStreamWriter(XMLStreamWriter writer) { + this.writer = writer; + } + + // + // Start of elements + // + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartDocument() + */ + @Override + public void writeStartDocument() throws XMLStreamException { + preStart(); + this.writer.writeStartDocument(); + postStart(); + } + + private void preStart() { + + } + + private void postStart() throws XMLStreamException { + //this.writer.writeCharacters(new char[] { '\n' }, 0, 1); + } + + private void preEnd() { + } + + private void postEnd() { + } + + /** + * @param version + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartDocument(java.lang.String) + */ + @Override + public void writeStartDocument(String version) throws XMLStreamException { + preStart(); + this.writer.writeStartDocument(version); + postStart(); + } + + /** + * @param encoding + * @param version + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartDocument(java.lang.String, java.lang.String) + */ + @Override + public void writeStartDocument(String encoding, String version) throws XMLStreamException { + preStart(); + this.writer.writeStartDocument(encoding, version); + postStart(); + } + + /** + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String) + */ + @Override + public void writeStartElement(String localName) throws XMLStreamException { + preStart(); + this.writer.writeStartElement(localName); + postStart(); + } + + /** + * @param namespaceURI + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String) + */ + @Override + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + preStart(); + this.writer.writeStartElement(namespaceURI, localName); + postStart(); + } + + /** + * @param prefix + * @param localName + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + preStart(); + this.writer.writeStartElement(prefix, localName, namespaceURI); + postStart(); + } + + // + // End of elements + // + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEndElement() + */ + @Override + public void writeEndElement() throws XMLStreamException { + preStart(); + this.writer.writeEndElement(); + postStart(); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEndDocument() + */ + @Override + public void writeEndDocument() throws XMLStreamException { + preStart(); + this.writer.writeEndDocument(); + postStart(); + } + + // + // Empty elements + // + + /** + * @param namespaceURI + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String, java.lang.String) + */ + @Override + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + preEnd(); + this.writer.writeEmptyElement(namespaceURI, localName); + postEnd(); + } + + /** + * @param prefix + * @param localName + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + preEnd(); + this.writer.writeEmptyElement(prefix, localName, namespaceURI); + postEnd(); + } + + /** + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String) + */ + @Override + public void writeEmptyElement(String localName) throws XMLStreamException { + this.writer.writeEmptyElement(localName); + } + + // + // attributes + // + + /** + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String) + */ + @Override + public void writeAttribute(String localName, String value) throws XMLStreamException { + this.writer.writeAttribute(localName, value); + } + + /** + * @param prefix + * @param namespaceURI + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String, java.lang.String, + * java.lang.String) + */ + @Override + public void writeAttribute(String prefix, String namespaceURI, String localName, String value) + throws XMLStreamException { + this.writer.writeAttribute(prefix, namespaceURI, localName, value); + } + + /** + * @param namespaceURI + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { + this.writer.writeAttribute(namespaceURI, localName, value); + } + + // + // other + // + + /** + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeComment(java.lang.String) + */ + @Override + public void writeComment(String data) throws XMLStreamException { + this.writer.writeComment(data); + } + + /** + * @param target + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeProcessingInstruction(java.lang.String) + */ + @Override + public void writeProcessingInstruction(String target) throws XMLStreamException { + this.writer.writeProcessingInstruction(target); + } + + /** + * @param target + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeProcessingInstruction(java.lang.String, java.lang.String) + */ + @Override + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + this.writer.writeProcessingInstruction(target, data); + } + + /** + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCData(java.lang.String) + */ + @Override + public void writeCData(String data) throws XMLStreamException { + this.writer.writeCData(data); + } + + /** + * @param dtd + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeDTD(java.lang.String) + */ + @Override + public void writeDTD(String dtd) throws XMLStreamException { + this.writer.writeDTD(dtd); + } + + /** + * @param prefix + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeNamespace(java.lang.String, java.lang.String) + */ + @Override + public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { + this.writer.writeNamespace(prefix, namespaceURI); + } + + /** + * @param namespaceURI + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeDefaultNamespace(java.lang.String) + */ + @Override + public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { + this.writer.writeDefaultNamespace(namespaceURI); + } + + /** + * @param name + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEntityRef(java.lang.String) + */ + @Override + public void writeEntityRef(String name) throws XMLStreamException { + this.writer.writeEntityRef(name); + } + + /** + * @param text + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCharacters(java.lang.String) + */ + @Override + public void writeCharacters(String text) throws XMLStreamException { + this.writer.writeCharacters(text); + } + + /** + * @param text + * @param start + * @param len + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCharacters(char[], int, int) + */ + @Override + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + this.writer.writeCharacters(text, start, len); + } + + /** + * @param uri + * @return + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#getPrefix(java.lang.String) + */ + @Override + public String getPrefix(String uri) throws XMLStreamException { + return this.writer.getPrefix(uri); + } + + /** + * @param prefix + * @param uri + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#setPrefix(java.lang.String, java.lang.String) + */ + @Override + public void setPrefix(String prefix, String uri) throws XMLStreamException { + this.writer.setPrefix(prefix, uri); + } + + /** + * @param uri + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#setDefaultNamespace(java.lang.String) + */ + @Override + public void setDefaultNamespace(String uri) throws XMLStreamException { + this.writer.setDefaultNamespace(uri); + } + + /** + * @param context + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#setNamespaceContext(javax.xml.namespace.NamespaceContext) + */ + @Override + public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { + this.writer.setNamespaceContext(context); + } + + /** + * @return + * @see javax.xml.stream.XMLStreamWriter#getNamespaceContext() + */ + @Override + public NamespaceContext getNamespaceContext() { + return this.writer.getNamespaceContext(); + } + + /** + * @param name + * @return + * @throws IllegalArgumentException + * @see javax.xml.stream.XMLStreamWriter#getProperty(java.lang.String) + */ + @Override + public Object getProperty(String name) throws IllegalArgumentException { + return this.writer.getProperty(name); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#close() + */ + @Override + public void close() throws XMLStreamException { + this.writer.close(); + } + + /** + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#flush() + */ + @Override + public void flush() throws XMLStreamException { + this.writer.flush(); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/Main.java b/src/main/java/ch/eitchnet/xmlpers/Main.java new file mode 100644 index 000000000..b9717ab6f --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/Main.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers; + +import java.io.File; +import java.io.FileWriter; + +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamWriter; + +/** + * @author Robert von Burg + * + */ +public class Main { + + public static void main(String[] args) throws Exception { + + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + + File file = new File("output.xml"); + XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file)); + System.out.println("writer: " + writer.getClass().getName()); + + //writer = new com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter(writer); + writer = new FormattingXmlStreamWriter(writer); + + writer.writeStartDocument(); + writer.writeStartElement("document"); + writer.writeStartElement("data"); + writer.writeAttribute("name", "value"); + writer.writeEndElement(); + writer.writeEndElement(); + writer.writeEndDocument(); + + writer.flush(); + writer.close(); + System.out.println("Wrote to " + file.getAbsolutePath()); + + //Transformer transformer = TransformerFactory.newInstance().newTransformer(); + //Result outputTarget = new StaxR; + //Source xmlSource; + //transformer.transform(xmlSource, outputTarget); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java b/src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java new file mode 100644 index 000000000..8a8a80609 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers; + + +/** + * @author Robert von Burg + * + */ +public interface XmlSaxWriter { + +} From 3b2a3970632a82148bd789686d8797ede2b547ea Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 8 Aug 2013 00:34:49 +0200 Subject: [PATCH 18/87] [Devel] still implementing new visitor pattern --- pom.xml | 2 +- .../xmlpers/FormattingXmlStreamWriter.java | 432 ------------------ src/main/java/ch/eitchnet/xmlpers/Main.java | 13 +- .../xmlpers/XmlPersistenceHandler.java | 26 +- .../xmlpers/XmlPersistencePathBuilder.java | 7 - .../xmlpers/XmlPersistenceTransaction.java | 5 +- .../java/javanet/staxutils/Indentation.java | 38 ++ .../staxutils/IndentingXMLStreamWriter.java | 352 ++++++++++++++ .../helpers/StreamWriterDelegate.java | 185 ++++++++ 9 files changed, 587 insertions(+), 473 deletions(-) delete mode 100644 src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java create mode 100644 src/main/java/javanet/staxutils/Indentation.java create mode 100644 src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java create mode 100644 src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java diff --git a/pom.xml b/pom.xml index 5394db648..6f22a98db 100644 --- a/pom.xml +++ b/pom.xml @@ -91,7 +91,7 @@ ch.eitchnet ch.eitchnet.utils - 0.1.0-SNAPSHOT + 0.2.0-SNAPSHOT org.slf4j diff --git a/src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java b/src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java deleted file mode 100644 index b3ae34e91..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/FormattingXmlStreamWriter.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers; - -import javax.xml.namespace.NamespaceContext; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -/** - * @author Robert von Burg - */ -public class FormattingXmlStreamWriter implements XMLStreamWriter { - - private final XMLStreamWriter writer; - - /** - * - * @param writer - */ - public FormattingXmlStreamWriter(XMLStreamWriter writer) { - this.writer = writer; - } - - // - // Start of elements - // - - /** - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartDocument() - */ - @Override - public void writeStartDocument() throws XMLStreamException { - preStart(); - this.writer.writeStartDocument(); - postStart(); - } - - private void preStart() { - - } - - private void postStart() throws XMLStreamException { - //this.writer.writeCharacters(new char[] { '\n' }, 0, 1); - } - - private void preEnd() { - } - - private void postEnd() { - } - - /** - * @param version - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartDocument(java.lang.String) - */ - @Override - public void writeStartDocument(String version) throws XMLStreamException { - preStart(); - this.writer.writeStartDocument(version); - postStart(); - } - - /** - * @param encoding - * @param version - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartDocument(java.lang.String, java.lang.String) - */ - @Override - public void writeStartDocument(String encoding, String version) throws XMLStreamException { - preStart(); - this.writer.writeStartDocument(encoding, version); - postStart(); - } - - /** - * @param localName - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String) - */ - @Override - public void writeStartElement(String localName) throws XMLStreamException { - preStart(); - this.writer.writeStartElement(localName); - postStart(); - } - - /** - * @param namespaceURI - * @param localName - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String) - */ - @Override - public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - preStart(); - this.writer.writeStartElement(namespaceURI, localName); - postStart(); - } - - /** - * @param prefix - * @param localName - * @param namespaceURI - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - preStart(); - this.writer.writeStartElement(prefix, localName, namespaceURI); - postStart(); - } - - // - // End of elements - // - - /** - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEndElement() - */ - @Override - public void writeEndElement() throws XMLStreamException { - preStart(); - this.writer.writeEndElement(); - postStart(); - } - - /** - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEndDocument() - */ - @Override - public void writeEndDocument() throws XMLStreamException { - preStart(); - this.writer.writeEndDocument(); - postStart(); - } - - // - // Empty elements - // - - /** - * @param namespaceURI - * @param localName - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String, java.lang.String) - */ - @Override - public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - preEnd(); - this.writer.writeEmptyElement(namespaceURI, localName); - postEnd(); - } - - /** - * @param prefix - * @param localName - * @param namespaceURI - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - preEnd(); - this.writer.writeEmptyElement(prefix, localName, namespaceURI); - postEnd(); - } - - /** - * @param localName - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String) - */ - @Override - public void writeEmptyElement(String localName) throws XMLStreamException { - this.writer.writeEmptyElement(localName); - } - - // - // attributes - // - - /** - * @param localName - * @param value - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String) - */ - @Override - public void writeAttribute(String localName, String value) throws XMLStreamException { - this.writer.writeAttribute(localName, value); - } - - /** - * @param prefix - * @param namespaceURI - * @param localName - * @param value - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String, java.lang.String, - * java.lang.String) - */ - @Override - public void writeAttribute(String prefix, String namespaceURI, String localName, String value) - throws XMLStreamException { - this.writer.writeAttribute(prefix, namespaceURI, localName, value); - } - - /** - * @param namespaceURI - * @param localName - * @param value - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String, java.lang.String) - */ - @Override - public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { - this.writer.writeAttribute(namespaceURI, localName, value); - } - - // - // other - // - - /** - * @param data - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeComment(java.lang.String) - */ - @Override - public void writeComment(String data) throws XMLStreamException { - this.writer.writeComment(data); - } - - /** - * @param target - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeProcessingInstruction(java.lang.String) - */ - @Override - public void writeProcessingInstruction(String target) throws XMLStreamException { - this.writer.writeProcessingInstruction(target); - } - - /** - * @param target - * @param data - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeProcessingInstruction(java.lang.String, java.lang.String) - */ - @Override - public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - this.writer.writeProcessingInstruction(target, data); - } - - /** - * @param data - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeCData(java.lang.String) - */ - @Override - public void writeCData(String data) throws XMLStreamException { - this.writer.writeCData(data); - } - - /** - * @param dtd - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeDTD(java.lang.String) - */ - @Override - public void writeDTD(String dtd) throws XMLStreamException { - this.writer.writeDTD(dtd); - } - - /** - * @param prefix - * @param namespaceURI - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeNamespace(java.lang.String, java.lang.String) - */ - @Override - public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { - this.writer.writeNamespace(prefix, namespaceURI); - } - - /** - * @param namespaceURI - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeDefaultNamespace(java.lang.String) - */ - @Override - public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { - this.writer.writeDefaultNamespace(namespaceURI); - } - - /** - * @param name - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEntityRef(java.lang.String) - */ - @Override - public void writeEntityRef(String name) throws XMLStreamException { - this.writer.writeEntityRef(name); - } - - /** - * @param text - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeCharacters(java.lang.String) - */ - @Override - public void writeCharacters(String text) throws XMLStreamException { - this.writer.writeCharacters(text); - } - - /** - * @param text - * @param start - * @param len - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeCharacters(char[], int, int) - */ - @Override - public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - this.writer.writeCharacters(text, start, len); - } - - /** - * @param uri - * @return - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#getPrefix(java.lang.String) - */ - @Override - public String getPrefix(String uri) throws XMLStreamException { - return this.writer.getPrefix(uri); - } - - /** - * @param prefix - * @param uri - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#setPrefix(java.lang.String, java.lang.String) - */ - @Override - public void setPrefix(String prefix, String uri) throws XMLStreamException { - this.writer.setPrefix(prefix, uri); - } - - /** - * @param uri - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#setDefaultNamespace(java.lang.String) - */ - @Override - public void setDefaultNamespace(String uri) throws XMLStreamException { - this.writer.setDefaultNamespace(uri); - } - - /** - * @param context - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#setNamespaceContext(javax.xml.namespace.NamespaceContext) - */ - @Override - public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { - this.writer.setNamespaceContext(context); - } - - /** - * @return - * @see javax.xml.stream.XMLStreamWriter#getNamespaceContext() - */ - @Override - public NamespaceContext getNamespaceContext() { - return this.writer.getNamespaceContext(); - } - - /** - * @param name - * @return - * @throws IllegalArgumentException - * @see javax.xml.stream.XMLStreamWriter#getProperty(java.lang.String) - */ - @Override - public Object getProperty(String name) throws IllegalArgumentException { - return this.writer.getProperty(name); - } - - /** - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#close() - */ - @Override - public void close() throws XMLStreamException { - this.writer.close(); - } - - /** - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#flush() - */ - @Override - public void flush() throws XMLStreamException { - this.writer.flush(); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/Main.java b/src/main/java/ch/eitchnet/xmlpers/Main.java index b9717ab6f..64ebde257 100644 --- a/src/main/java/ch/eitchnet/xmlpers/Main.java +++ b/src/main/java/ch/eitchnet/xmlpers/Main.java @@ -24,6 +24,8 @@ package ch.eitchnet.xmlpers; import java.io.File; import java.io.FileWriter; +import javanet.staxutils.IndentingXMLStreamWriter; + import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; @@ -41,15 +43,16 @@ public class Main { XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file)); System.out.println("writer: " + writer.getClass().getName()); - //writer = new com.sun.xml.internal.txw2.output.IndentingXMLStreamWriter(writer); - writer = new FormattingXmlStreamWriter(writer); + writer = new IndentingXMLStreamWriter(writer); writer.writeStartDocument(); writer.writeStartElement("document"); - writer.writeStartElement("data"); + writer.writeEmptyElement("data"); writer.writeAttribute("name", "value"); - writer.writeEndElement(); - writer.writeEndElement(); + //writer.writeEndElement(); + writer.writeEmptyElement("stuff"); + writer.writeAttribute("attr", "attrVal"); + //writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java index c615795ac..a393e72b9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java @@ -23,7 +23,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.SystemHelper; -import ch.eitchnet.utils.objectfilter.ITransactionObject; import ch.eitchnet.utils.objectfilter.ObjectFilter; /** @@ -32,19 +31,8 @@ import ch.eitchnet.utils.objectfilter.ObjectFilter; */ public class XmlPersistenceHandler { - /** - * - */ public static final String CONFIG_VERBOSE = "ch.eitchnet.xmlpers.config.verbose"; - - /** - * - */ public static final String CONFIG_BASEPATH = "ch.eitchnet.xmlpers.config.basepath"; - - /** - * - */ public static final String CONFIG_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers.config.daoFactoryClass"; protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandler.class); @@ -54,9 +42,6 @@ public class XmlPersistenceHandler { protected XmlFilePersister persister; protected XmlDaoFactory xmlDaoFactory; - /** - * - */ public void initialize() { String basePath = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), XmlPersistenceHandler.CONFIG_BASEPATH, null); @@ -85,9 +70,6 @@ public class XmlPersistenceHandler { this.xmlPersistenceTxThreadLocal = new ThreadLocal(); } - /** - * - */ public XmlPersistenceTransaction openTx() { if (this.verbose) @@ -99,7 +81,7 @@ public class XmlPersistenceHandler { throw new XmlPersistenceExecption("Previous transaction not properly closed"); // set a new persistence transaction object - ObjectFilter objectFilter = new ObjectFilter(); + ObjectFilter objectFilter = new ObjectFilter(); xmlPersistenceTx = new XmlPersistenceTransaction(); xmlPersistenceTx.initialize(this.persister, this.xmlDaoFactory, objectFilter, this.verbose); @@ -108,9 +90,6 @@ public class XmlPersistenceHandler { return xmlPersistenceTx; } - /** - * - */ public XmlPersistenceTransaction getTx() { XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); if (xmlPersistenceTx == null) @@ -119,9 +98,6 @@ public class XmlPersistenceHandler { return xmlPersistenceTx; } - /** - * - */ public void commitTx() { if (this.verbose) diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java index b92107cfc..baa894740 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java @@ -32,14 +32,7 @@ import org.slf4j.LoggerFactory; public class XmlPersistencePathBuilder { private static final Logger logger = LoggerFactory.getLogger(XmlPersistencePathBuilder.class); - /** - * - */ public static final String FILE_EXT = ".xml"; - - /** - * - */ public static final int EXT_LENGTH = XmlPersistencePathBuilder.FILE_EXT.length(); private String basePath; diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java index f3641a817..9d2f3f2b0 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java @@ -39,7 +39,6 @@ import ch.eitchnet.utils.objectfilter.ObjectFilter; /** * @author Robert von Burg - * */ public class XmlPersistenceTransaction { @@ -48,7 +47,7 @@ public class XmlPersistenceTransaction { private boolean verbose; private XmlFilePersister persister; private XmlDaoFactory xmlDaoFactory; - private ObjectFilter objectFilter; + private ObjectFilter objectFilter; private DocumentBuilder docBuilder; private DOMImplementation domImplementation; @@ -58,7 +57,7 @@ public class XmlPersistenceTransaction { * @param objectFilter */ public void initialize(XmlFilePersister persister, XmlDaoFactory xmlDaoFactory, - ObjectFilter objectFilter, boolean verbose) { + ObjectFilter objectFilter, boolean verbose) { this.persister = persister; this.xmlDaoFactory = xmlDaoFactory; this.objectFilter = objectFilter; diff --git a/src/main/java/javanet/staxutils/Indentation.java b/src/main/java/javanet/staxutils/Indentation.java new file mode 100644 index 000000000..4dfa7b48e --- /dev/null +++ b/src/main/java/javanet/staxutils/Indentation.java @@ -0,0 +1,38 @@ +package javanet.staxutils; + +/** + * Characters that represent line breaks and indentation. These are represented + * as String-valued JavaBean properties. + */ +public interface Indentation { + + /** Two spaces; the default indentation. */ + public static final String DEFAULT_INDENT = " "; + + /** + * Set the characters used for one level of indentation. The default is + * {@link #DEFAULT_INDENT}. "\t" is a popular alternative. + */ + void setIndent(String indent); + + /** The characters used for one level of indentation. */ + String getIndent(); + + /** + * "\n"; the normalized representation of end-of-line in XML. + */ + public static final String NORMAL_END_OF_LINE = "\n"; + + /** + * Set the characters that introduce a new line. The default is + * {@link #NORMAL_END_OF_LINE}. + * {@link IndentingXMLStreamWriter#getLineSeparator}() is a popular + * alternative. + */ + public void setNewLine(String newLine); + + /** The characters that introduce a new line. */ + String getNewLine(); + +} diff --git a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java new file mode 100644 index 000000000..9e09a7be0 --- /dev/null +++ b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2006, John Kristian + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of StAX-Utils nor the names of its contributors + * may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +package javanet.staxutils; + +import javanet.staxutils.helpers.StreamWriterDelegate; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * A filter that indents an XML stream. To apply it, construct a filter that + * contains another {@link XMLStreamWriter}, which you pass to the constructor. + * Then call methods of the filter instead of the contained stream. For example: + * + *
+ * {@link XMLStreamWriter} stream = ...
+ * stream = new {@link IndentingXMLStreamWriter}(stream);
+ * stream.writeStartDocument();
+ * ...
+ * 
+ * + *

+ * The filter inserts characters to format the document as an outline, with + * nested elements indented. Basically, it inserts a line break and whitespace + * before: + *

    + *
  • each DTD, processing instruction or comment that's not preceded by data
  • + *
  • each starting tag that's not preceded by data
  • + *
  • each ending tag that's preceded by nested elements but not data
  • + *
+ * This works well with 'data-oriented' XML, wherein each element contains + * either data or nested elements but not both. It can work badly with other + * styles of XML. For example, the data in a 'mixed content' document are apt to + * be polluted with indentation characters. + *

+ * Indentation can be adjusted by setting the newLine and indent properties. But + * set them to whitespace only, for best results. Non-whitespace is apt to cause + * problems, for example when this class attempts to insert newLine before the + * root element. + * + * @author John Kristian + */ +public class IndentingXMLStreamWriter extends StreamWriterDelegate implements Indentation { + + public IndentingXMLStreamWriter(XMLStreamWriter out) { + this(out, DEFAULT_INDENT, NORMAL_END_OF_LINE); + } + + public IndentingXMLStreamWriter(XMLStreamWriter out, String indent) { + this(out, indent, NORMAL_END_OF_LINE); + } + + public IndentingXMLStreamWriter(XMLStreamWriter out, String indent, String newLine) { + super(out); + setIndent(indent); + setNewLine(newLine); + } + + /** How deeply nested the current scope is. The root element is depth 1. */ + private int depth = 0; // document scope + + /** stack[depth] indicates what's been written into the current scope. */ + private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet + + private static final int WROTE_MARKUP = 1; + + private static final int WROTE_DATA = 2; + + private String indent = DEFAULT_INDENT; + + private String newLine = NORMAL_END_OF_LINE; + + /** newLine followed by copies of indent. */ + private char[] linePrefix = null; + + public void setIndent(String indent) { + if (!indent.equals(this.indent)) { + this.indent = indent; + linePrefix = null; + } + } + + public String getIndent() { + return indent; + } + + public void setNewLine(String newLine) { + if (!newLine.equals(this.newLine)) { + this.newLine = newLine; + linePrefix = null; + } + } + + /** + * @return System.getProperty("line.separator"); or + * {@link #NORMAL_END_OF_LINE} if that fails. + */ + public static String getLineSeparator() { + try { + return System.getProperty("line.separator"); + } catch (SecurityException ignored) { + } + return NORMAL_END_OF_LINE; + } + + public String getNewLine() { + return newLine; + } + + public void writeStartDocument() throws XMLStreamException { + beforeMarkup(); + out.writeStartDocument(); + afterMarkup(); + } + + public void writeStartDocument(String version) throws XMLStreamException { + beforeMarkup(); + out.writeStartDocument(version); + afterMarkup(); + } + + public void writeStartDocument(String encoding, String version) throws XMLStreamException { + beforeMarkup(); + out.writeStartDocument(encoding, version); + afterMarkup(); + } + + public void writeDTD(String dtd) throws XMLStreamException { + beforeMarkup(); + out.writeDTD(dtd); + afterMarkup(); + } + + public void writeProcessingInstruction(String target) throws XMLStreamException { + beforeMarkup(); + out.writeProcessingInstruction(target); + afterMarkup(); + } + + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + beforeMarkup(); + out.writeProcessingInstruction(target, data); + afterMarkup(); + } + + public void writeComment(String data) throws XMLStreamException { + beforeMarkup(); + out.writeComment(data); + afterMarkup(); + } + + public void writeEmptyElement(String localName) throws XMLStreamException { + beforeMarkup(); + out.writeEmptyElement(localName); + afterMarkup(); + } + + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + beforeMarkup(); + out.writeEmptyElement(namespaceURI, localName); + afterMarkup(); + } + + public void writeEmptyElement(String prefix, String localName, String namespaceURI) + throws XMLStreamException { + beforeMarkup(); + out.writeEmptyElement(prefix, localName, namespaceURI); + afterMarkup(); + } + + public void writeStartElement(String localName) throws XMLStreamException { + beforeStartElement(); + out.writeStartElement(localName); + afterStartElement(); + } + + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + beforeStartElement(); + out.writeStartElement(namespaceURI, localName); + afterStartElement(); + } + + public void writeStartElement(String prefix, String localName, String namespaceURI) + throws XMLStreamException { + beforeStartElement(); + out.writeStartElement(prefix, localName, namespaceURI); + afterStartElement(); + } + + public void writeCharacters(String text) throws XMLStreamException { + out.writeCharacters(text); + afterData(); + } + + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + out.writeCharacters(text, start, len); + afterData(); + } + + public void writeCData(String data) throws XMLStreamException { + out.writeCData(data); + afterData(); + } + + public void writeEntityRef(String name) throws XMLStreamException { + out.writeEntityRef(name); + afterData(); + } + + public void writeEndElement() throws XMLStreamException { + beforeEndElement(); + out.writeEndElement(); + afterEndElement(); + } + + public void writeEndDocument() throws XMLStreamException { + try { + while (depth > 0) { + writeEndElement(); // indented + } + } catch (Exception ignored) { + ignored.printStackTrace(); + } + out.writeEndDocument(); + afterEndDocument(); + } + + /** Prepare to write markup, by writing a new line and indentation. */ + protected void beforeMarkup() { + int soFar = stack[depth]; + if ((soFar & WROTE_DATA) == 0 // no data in this scope + && (depth > 0 || soFar != 0)) // not the first line + { + try { + writeNewLine(depth); + if (depth > 0 && getIndent().length() > 0) { + afterMarkup(); // indentation was written + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + /** Note that markup or indentation was written. */ + protected void afterMarkup() { + stack[depth] |= WROTE_MARKUP; + } + + /** Note that data were written. */ + protected void afterData() { + stack[depth] |= WROTE_DATA; + } + + /** Prepare to start an element, by allocating stack space. */ + protected void beforeStartElement() { + beforeMarkup(); + if (stack.length <= depth + 1) { + // Allocate more space for the stack: + int[] newStack = new int[stack.length * 2]; + System.arraycopy(stack, 0, newStack, 0, stack.length); + stack = newStack; + } + stack[depth + 1] = 0; // nothing written yet + } + + /** Note that an element was started. */ + protected void afterStartElement() { + afterMarkup(); + ++depth; + } + + /** Prepare to end an element, by writing a new line and indentation. */ + protected void beforeEndElement() { + if (depth > 0 && stack[depth] == WROTE_MARKUP) { // but not data + try { + writeNewLine(depth - 1); + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } + } + + /** Note that an element was ended. */ + protected void afterEndElement() { + if (depth > 0) { + --depth; + } + } + + /** Note that a document was ended. */ + protected void afterEndDocument() { + if (stack[depth = 0] == WROTE_MARKUP) { // but not data + try { + writeNewLine(0); + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } + stack[depth] = 0; // start fresh + } + + /** Write a line separator followed by indentation. */ + protected void writeNewLine(int indentation) throws XMLStreamException { + final int newLineLength = getNewLine().length(); + final int prefixLength = newLineLength + (getIndent().length() * indentation); + if (prefixLength > 0) { + if (linePrefix == null) { + linePrefix = (getNewLine() + getIndent()).toCharArray(); + } + while (prefixLength > linePrefix.length) { + // make linePrefix longer: + char[] newPrefix = new char[newLineLength + + ((linePrefix.length - newLineLength) * 2)]; + System.arraycopy(linePrefix, 0, newPrefix, 0, linePrefix.length); + System.arraycopy(linePrefix, newLineLength, newPrefix, linePrefix.length, + linePrefix.length - newLineLength); + linePrefix = newPrefix; + } + out.writeCharacters(linePrefix, 0, prefixLength); + } + } + +} diff --git a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java new file mode 100644 index 000000000..edba1f7f5 --- /dev/null +++ b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java @@ -0,0 +1,185 @@ +/* + * Copyright (c) 2006, John Kristian + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * * Neither the name of StAX-Utils nor the names of its contributors + * may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +package javanet.staxutils.helpers; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * Abstract class for writing filtered XML streams. This class provides methods + * that merely delegate to the contained stream. Subclasses should override some + * of these methods, and may also provide additional methods and fields. + * + * @author John Kristian + */ +public abstract class StreamWriterDelegate implements XMLStreamWriter { + + protected StreamWriterDelegate(XMLStreamWriter out) { + this.out = out; + } + + protected XMLStreamWriter out; + + public Object getProperty(String name) throws IllegalArgumentException { + return out.getProperty(name); + } + + public NamespaceContext getNamespaceContext() { + return out.getNamespaceContext(); + } + + public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { + out.setNamespaceContext(context); + } + + public void setDefaultNamespace(String uri) throws XMLStreamException { + out.setDefaultNamespace(uri); + } + + public void writeStartDocument() throws XMLStreamException { + out.writeStartDocument(); + } + + public void writeStartDocument(String version) throws XMLStreamException { + out.writeStartDocument(version); + } + + public void writeStartDocument(String encoding, String version) throws XMLStreamException { + out.writeStartDocument(encoding, version); + } + + public void writeDTD(String dtd) throws XMLStreamException { + out.writeDTD(dtd); + } + + public void writeProcessingInstruction(String target) throws XMLStreamException { + out.writeProcessingInstruction(target); + } + + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + out.writeProcessingInstruction(target, data); + } + + public void writeComment(String data) throws XMLStreamException { + out.writeComment(data); + } + + public void writeEmptyElement(String localName) throws XMLStreamException { + out.writeEmptyElement(localName); + } + + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + out.writeEmptyElement(namespaceURI, localName); + } + + public void writeEmptyElement(String prefix, String localName, String namespaceURI) + throws XMLStreamException { + out.writeEmptyElement(prefix, localName, namespaceURI); + } + + public void writeStartElement(String localName) throws XMLStreamException { + out.writeStartElement(localName); + } + + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + out.writeStartElement(namespaceURI, localName); + } + + public void writeStartElement(String prefix, String localName, String namespaceURI) + throws XMLStreamException { + out.writeStartElement(prefix, localName, namespaceURI); + } + + public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { + out.writeDefaultNamespace(namespaceURI); + } + + public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { + out.writeNamespace(prefix, namespaceURI); + } + + public String getPrefix(String uri) throws XMLStreamException { + return out.getPrefix(uri); + } + + public void setPrefix(String prefix, String uri) throws XMLStreamException { + out.setPrefix(prefix, uri); + } + + public void writeAttribute(String localName, String value) throws XMLStreamException { + out.writeAttribute(localName, value); + } + + public void writeAttribute(String namespaceURI, String localName, String value) + throws XMLStreamException { + out.writeAttribute(namespaceURI, localName, value); + } + + public void writeAttribute(String prefix, String namespaceURI, String localName, String value) + throws XMLStreamException { + out.writeAttribute(prefix, namespaceURI, localName, value); + } + + public void writeCharacters(String text) throws XMLStreamException { + out.writeCharacters(text); + } + + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + out.writeCharacters(text, start, len); + } + + public void writeCData(String data) throws XMLStreamException { + out.writeCData(data); + } + + public void writeEntityRef(String name) throws XMLStreamException { + out.writeEntityRef(name); + } + + public void writeEndElement() throws XMLStreamException { + out.writeEndElement(); + } + + public void writeEndDocument() throws XMLStreamException { + out.writeEndDocument(); + } + + public void flush() throws XMLStreamException { + out.flush(); + } + + public void close() throws XMLStreamException { + out.close(); + } + +} From f391055c6a9d3cb32b16fda8bb9197a1503a47e4 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 30 Aug 2013 09:43:45 +0200 Subject: [PATCH 19/87] [Devel] reimplementing using visitor pattern Changing to the visitor pattern will make it easier to implement a SAX reader and writer This is a commit so that i don't loose my work. The code currently does not compile --- pom.xml | 6 +- src/main/java/ch/eitchnet/xmlpers/Main.java | 67 --- .../ch/eitchnet/xmlpers/XmlFilePersister.java | 423 ------------------ .../xmlpers/XmlPersistenceHandler.java | 116 ----- .../xmlpers/XmlPersistencePathBuilder.java | 157 ------- .../xmlpers/XmlPersistenceTransaction.java | 314 ------------- .../xmlpers/api/XmlPersistenceConstants.java | 33 ++ .../api/XmlPersistenceContextData.java | 48 ++ .../XmlPersistenceDao.java} | 60 +-- .../XmlPersistenceDaoFactory.java} | 19 +- .../api/XmlPersistenceDomContextData.java | 49 ++ .../XmlPersistenceException.java} | 8 +- .../api/XmlPersistenceFileHandler.java | 34 ++ .../xmlpers/api/XmlPersistenceHandler.java | 83 ++++ .../api/XmlPersistenceMetadataDao.java} | 35 +- .../api/XmlPersistenceSaxContextData.java | 65 +++ .../xmlpers/api/XmlPersistenceSaxHandler.java | 126 ++++++ .../xmlpers/api/XmlPersistenceSaxWriter.java | 35 ++ .../api/XmlPersistenceTransaction.java | 267 +++++++++++ .../eitchnet/xmlpers/impl/AbstractXmlDao.java | 174 +++++++ .../eitchnet/xmlpers/impl/MetadataXmlDao.java | 99 ++++ .../impl/XmlPersistenceDomHandler.java | 135 ++++++ .../xmlpers/impl/XmlPersistenceFileDao.java | 202 +++++++++ .../impl/XmlPersistencePathBuilder.java | 298 ++++++++++++ .../impl/XmlPersistenceStreamWriter.java | 94 ++++ .../java/ch/eitchnet/xmlpers/test/Main.java | 328 ++++++++++++++ .../xmlpers/test/XmlPersistenceTest.java | 142 +++--- .../ch/eitchnet/xmlpers/test/impl/Book.java | 111 +++++ .../eitchnet/xmlpers/test/impl/BookDao.java | 41 ++ .../eitchnet/xmlpers/test/impl/MyClass.java | 115 ----- .../xmlpers/test/impl/MyTypeResourceDao.java} | 11 +- .../xmlpers/test/impl/ResourceDao.java | 45 ++ .../xmlpers/test/impl/ResourceDomDao.java | 74 +++ .../{MyClassDao.java => ResourceSaxDao.java} | 68 +-- .../test/impl/TestModelDaoFactory.java | 77 ++++ .../xmlpers/test/model/Parameter.java | 126 ++++++ .../eitchnet/xmlpers/test/model/Resource.java | 129 ++++++ 37 files changed, 2818 insertions(+), 1396 deletions(-) delete mode 100644 src/main/java/ch/eitchnet/xmlpers/Main.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java rename src/main/java/ch/eitchnet/xmlpers/{XmlDao.java => api/XmlPersistenceDao.java} (51%) rename src/main/java/ch/eitchnet/xmlpers/{XmlDaoFactory.java => api/XmlPersistenceDaoFactory.java} (64%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java rename src/main/java/ch/eitchnet/xmlpers/{XmlPersistenceExecption.java => api/XmlPersistenceException.java} (82%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java => main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java} (58%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/Main.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java rename src/{main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java => test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java} (83%) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java rename src/test/java/ch/eitchnet/xmlpers/test/impl/{MyClassDao.java => ResourceSaxDao.java} (50%) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java diff --git a/pom.xml b/pom.xml index 6f22a98db..85a3a0442 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ ch.eitchnet ch.eitchnet.xmlpers jar - 0.1.0-SNAPSHOT + 0.2.0-SNAPSHOT ch.eitchnet.xmlpers https://github.com/eitch/ch.eitchnet.xmlpers @@ -124,8 +124,8 @@ maven-compiler-plugin 2.3.2 - 1.6 - 1.6 + 1.7 + 1.7 diff --git a/src/main/java/ch/eitchnet/xmlpers/Main.java b/src/main/java/ch/eitchnet/xmlpers/Main.java deleted file mode 100644 index 64ebde257..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/Main.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers; - -import java.io.File; -import java.io.FileWriter; - -import javanet.staxutils.IndentingXMLStreamWriter; - -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamWriter; - -/** - * @author Robert von Burg - * - */ -public class Main { - - public static void main(String[] args) throws Exception { - - XMLOutputFactory factory = XMLOutputFactory.newInstance(); - - File file = new File("output.xml"); - XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file)); - System.out.println("writer: " + writer.getClass().getName()); - - writer = new IndentingXMLStreamWriter(writer); - - writer.writeStartDocument(); - writer.writeStartElement("document"); - writer.writeEmptyElement("data"); - writer.writeAttribute("name", "value"); - //writer.writeEndElement(); - writer.writeEmptyElement("stuff"); - writer.writeAttribute("attr", "attrVal"); - //writer.writeEndElement(); - writer.writeEndDocument(); - - writer.flush(); - writer.close(); - System.out.println("Wrote to " + file.getAbsolutePath()); - - //Transformer transformer = TransformerFactory.newInstance().newTransformer(); - //Result outputTarget = new StaxR; - //Source xmlSource; - //transformer.transform(xmlSource, outputTarget); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java b/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java deleted file mode 100644 index b077cb1b5..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/XmlFilePersister.java +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import ch.eitchnet.utils.helper.FileHelper; -import ch.eitchnet.utils.helper.XmlHelper; - -/** - * @author Robert von Burg - * - */ -public class XmlFilePersister { - - private static final Logger logger = LoggerFactory.getLogger(XmlFilePersister.class); - - private boolean verbose; - private XmlPersistencePathBuilder xmlPathHelper; - - /** - * @param xmlPathHelper - * @param verbose - */ - public XmlFilePersister(XmlPersistencePathBuilder xmlPathHelper, boolean verbose) { - this.xmlPathHelper = xmlPathHelper; - this.verbose = verbose; - } - - /** - * @param type - * @param subType - * @param id - * @param document - */ - public void saveOrUpdate(String type, String subType, String id, Document document) { - - File pathF; - if (subType != null) - pathF = this.xmlPathHelper.getPathF(type, subType, id); - else - pathF = this.xmlPathHelper.getPathF(type, id); - - // if this is a new file, then check create parents, if the don't exist - if (!pathF.exists()) { - File parentFile = pathF.getParentFile(); - if (!parentFile.exists() && !parentFile.mkdirs()) { - throw new XmlPersistenceExecption("Could not create path for " + type + " / " + subType + " / " + id - + " at " + pathF.getAbsolutePath()); - } - } - - if (this.verbose) - XmlFilePersister.logger.info("Persisting " + type + " / " + subType + " / " + id + " to " - + pathF.getAbsolutePath() + "..."); - - try { - - XmlHelper.writeDocument(document, pathF); - - } catch (Exception e) { - throw new XmlPersistenceExecption("Could not persist object " + type + " / " + subType + " / " + id - + " to " + pathF.getAbsolutePath(), e); - } - - if (this.verbose) - XmlFilePersister.logger.info("Done."); - } - - /** - * @param type - * @param subType - * @param id - */ - public void remove(String type, String subType, String id) { - - File pathF; - if (subType != null) - pathF = this.xmlPathHelper.getPathF(type, subType, id); - else - pathF = this.xmlPathHelper.getPathF(type, id); - - if (this.verbose) - XmlFilePersister.logger.info("Remove persistence file for " + type + " / " + subType + " / " + id - + " from " + pathF.getAbsolutePath() + "..."); - - if (!pathF.exists()) { - XmlFilePersister.logger.error("Persistence file for " + type + " / " + subType + " / " + id - + " does not exist at " + pathF.getAbsolutePath()); - } else if (!pathF.delete()) { - throw new XmlPersistenceExecption("Could not delete persistence file for " + type + " / " + subType + " / " - + id + " at " + pathF.getAbsolutePath()); - } - - if (this.verbose) - XmlFilePersister.logger.info("Done."); - } - - /** - * @param type - * @param subType - */ - public void removeAll(String type, String subType) { - - File pathF; - if (subType == null) - pathF = this.xmlPathHelper.getPathF(type); - else - pathF = this.xmlPathHelper.getPathF(type, subType); - - if (!pathF.exists()) { - if (subType == null) - XmlFilePersister.logger.error("Path for " + type + " at " + pathF.getAbsolutePath() - + " does not exist, so removing not possible!"); - else - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so removing not possible!"); - - } else { - - File[] filesToRemove = pathF.listFiles(); - boolean removed = FileHelper.deleteFiles(filesToRemove, this.verbose); - - if (!removed) { - if (subType == null) - throw new XmlPersistenceExecption("Could not delete persistence files for " + type + " at " - + pathF.getAbsolutePath()); - - throw new XmlPersistenceExecption("Could not delete persistence files for " + type + " / " + subType - + " at " + pathF.getAbsolutePath()); - } - } - } - - /** - * - * @param type - * @param subType - * - * @return - */ - public Set queryKeySet(String type, String subType) { - - // if a sub type is required, then it's simple: - if (subType != null) { - - File pathF = this.xmlPathHelper.getPathF(type, subType); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so no objects exist!"); - return Collections.emptySet(); - } - - Set keySet = new HashSet(); - for (File f : pathF.listFiles()) { - String name = f.getName(); - keySet.add(name.substring(0, name.length() - XmlPersistencePathBuilder.FILE_EXT.length())); - } - - if (this.verbose) - XmlFilePersister.logger.info("Found " + keySet.size() + " elements for " + type + " / " + subType); - - return keySet; - } - - // otherwise we need to iterate any existing subTypes and create a combined key set - File pathF = this.xmlPathHelper.getPathF(type); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so no objects exist!"); - return Collections.emptySet(); - } - - Set keySet = new HashSet(); - - File[] subTypeFiles = pathF.listFiles(); - for (File subTypeFile : subTypeFiles) { - - if (subTypeFile.isFile()) { - keySet.add(this.xmlPathHelper.getId(subTypeFile.getName())); - } else { - - for (File f : subTypeFile.listFiles()) { - keySet.add(this.xmlPathHelper.getId(f.getName())); - } - } - } - - if (this.verbose) - XmlFilePersister.logger.info("Found " + keySet.size() + " elements for " + type); - - return keySet; - } - - /** - * - * @param type - * @param subType - * - * @return - */ - public long querySize(String type, String subType) { - - // if a sub type is required, then it's simple: - if (subType != null) { - - File pathF = this.xmlPathHelper.getPathF(type, subType); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so no objects exist!"); - return 0l; - } - - int length = pathF.listFiles().length; - - if (this.verbose) - XmlFilePersister.logger.info("Found " + length + " elements for " + type + " / " + subType); - - return length; - } - - // otherwise we need to iterate any existing sub types and - // return the size of the combined collection - - File pathF = this.xmlPathHelper.getPathF(type); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so no objects exist!"); - return 0l; - } - - long numberOfFiles = 0l; - - File[] subTypeFiles = pathF.listFiles(); - for (File subTypeFile : subTypeFiles) { - - if (subTypeFile.isFile()) { - numberOfFiles++; - } else { - numberOfFiles += subTypeFile.listFiles().length; - } - } - - if (this.verbose) - XmlFilePersister.logger.info("Found " + numberOfFiles + " elements for " + type); - - return numberOfFiles; - } - -// XXX think about allowing paged loading... -// /** -// * @param type -// * @param subType -// * @param firstResult -// * @param maxResults -// * -// * @return -// */ -// public List queryFrom(String type, String subType, int firstResult, int maxResults) { -// -// File pathF = this.xmlPathHelper.getPathF(type, subType); -// if (!pathF.exists()) { -// logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() -// + " does not exist, so no objects exist!"); -// return Collections.emptyList(); -// } -// -// File[] listFiles = pathF.listFiles(); -// Arrays.sort(listFiles, new Comparator() { -// -// @Override -// public int compare(File file1, File file2) { -// return file1.getName().compareTo(file2.getName()); -// } -// }); -// -// // make sure positions are not illegal -// int size = listFiles.length; -// if (firstResult >= size) -// return Collections.emptyList(); -// -// if ((firstResult + maxResults) > size) -// maxResults = size - firstResult; -// -// File[] result = Arrays.copyOfRange(listFiles, firstResult, firstResult + maxResults); -// -// List list = new ArrayList(); -// for (File f : result) { -// list.add(loadObject(clazz, f)); -// } -// -// return list; -// } - - /** - * - * @param type - * @param subType - * - * @return - */ - public List queryAll(String type, String subType, DocumentBuilder docBuilder) { - - // if a sub type is required, then it's simple: - if (subType != null) { - - File pathF = this.xmlPathHelper.getPathF(type, subType); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so no objects exist!"); - return Collections.emptyList(); - } - - List list = new ArrayList(); - for (File subTypeF : pathF.listFiles()) { - list.add(parseFile(subTypeF, docBuilder)); - } - - if (this.verbose) - XmlFilePersister.logger.info("Loaded " + list.size() + " elements for " + type + " / " + subType); - - return list; - } - - // otherwise we need to iterate any existing sub types and - // return those elements as well - - File pathF = this.xmlPathHelper.getPathF(type); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " at " + pathF.getAbsolutePath() - + " does not exist, so no objects exist!"); - return Collections.emptyList(); - } - - List list = new ArrayList(); - - File[] subTypeFiles = pathF.listFiles(); - for (File subTypeFile : subTypeFiles) { - - if (subTypeFile.isFile()) { - list.add(parseFile(subTypeFile, docBuilder)); - - } else { - for (File subTypeF : subTypeFile.listFiles()) { - list.add(parseFile(subTypeF, docBuilder)); - } - } - } - - if (this.verbose) - XmlFilePersister.logger.info("Loaded " + list.size() + " elements for " + type); - - return list; - } - - /** - * - * @param type - * @param subType - * @param id - * - * @return - */ - public Element queryById(String type, String subType, String id, DocumentBuilder docBuilder) { - - File pathF = this.xmlPathHelper.getPathF(type, subType, id); - if (!pathF.exists()) { - XmlFilePersister.logger.error("Path for " + type + " / " + subType + " / " + id + " at " - + pathF.getAbsolutePath() + " does not exist, so object does not exist!"); - return null; - } - - return parseFile(pathF, docBuilder); - } - - /** - * @param subTypeF - * @return - */ - private Element parseFile(File subTypeF, DocumentBuilder docBuilder) { - try { - - Document document = docBuilder.parse(subTypeF); - return document.getDocumentElement(); - - } catch (SAXException e) { - throw new XmlPersistenceExecption("Failed to parse file " + subTypeF.getAbsolutePath(), e); - } catch (IOException e) { - throw new XmlPersistenceExecption("Failed to read file " + subTypeF.getAbsolutePath(), e); - } - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java deleted file mode 100644 index a393e72b9..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceHandler.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.SystemHelper; -import ch.eitchnet.utils.objectfilter.ObjectFilter; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceHandler { - - public static final String CONFIG_VERBOSE = "ch.eitchnet.xmlpers.config.verbose"; - public static final String CONFIG_BASEPATH = "ch.eitchnet.xmlpers.config.basepath"; - public static final String CONFIG_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers.config.daoFactoryClass"; - - protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandler.class); - - protected boolean verbose; - protected ThreadLocal xmlPersistenceTxThreadLocal; - protected XmlFilePersister persister; - protected XmlDaoFactory xmlDaoFactory; - - public void initialize() { - - String basePath = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), XmlPersistenceHandler.CONFIG_BASEPATH, null); - this.verbose = SystemHelper.getPropertyBool(XmlPersistenceHandler.class.getSimpleName(), XmlPersistenceHandler.CONFIG_VERBOSE, - Boolean.FALSE).booleanValue(); - - // get class to use as transaction - String daoFactoryClassName = SystemHelper.getProperty(XmlPersistenceHandler.class.getSimpleName(), - XmlPersistenceHandler.CONFIG_DAO_FACTORY_CLASS, null); - try { - @SuppressWarnings("unchecked") - Class xmlDaoFactoryClass = (Class) Class.forName(daoFactoryClassName); - - this.xmlDaoFactory = xmlDaoFactoryClass.newInstance(); - - } catch (ClassNotFoundException e) { - throw new XmlPersistenceExecption("XmlDaoFactory class does not exist " + daoFactoryClassName, e); - } catch (Exception e) { - throw new XmlPersistenceExecption("Failed to load class " + daoFactoryClassName, e); - } - - XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(basePath); - this.persister = new XmlFilePersister(pathBuilder, this.verbose); - - // initialize the Thread local object which is used per transaction - this.xmlPersistenceTxThreadLocal = new ThreadLocal(); - } - - public XmlPersistenceTransaction openTx() { - - if (this.verbose) - XmlPersistenceHandler.logger.info("Opening new transaction..."); - - // make sure no previous filter exists - XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); - if (xmlPersistenceTx != null) - throw new XmlPersistenceExecption("Previous transaction not properly closed"); - - // set a new persistence transaction object - ObjectFilter objectFilter = new ObjectFilter(); - xmlPersistenceTx = new XmlPersistenceTransaction(); - xmlPersistenceTx.initialize(this.persister, this.xmlDaoFactory, objectFilter, this.verbose); - - this.xmlPersistenceTxThreadLocal.set(xmlPersistenceTx); - - return xmlPersistenceTx; - } - - public XmlPersistenceTransaction getTx() { - XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); - if (xmlPersistenceTx == null) - throw new XmlPersistenceExecption("No transaction currently open!"); - - return xmlPersistenceTx; - } - - public void commitTx() { - - if (this.verbose) - XmlPersistenceHandler.logger.info("Committing transaction..."); - - try { - XmlPersistenceTransaction xmlPersistenceTx = this.xmlPersistenceTxThreadLocal.get(); - if (xmlPersistenceTx == null) - throw new XmlPersistenceExecption("No transaction currently open!"); - - xmlPersistenceTx.commitTx(); - } finally { - this.xmlPersistenceTxThreadLocal.set(null); - } - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java deleted file mode 100644 index baa894740..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistencePathBuilder.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers; - -import java.io.File; -import java.io.IOException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistencePathBuilder { - private static final Logger logger = LoggerFactory.getLogger(XmlPersistencePathBuilder.class); - - public static final String FILE_EXT = ".xml"; - public static final int EXT_LENGTH = XmlPersistencePathBuilder.FILE_EXT.length(); - - private String basePath; - - /** - * @param basePath - */ - public XmlPersistencePathBuilder(String basePath) { - File basePathF = new File(basePath); - if (!basePathF.exists()) - throw new XmlPersistenceExecption("The database store path does not exist at " - + basePathF.getAbsolutePath()); - if (!basePathF.canWrite()) - throw new XmlPersistenceExecption("The database store path is not writeable at " - + basePathF.getAbsolutePath()); - - try { - this.basePath = basePathF.getCanonicalPath(); - } catch (IOException e) { - throw new XmlPersistenceExecption("Failed to build canonical path from " + basePath, e); - } - - XmlPersistencePathBuilder.logger.info("Using base path " + basePath); - } - - /** - * @param id - * @return - */ - public String getFilename(String id) { - return id.concat(XmlPersistencePathBuilder.FILE_EXT); - } - - /** - * @param filename - * @return - */ - public String getId(String filename) { - if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') - throw new XmlPersistenceExecption("The filename does not have a . at index " - + (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); - - return filename.substring(0, filename.length() - XmlPersistencePathBuilder.EXT_LENGTH); - } - - /** - * @param type - * - * @return - */ - public String getPath(String type) { - - StringBuilder sb = new StringBuilder(this.basePath); - sb.append("/"); - sb.append(type); - - return sb.toString(); - } - - /** - * @param type - * - * @return - */ - public File getPathF(String type) { - return new File(getPath(type)); - } - - /** - * @param type - * @param subType - * @return - */ - public String getPath(String type, String subType) { - - StringBuilder sb = new StringBuilder(this.basePath); - sb.append("/"); - sb.append(type); - sb.append("/"); - sb.append(subType); - - return sb.toString(); - } - - /** - * @param type - * @param subType - * @return - */ - public File getPathF(String type, String subType) { - return new File(getPath(type, subType)); - } - - /** - * @param type - * @param subType - * @param id - * @return - */ - public String getPath(String type, String subType, String id) { - - StringBuilder sb = new StringBuilder(this.basePath); - sb.append("/"); - sb.append(type); - sb.append("/"); - sb.append(subType); - sb.append("/"); - sb.append(getFilename(id)); - - return sb.toString(); - } - - /** - * @param type - * @param subType - * @param id - * @return - */ - public File getPathF(String type, String subType, String id) { - return new File(getPath(type, subType, id)); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java deleted file mode 100644 index 9d2f3f2b0..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceTransaction.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import ch.eitchnet.utils.helper.XmlHelper; -import ch.eitchnet.utils.objectfilter.ITransactionObject; -import ch.eitchnet.utils.objectfilter.ObjectFilter; - -/** - * @author Robert von Burg - */ -public class XmlPersistenceTransaction { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTransaction.class); - - private boolean verbose; - private XmlFilePersister persister; - private XmlDaoFactory xmlDaoFactory; - private ObjectFilter objectFilter; - private DocumentBuilder docBuilder; - private DOMImplementation domImplementation; - - /** - * @param persister - * @param xmlDaoFactory - * @param objectFilter - */ - public void initialize(XmlFilePersister persister, XmlDaoFactory xmlDaoFactory, - ObjectFilter objectFilter, boolean verbose) { - this.persister = persister; - this.xmlDaoFactory = xmlDaoFactory; - this.objectFilter = objectFilter; - this.verbose = verbose; - } - - private DocumentBuilder getDocBuilder() { - if (this.docBuilder == null) { - try { - this.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new XmlPersistenceExecption("Failed to load document builder: " + e.getLocalizedMessage(), e); - } - } - return this.docBuilder; - } - - /** - * @return - */ - protected DOMImplementation getDomImpl() { - if (this.domImplementation == null) - this.domImplementation = getDocBuilder().getDOMImplementation(); - return this.domImplementation; - } - - /* - * modifying methods - */ - - /** - * @param object - */ - public void add(ITransactionObject object) { - this.objectFilter.add(object); - } - - /** - * @param objects - */ - public void addAll(List objects) { - this.objectFilter.addAll(objects); - } - - /** - * @param object - */ - public void update(ITransactionObject object) { - this.objectFilter.update(object); - } - - /** - * @param objects - */ - public void updateAll(List objects) { - this.objectFilter.updateAll(objects); - } - - /** - * @param object - */ - public void remove(ITransactionObject object) { - this.objectFilter.remove(object); - } - - /** - * @param objects - */ - public void removeAll(List objects) { - this.objectFilter.removeAll(objects); - } - - /* - * querying methods - */ - - /** - * @param type - * @return - */ - public Set queryKeySet(String type) { - return queryKeySet(type, null); - } - - /** - * @param type - * @param subType - * @return - */ - public Set queryKeySet(String type, String subType) { - return this.persister.queryKeySet(type, subType); - } - - /** - * @param type - * @return - */ - public long querySize(String type) { - return querySize(type, null); - } - - /** - * @param type - * @param subType - * @return - */ - public long querySize(String type, String subType) { - return this.persister.querySize(type, subType); - } - - /** - * @param type - * @return - */ - public List queryAll(String type) { - return queryAll(type, null); - } - - /** - * @param type - * @param subType - * @return - */ - public List queryAll(String type, String subType) { - - // XXX ok, this is very ugly, but for starters it will have to do - XmlDao dao = this.xmlDaoFactory.getDao(type); - - List elements = this.persister.queryAll(type, subType, getDocBuilder()); - List objects = new ArrayList(elements.size()); - - for (Element element : elements) { - @SuppressWarnings("unchecked") - T object = (T) dao.parseFromDom(element); - objects.add(object); - } - - return objects; - } - - /** - * @param type - * @param id - * @return - */ - public T queryById(String type, String id) { - return queryById(type, null, id); - } - - /** - * @param type - * @param subType - * @param id - * @return - */ - public T queryById(String type, String subType, String id) { - - XmlDao dao = this.xmlDaoFactory.getDao(type); - - Element element = this.persister.queryById(type, subType, id, getDocBuilder()); - if (element == null) - throw new XmlPersistenceExecption("No object exists for " + type + " / " + subType + " / " + id); - - @SuppressWarnings("unchecked") - T object = (T) dao.parseFromDom(element); - - return object; - } - - /* - * committing - */ - - /** - * - */ - void commitTx() { - - if (this.verbose) - XmlPersistenceTransaction.logger.info("Committing..."); - - Set keySet = this.objectFilter.keySet(); - if (keySet.isEmpty()) - return; - - for (String key : keySet) { - - XmlDao dao = this.xmlDaoFactory.getDao(key); - - List removed = this.objectFilter.getRemoved(key); - if (removed.isEmpty()) { - if (this.verbose) - XmlPersistenceTransaction.logger.info("No objects removed in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransaction.logger.info(removed.size() + " objects removed in this tx."); - - for (ITransactionObject object : removed) { - - String type = dao.getType(object); - String subType = dao.getSubType(object); - String id = dao.getId(object); - - this.persister.remove(type, subType, id); - } - } - - List updated = this.objectFilter.getUpdated(key); - if (updated.isEmpty()) { - if (this.verbose) - XmlPersistenceTransaction.logger.info("No objects updated in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransaction.logger.info(updated.size() + " objects updated in this tx."); - - for (ITransactionObject object : updated) { - - String type = dao.getType(object); - String subType = dao.getSubType(object); - String id = dao.getId(object); - - Document doc = XmlHelper.createDocument(); - Element asDom = dao.serializeToDom(object, doc); - doc.appendChild(asDom); - this.persister.saveOrUpdate(type, subType, id, doc); - } - } - - List added = this.objectFilter.getAdded(key); - if (added.isEmpty()) { - if (this.verbose) - XmlPersistenceTransaction.logger.info("No objects added in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransaction.logger.info(added.size() + " objects added in this tx."); - - for (ITransactionObject object : added) { - - String type = dao.getType(object); - String subType = dao.getSubType(object); - String id = dao.getId(object); - - Document doc = XmlHelper.createDocument(); - Element asDom = dao.serializeToDom(object, doc); - doc.appendChild(asDom); - this.persister.saveOrUpdate(type, subType, id, doc); - } - } - } - - this.objectFilter.clearCache(); - XmlPersistenceTransaction.logger.info("Completed TX"); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java new file mode 100644 index 000000000..050c9789a --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceConstants { + + public static final String PROP_VERBOSE = "ch.eitchnet.xmlpers.verbose"; + public static final String PROP_BASEPATH = "ch.eitchnet.xmlpers.basepath"; + public static final String PROP_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers.daoFactoryClass"; +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java new file mode 100644 index 000000000..821f26ea9 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import java.io.File; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceContextData { + + private File file; + + /** + * @return the file + */ + public File getFile() { + return this.file; + } + + /** + * @param file + * the file to set + */ + public void setFile(File file) { + this.file = file; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlDao.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java similarity index 51% rename from src/main/java/ch/eitchnet/xmlpers/XmlDao.java rename to src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java index 134f290b1..e034d9c76 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java @@ -17,57 +17,37 @@ * along with ch.eitchnet.java.xmlpers. If not, see . * */ -package ch.eitchnet.xmlpers; +package ch.eitchnet.xmlpers.api; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.ContentHandler; +import java.util.List; +import java.util.Set; + +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; /** * @author Robert von Burg - * */ -public interface XmlDao { +public interface XmlPersistenceDao { - /** - * @param object - * @return - */ - public String getType(T object); + public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao); - /** - * @param object - * @return - */ - public String getSubType(T object); + public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler); - /** - * @param object - * @return - */ - public String getId(T object); + public void add(T object); - /** - * - * @param object - * @param document - * @return - */ - public Element serializeToDom(T object, Document document); + public void update(T object); - /** - * @param element - * @return - */ - public T parseFromDom(Element element); + public void remove(T object); - /** - * @param object - * @param contentHandler - */ - // XXX Use the XMLSerializer object for serializing to SAX... - public void serializeToSax(T object, ContentHandler contentHandler); + public void removeById(String id); - // XXX parse from SAX is missing... + public void removeAll(); + public T queryById(String id); + + public List queryAll(); + + public Set queryKeySet(); + + public long querySize(); } diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java similarity index 64% rename from src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java rename to src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java index 90b469703..76ac22cad 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlDaoFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java @@ -17,13 +17,24 @@ * along with ch.eitchnet.java.xmlpers. If not, see . * */ -package ch.eitchnet.xmlpers; +package ch.eitchnet.xmlpers.api; + +import java.util.Properties; + +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; /** * @author Robert von Burg - * */ -public interface XmlDaoFactory { +public interface XmlPersistenceDaoFactory { - public XmlDao getDao(String type); + public void initialize(XmlPersistenceFileDao fileDao, Properties properties); + + public XmlPersistenceMetadataDao getMetadataDao(); + + public XmlPersistenceDao getDao(T object); + + public XmlPersistenceDao getDao(String type); + + public XmlPersistenceDao getDao(String type, String subType); } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java new file mode 100644 index 000000000..081660b04 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import org.w3c.dom.Document; + + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceDomContextData extends XmlPersistenceContextData { + + private Document document; + + /** + * @return the document + */ + public Document getDocument() { + return this.document; + } + + /** + * @param document + * the document to set + */ + public void setDocument(Document document) { + this.document = document; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java similarity index 82% rename from src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java rename to src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java index ff01fca32..d56835be8 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlPersistenceExecption.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java @@ -17,26 +17,26 @@ * along with ch.eitchnet.java.xmlpers. If not, see . * */ -package ch.eitchnet.xmlpers; +package ch.eitchnet.xmlpers.api; /** * @author Robert von Burg */ -public class XmlPersistenceExecption extends RuntimeException { +public class XmlPersistenceException extends RuntimeException { private static final long serialVersionUID = 1L; /** * @param message * @param cause */ - public XmlPersistenceExecption(String message, Throwable cause) { + public XmlPersistenceException(String message, Throwable cause) { super(message, cause); } /** * @param message */ - public XmlPersistenceExecption(String message) { + public XmlPersistenceException(String message) { super(message); } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java new file mode 100644 index 000000000..a3d71c00b --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + + +/** + * @author Robert von Burg + * + */ +public interface XmlPersistenceFileHandler { + + public void read(XmlPersistenceContextData contextData); + + public void write(XmlPersistenceContextData contextData); +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java new file mode 100644 index 000000000..8a1106aa5 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.api; + +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; +import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceHandler { + + protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandler.class); + + protected boolean initialized; + protected boolean verbose; + protected XmlPersistenceDaoFactory daoFactory; + + public void initialize(Properties properties) { + if (this.initialized) + throw new IllegalStateException("Already initialized!"); + + // get properties + String context = XmlPersistenceHandler.class.getSimpleName(); + boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, + Boolean.FALSE).booleanValue(); + String daoFactoryClassName = PropertiesHelper.getProperty(properties, context, + XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, null); + + // load dao factory + XmlPersistenceDaoFactory daoFactory; + try { + @SuppressWarnings("unchecked") + Class xmlDaoFactoryClass = (Class) Class.forName(daoFactoryClassName); + + daoFactory = xmlDaoFactoryClass.newInstance(); + + } catch (ClassNotFoundException e) { + throw new XmlPersistenceException("XmlDaoFactory class does not exist " + daoFactoryClassName, e); + } catch (Exception e) { + throw new XmlPersistenceException("Failed to load class " + daoFactoryClassName, e); + } + + // initialize the dao factory + XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(properties); + XmlPersistenceFileDao fileDao = new XmlPersistenceFileDao(pathBuilder, properties); + daoFactory.initialize(fileDao, properties); + + this.daoFactory = daoFactory; + this.verbose = verbose; + } + + public XmlPersistenceTransaction openTx() { + + XmlPersistenceTransaction tx = new XmlPersistenceTransaction(this.daoFactory, this.verbose); + XmlPersistenceTransaction.setTx(tx); + return tx; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java similarity index 58% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java rename to src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java index efa26d450..36039f7dd 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyDaoFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java @@ -17,27 +17,32 @@ * along with ch.eitchnet.java.xmlpers. If not, see . * */ -package ch.eitchnet.xmlpers.test.impl; +package ch.eitchnet.xmlpers.api; -import ch.eitchnet.xmlpers.XmlDao; -import ch.eitchnet.xmlpers.XmlDaoFactory; +import java.util.Set; + +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; /** * @author Robert von Burg - * */ -public class MyDaoFactory implements XmlDaoFactory { +public interface XmlPersistenceMetadataDao { - /** - * @see ch.eitchnet.xmlpers.XmlDaoFactory#getDao(java.lang.String) - */ - @SuppressWarnings("unchecked") - @Override - public XmlDao getDao(String type) { - if (type.equals(MyClass.class.getName())) - return (XmlDao) new MyClassDao(); + public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao); - throw new RuntimeException("Class with type " + type + " is unknown!"); - } + public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler); + public void removeAll(); + + public Set queryKeySet(); + + public Set queryKeySet(String type); + + public Set queryKeySet(String type, String subType); + + public long querySize(); + + public long querySize(String type); + + public long querySize(String type, String subType); } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java new file mode 100644 index 000000000..8ab786c9a --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import org.xml.sax.helpers.DefaultHandler; + + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceSaxContextData extends XmlPersistenceContextData { + + private DefaultHandler defaultHandler; + private XmlPersistenceSaxWriter xmlWriter; + + /** + * @return the defaultHandler + */ + public DefaultHandler getDefaultHandler() { + return this.defaultHandler; + } + + /** + * @param defaultHandler + * the defaultHandler to set + */ + public void setDefaultHandler(DefaultHandler defaultHandler) { + this.defaultHandler = defaultHandler; + } + + /** + * @return the xmlWriter + */ + public XmlPersistenceSaxWriter getXmlWriter() { + return this.xmlWriter; + } + + /** + * @param xmlWriter + * the xmlWriter to set + */ + public void setXmlWriter(XmlPersistenceSaxWriter xmlWriter) { + this.xmlWriter = xmlWriter; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java new file mode 100644 index 000000000..f9029ac60 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import javanet.staxutils.IndentingXMLStreamWriter; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.utils.exceptions.XmlException; +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceSaxHandler implements XmlPersistenceFileHandler { + + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceSaxHandler.class); + + @Override + public void read(XmlPersistenceContextData contextData) { + + XmlPersistenceSaxContextData cd = (XmlPersistenceSaxContextData) contextData; + + // check assertions + if (cd.getFile() == null) + throw new IllegalStateException("No file has been set on the context data!"); + if (cd.getDefaultHandler() == null) + throw new IllegalStateException("No DefaultHandler has been set on the context data!"); + + File file; + try { + + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser sp = spf.newSAXParser(); + + file = cd.getFile(); + DefaultHandler defaultHandler = cd.getDefaultHandler(); + sp.parse(file, defaultHandler); + + } catch (ParserConfigurationException | SAXException | IOException e) { + + throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); + } + + logger.info("SAX parsed file " + file.getAbsolutePath()); + } + + @Override + public void write(XmlPersistenceContextData contextData) { + + XmlPersistenceSaxContextData cd = (XmlPersistenceSaxContextData) contextData; + + // check assertions + if (cd.getFile() == null) + throw new IllegalStateException("No file has been set on the context data!"); + if (cd.getXmlWriter() == null) + throw new IllegalStateException("No Xml writer has been set on the context data!"); + + XMLStreamWriter writer = null; + try { + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + File file = cd.getFile(); + writer = factory.createXMLStreamWriter(new FileWriter(file)); + writer = new IndentingXMLStreamWriter(writer); + + // start document + writer.writeStartDocument("utf-8", "1.0"); + + // then delegate object writing to caller + XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); + cd.getXmlWriter().write(xmlWriter); + + // and now end + writer.writeEndDocument(); + writer.flush(); + + } catch (FactoryConfigurationError | XMLStreamException | IOException e) { + throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (Exception e) { + logger.error("Failed to close stream: " + e.getMessage()); + } + } + } + + logger.info("Wrote SAX to " + cd.getFile().getAbsolutePath()); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java new file mode 100644 index 000000000..df950f904 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import javax.xml.stream.XMLStreamException; + +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; + +/** + * @author Robert von Burg + * + */ +public interface XmlPersistenceSaxWriter { + + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException; +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java new file mode 100644 index 000000000..1e5e9151f --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.api; + +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.objectfilter.ObjectFilter; + +/** + * @author Robert von Burg + */ +public class XmlPersistenceTransaction { + + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTransaction.class); + + private static final ThreadLocal TX_THREADLOCAL_THREAD_LOCAL; + static { + TX_THREADLOCAL_THREAD_LOCAL = new ThreadLocal<>(); + } + + private final XmlPersistenceDaoFactory daoFactory; + private final boolean verbose; + private final ObjectFilter objectFilter; + + /** + * @param verbose + */ + public XmlPersistenceTransaction(XmlPersistenceDaoFactory daoFactory, boolean verbose) { + this.daoFactory = daoFactory; + this.verbose = verbose; + this.objectFilter = new ObjectFilter(); + } + + /* + * modifying methods + */ + + /** + * @param object + */ + public void add(T object) { + this.objectFilter.add(object); + } + + /** + * @param objects + */ + @SuppressWarnings("unchecked") + public void addAll(List objects) { + this.objectFilter.addAll((List) objects); + } + + /** + * @param object + */ + public void update(T object) { + this.objectFilter.update(object); + } + + /** + * @param objects + */ + @SuppressWarnings("unchecked") + public void updateAll(List objects) { + this.objectFilter.updateAll((List) objects); + } + + /** + * @param object + */ + public void remove(T object) { + this.objectFilter.remove(object); + } + + /** + * @param objects + */ + @SuppressWarnings("unchecked") + public void removeAll(List objects) { + this.objectFilter.removeAll((List) objects); + } + + /* + * querying methods + */ + + /** + * @param type + * @return + */ + public Set queryKeySet() { + return this.daoFactory.getMetadataDao().queryKeySet(); + } + + /** + * @param type + * @return + */ + public Set queryKeySet(String type) { + return this.daoFactory.getMetadataDao().queryKeySet(type); + } + + /** + * @param type + * @param subType + * @return + */ + public Set queryKeySet(String type, String subType) { + return this.daoFactory.getMetadataDao().queryKeySet(type, subType); + } + + /** + * @param type + * @return + */ + public long querySize(String type) { + return querySize(type, null); + } + + /** + * @param type + * @param subType + * @return + */ + public long querySize(String type, String subType) { + return this.daoFactory.getDao(type, subType).querySize(); + } + + /** + * @param type + * @return + */ + public List queryAll(String type) { + XmlPersistenceDao dao = this.daoFactory.getDao(type); + List objects = dao.queryAll(type); + return objects; + } + + /** + * @param type + * @param subType + * @return + */ + public List queryAll(String type, String subType) { + XmlPersistenceDao dao = this.daoFactory.getDao(type, subType); + List objects = dao.queryAll(type, subType); + return objects; + } + + /** + * @param type + * @param id + * @return + */ + public T queryById(String type, String id) { + return queryById(type, id); + } + + /** + * @param type + * @param subType + * @param id + * @return + */ + public T queryById(String type, String subType, String id) { + XmlPersistenceDao dao = this.daoFactory.getDao(type, subType); + T object = dao.queryById(id); + return object; + } + + /** + * + */ + public void commit() { + + if (this.verbose) + XmlPersistenceTransaction.logger.info("Committing TX..."); + + Set keySet = this.objectFilter.keySet(); + if (keySet.isEmpty()) + return; + + for (String key : keySet) { + + List removed = this.objectFilter.getRemoved(key); + if (removed.isEmpty()) { + if (this.verbose) + XmlPersistenceTransaction.logger.info("No objects removed in this tx."); + } else { + if (this.verbose) + XmlPersistenceTransaction.logger.info(removed.size() + " objects removed in this tx."); + + for (Object object : removed) { + XmlPersistenceDao dao = this.daoFactory.getDao(object); + dao.remove(object); + } + } + + List updated = this.objectFilter.getUpdated(key); + if (updated.isEmpty()) { + if (this.verbose) + XmlPersistenceTransaction.logger.info("No objects updated in this tx."); + } else { + if (this.verbose) + XmlPersistenceTransaction.logger.info(updated.size() + " objects updated in this tx."); + + for (Object object : updated) { + + XmlPersistenceDao dao = this.daoFactory.getDao(object); + dao.update(object); + } + } + + List added = this.objectFilter.getAdded(key); + if (added.isEmpty()) { + if (this.verbose) + XmlPersistenceTransaction.logger.info("No objects added in this tx."); + } else { + if (this.verbose) + XmlPersistenceTransaction.logger.info(added.size() + " objects added in this tx."); + + for (Object object : added) { + + XmlPersistenceDao dao = this.daoFactory.getDao(object); + dao.add(object); + } + } + } + + this.objectFilter.clearCache(); + XmlPersistenceTransaction.logger.info("Completed TX"); + } + + public static XmlPersistenceTransaction getTx() { + XmlPersistenceTransaction tx = TX_THREADLOCAL_THREAD_LOCAL.get(); + if (tx == null) + throw new IllegalStateException("No transaction is currently open!"); + return tx; + } + + public static void setTx(XmlPersistenceTransaction tx) { + if (TX_THREADLOCAL_THREAD_LOCAL.get() != null) + throw new IllegalStateException("A transaction is already open!"); + TX_THREADLOCAL_THREAD_LOCAL.set(tx); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java new file mode 100644 index 000000000..7d4491855 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import ch.eitchnet.utils.exceptions.XmlException; +import ch.eitchnet.xmlpers.api.XmlPersistenceDao; +import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; + +/** + * @author Robert von Burg + * + */ +public abstract class AbstractXmlDao implements XmlPersistenceDao { + + private XmlPersistenceFileDao fileDao; + private XmlPersistenceFileHandler fileHandler; + + // TODO think about setting some methods to final + // TODO maybe decouple the write and load method into their own class + // TODO if no sub type is given, then don't search recursively - it means subType does not exist + + @Override + public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao) { + this.fileDao = fileDao; + } + + @Override + public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler) { + this.fileHandler = fileHandler; + } + + /** + * @return the fileHandler + */ + protected XmlPersistenceFileHandler getFileHandler() { + return this.fileHandler; + } + + /** + * @return the fileDao + */ + protected XmlPersistenceFileDao getFileDao() { + return this.fileDao; + } + + @Override + public void remove(T object) { + this.fileDao.remove(getType(), getSubType(), getId(object)); + } + + @Override + public void removeById(String id) { + this.fileDao.remove(getType(), getSubType(), id); + } + + @Override + public void removeAll() { + this.fileDao.removeAll(getType(), getSubType()); + } + + @Override + public Set queryKeySet() { + return this.fileDao.queryKeySet(getType(), getSubType()); + } + + @Override + public long querySize() { + return this.fileDao.querySize(getType(), getSubType()); + } + + @Override + public List queryAll() { + File queryPath = this.fileDao.getPathBuilder().getPath(getType(), getSubType()); + String msg = "Can not read persistence unit for {0} / {1} at {2}"; + return queryAll(queryPath, msg, getType(), getSubType(), queryPath); + } + + private List queryAll(File queryPath, String errorMsg, Object... msgArgs) { + File[] persistenceUnits = queryPath.listFiles(); + List result = new ArrayList<>(); + for (File persistenceUnit : persistenceUnits) { + if (!persistenceUnit.isFile()) + continue; + + assertReadable(persistenceUnit, errorMsg, msgArgs); + T object = read(persistenceUnit); + result.add(object); + } + + return result; + } + + private void assertReadable(File persistenceUnit, String errorMsg, Object... msgArgs) { + if (!persistenceUnit.canRead()) { + String msg = String.format(errorMsg, msgArgs); + throw new XmlException(msg); + } + } + + @Override + public T queryById(String id) { + File persistenceUnit = this.fileDao.getPathBuilder().getPath(getType(), getSubType(), id); + String msg = "Can not read persistence unit for {0} / {1} / {2} at {3}"; + return queryById(persistenceUnit, msg, getType(), getSubType(), id, persistenceUnit); + } + + private T queryById(File persistenceUnit, String msg, Object... msgArgs) { + assertReadable(persistenceUnit, msg, msgArgs); + T object = read(persistenceUnit); + return object; + } + + @Override + public void add(T object) { + XmlPersistencePathBuilder pathBuilder = this.fileDao.getPathBuilder(); + File addPath = pathBuilder.getAddPath(getType(), getSubType(), getId(object)); + write(object, addPath); + } + + @Override + public void update(T object) { + XmlPersistencePathBuilder pathBuilder = this.fileDao.getPathBuilder(); + File updatePath = pathBuilder.getUpdatePath(getType(), getSubType(), getId(object)); + write(object, updatePath); + } + + /** + * Returns the type of domain object being handled by this {@link XmlPersistenceDao}. This would in most cases be + * the simple name of the class being persisted + * + * @return the type of object being persisted + */ + protected abstract String getType(); + + /** + * Returns the sub type, enabling categorizing types by a sub type. Default implementation returns null, thus no + * categorization is performed for this {@link XmlPersistenceDao} implementation + * + * @return the sub type to further categorize the type of object being persisted + */ + protected String getSubType() { + return null; + } + + protected abstract String getId(T object); + + protected abstract T read(File filePath); + + protected abstract void write(T object, File filePath); +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java new file mode 100644 index 000000000..019a2ad71 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import java.util.Set; + +import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; +import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; + +/** + * @author Robert von Burg + * + */ +public abstract class MetadataXmlDao implements XmlPersistenceMetadataDao { + + private XmlPersistenceFileDao fileDao; + private XmlPersistenceFileHandler fileHandler; + + // TODO think about setting some methods to final + // TODO maybe decouple the write and load method into their own class + + @Override + public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao) { + this.fileDao = fileDao; + } + + @Override + public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler) { + this.fileHandler = fileHandler; + } + + /** + * @return the fileHandler + */ + protected XmlPersistenceFileHandler getFileHandler() { + return this.fileHandler; + } + + /** + * @return the fileDao + */ + protected XmlPersistenceFileDao getFileDao() { + return this.fileDao; + } + + @Override + public void removeAll() { + this.fileDao.removeAll(); + } + + @Override + public Set queryKeySet(String type, String subType) { + return this.fileDao.queryKeySet(type, subType); + } + + @Override + public Set queryKeySet(String type) { + return this.fileDao.queryKeySet(type); + } + + @Override + public Set queryKeySet() { + return this.fileDao.queryKeySet(); + } + + @Override + public long querySize(String type, String subType) { + return this.fileDao.querySize(type, subType); + } + + @Override + public long querySize(String type) { + return this.fileDao.querySize(type); + } + + @Override + public long querySize() { + return this.fileDao.querySize(); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java new file mode 100644 index 000000000..102c7738a --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; +import java.io.IOException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; + +import ch.eitchnet.utils.exceptions.XmlException; +import ch.eitchnet.utils.helper.XmlHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceContextData; +import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceDomHandler implements XmlPersistenceFileHandler { + + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceDomHandler.class); + + public DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { + DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); + return docBuilder; + } + + @Override + public void read(XmlPersistenceContextData contextData) { + + XmlPersistenceDomContextData cd = (XmlPersistenceDomContextData) contextData; + + // check assertions + if (cd.getFile() == null) + throw new IllegalStateException("No file has been set on the context data!"); + + try { + DocumentBuilder docBuilder = createDocumentBuilder(); + File file = cd.getFile(); + Document document = docBuilder.parse(file); + cd.setDocument(document); + } catch (ParserConfigurationException | SAXException | IOException e) { + throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); + } + + logger.info("DOM parsed file " + cd.getFile().getAbsolutePath()); + } + + @Override + public void write(XmlPersistenceContextData contextData) { + + XmlPersistenceDomContextData cd = (XmlPersistenceDomContextData) contextData; + + // check assertions + if (cd.getFile() == null) + throw new IllegalStateException("No file has been set on the context data!"); + if (cd.getDocument() == null) + throw new IllegalStateException("No document has been set on the context data!"); + + String lineSep = System.getProperty(XmlHelper.PROP_LINE_SEPARATOR); + try { + Document document = cd.getDocument(); + String encoding = document.getInputEncoding(); + if (encoding == null || encoding.isEmpty()) { + logger.info("No encoding passed. Using default encoding " + XmlHelper.DEFAULT_ENCODING); + encoding = XmlHelper.DEFAULT_ENCODING; + } + + if (!lineSep.equals("\n")) { + logger.info("Overriding line separator to \\n"); + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, "\n"); + } + + // Set up a transformer + TransformerFactory transfac = TransformerFactory.newInstance(); + Transformer transformer = transfac.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.ENCODING, encoding); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); + // transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\t"); + + // Transform to file + File file = new File("target/res_dom.xml"); + StreamResult result = new StreamResult(file); + Source xmlSource = new DOMSource(document); + transformer.transform(xmlSource, result); + + logger.info("Wrote DOM to " + file.getAbsolutePath()); + + } catch (TransformerFactoryConfigurationError | TransformerException e) { + throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); + } finally { + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep); + } + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java new file mode 100644 index 000000000..4697d8e58 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; +import java.text.MessageFormat; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; + +/** + * @author Robert von Burg + */ +public class XmlPersistenceFileDao { + + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceFileDao.class); + + private boolean verbose; + private XmlPersistencePathBuilder pathBuilder; + + public XmlPersistenceFileDao(XmlPersistencePathBuilder pathBuilder, Properties properties) { + + // get properties + String context = XmlPersistencePathBuilder.class.getSimpleName(); + boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, + Boolean.FALSE).booleanValue(); + + // initialize + this.verbose = verbose; + this.pathBuilder = pathBuilder; + } + + /** + * @return the pathBuilder + */ + public XmlPersistencePathBuilder getPathBuilder() { + return this.pathBuilder; + } + + public void removeAll() { + + File removePath = this.pathBuilder.getRemovePath(); + String failMsg = "Deletion of persistence units at {1} failed! Check file permissions!"; + remove(removePath, failMsg, removePath); + } + + public void removeAll(String type) { + + File removePath = this.pathBuilder.getRemovePath(type); + String failMsg = "Deletion of persistence units for {0} at {1} failed! Check file permissions!"; + remove(removePath, failMsg, type, removePath); + } + + public void removeAll(String type, String subType) { + + File removePath = this.pathBuilder.getRemovePath(type, subType); + String failMsg = "Deletion of persistence units for {0} / {1} at {2} failed! Check file permissions!"; + remove(removePath, failMsg, type, subType, removePath); + } + + public void remove(String type, String id) { + File removePath = this.pathBuilder.getRemovePath(type, id); + String failMsg = "Deletion of persistence units for {0} / {1} at {2} failed! Check file permissions!"; + remove(removePath, failMsg, type, id, removePath); + } + + public void remove(String type, String subType, String id) { + File removePath = this.pathBuilder.getRemovePath(type, subType, id); + String failMsg = "Deletion of persistence units for {0} / {1} / {2} at {3} failed! Check file permissions!"; + remove(removePath, failMsg, type, subType, id, removePath); + } + + private void remove(File removePath, String failMsg, Object... msgParts) { + File[] removePaths = new File[] { removePath }; + boolean removed = FileHelper.deleteFiles(removePaths, this.verbose); + if (!removed) { + String msg = MessageFormat.format(failMsg, msgParts); + throw new XmlPersistenceException(msg); + } + } + + /** + * Returns the set of types + * + * @return + */ + public Set queryKeySet() { + File queryPath = this.pathBuilder.getQueryPath(); + Set keySet = queryKeySet(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " types"); + return keySet; + } + + /** + * Returns the set of sub types for the given type + * + * @param type + * + * @return + */ + public Set queryKeySet(String type) { + File queryPath = this.pathBuilder.getQueryPath(type); + Set keySet = queryKeySet(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " elements for " + type); + return keySet; + } + + /** + * Returns the set of ids for the objects with the give type and sub type + * + * @param type + * @param subType + * + * @return + */ + public Set queryKeySet(String type, String subType) { + File queryPath = this.pathBuilder.getQueryPath(type, subType); + Set keySet = queryKeySet(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " elements for " + type); + return keySet; + } + + /** + * @param queryPath + * @return + */ + private Set queryKeySet(File queryPath) { + Set keySet = new HashSet(); + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + if (subTypeFile.isFile()) + keySet.add(this.pathBuilder.getId(subTypeFile.getName())); + } + + return keySet; + } + + public long querySize() { + File queryPath = this.pathBuilder.getQueryPath(); + long numberOfFiles = querySize(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " types"); + return numberOfFiles; + } + + public long querySize(String type) { + File queryPath = this.pathBuilder.getQueryPath(type); + long numberOfFiles = querySize(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " elements for " + type); + return numberOfFiles; + } + + public long querySize(String type, String subType) { + File queryPath = this.pathBuilder.getQueryPath(type, subType); + long numberOfFiles = querySize(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " elements for " + type); + return numberOfFiles; + } + + private long querySize(File queryPath) { + long numberOfFiles = 0l; + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isFile()) + numberOfFiles++; + } + return numberOfFiles; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java new file mode 100644 index 000000000..952669c7a --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java @@ -0,0 +1,298 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; + +/** + * @author Robert von Burg + */ +public class XmlPersistencePathBuilder { + private static final Logger logger = LoggerFactory.getLogger(XmlPersistencePathBuilder.class); + + public static final String FILE_EXT = ".xml"; + public static final int EXT_LENGTH = XmlPersistencePathBuilder.FILE_EXT.length(); + + private final boolean verbose; + private final String basePath; + + public XmlPersistencePathBuilder(Properties properties) { + + // get properties + String context = XmlPersistencePathBuilder.class.getSimpleName(); + boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, + Boolean.FALSE).booleanValue(); + String basePath = PropertiesHelper + .getProperty(properties, context, XmlPersistenceConstants.PROP_BASEPATH, null); + + // validate base path exists and is writable + File basePathF = new File(basePath); + if (!basePathF.exists()) + throw new XmlPersistenceException("The database store path does not exist at " + + basePathF.getAbsolutePath()); + if (!basePathF.canWrite()) + throw new XmlPersistenceException("The database store path is not writeable at " + + basePathF.getAbsolutePath()); + + // we want a clean base path + String canonicalBasePath; + try { + canonicalBasePath = basePathF.getCanonicalPath(); + } catch (IOException e) { + throw new XmlPersistenceException("Failed to build canonical path from " + basePath, e); + } + + // this.basePathF = basePathF; + this.basePath = canonicalBasePath; + this.verbose = verbose; + + logger.info("Using base path " + basePath); + } + + String getFilename(String id) { + return id.concat(XmlPersistencePathBuilder.FILE_EXT); + } + + String getId(String filename) { + assertFilename(filename); + + return filename.substring(0, filename.length() - XmlPersistencePathBuilder.EXT_LENGTH); + } + + String getPathAsString(String type, String subType, String id) { + StringBuilder sb = new StringBuilder(this.basePath); + if (!StringHelper.isEmpty(type)) { + sb.append("/"); + sb.append(type); + } + if (!StringHelper.isEmpty(subType)) { + sb.append("/"); + sb.append(subType); + } + if (!StringHelper.isEmpty(id)) { + sb.append("/"); + sb.append(getFilename(id)); + } + + return sb.toString(); + } + + File getPath() { + return new File(getPathAsString(null, null, null)); + } + + File getPath(String type) { + assertType(type); + return new File(getPathAsString(type, null, null)); + } + + File getPath(String type, String subType) { + assertType(type); + assertSubType(subType); + return new File(getPathAsString(type, subType, null)); + } + + File getPath(String type, String subType, String id) { + assertType(type); + assertSubType(subType); + assertId(id); + return new File(getPathAsString(type, subType, id)); + } + + File getAddPath(String type, String subType, String id) { + assertType(type); + assertSubType(subType); + assertId(id); + + File path = getPath(type, subType, id); + + if (path.exists()) { + String msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + + // check if parent path exists + if (!path.exists()) { + File parentFile = path.getParentFile(); + if (!parentFile.exists() && !parentFile.mkdirs()) { + String msg = "Could not create parent path for {0} / {1} / {2} at {3}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + } + + return path; + } + + File getUpdatePath(String type, String subType, String id) { + assertType(type); + assertSubType(subType); + assertId(id); + + File path = getPath(type, subType, id); + + if (!path.exists()) { + String msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + + return path; + } + + File getRemovePath() { + + File path = getPath(); + if (!path.exists()) { + String msg = "No Persistence units exist at {0}"; + throw new XmlPersistenceException(MessageFormat.format(msg, path.getAbsolutePath())); + } + + if (this.verbose) { + String msg = "Remove path for all is {0}..."; + logger.info(MessageFormat.format(msg, path.getAbsolutePath())); + } + + return path; + } + + File getRemovePath(String type) { + assertType(type); + + File path = getPath(type); + if (!path.exists()) { + String msg = "No Persistence units exist for {0} at {1}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, path.getAbsolutePath())); + } + + if (this.verbose) { + String msg = "Remove path for {0} is {1}..."; + logger.info(MessageFormat.format(msg, type, path.getAbsolutePath())); + } + + return path; + } + + File getRemovePath(String type, String subType) { + assertType(type); + assertSubType(subType); + + File path = getPath(type, subType); + if (!path.exists()) { + String msg = "No Persistence units exist for {0} / {1} at {2}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); + } + + if (this.verbose) { + String msg = "Remove path for {0} / {1} is {2}..."; + logger.info(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); + } + + return path; + } + + File getRemovePath(String type, String subType, String id) { + assertType(type); + assertSubType(subType); + assertId(id); + + File path = getPath(type, subType, id); + if (!path.exists()) { + String msg = "Persistence unit for {0} / {1} / {2} does not exist at {3}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + + if (this.verbose) { + String msg = "Remove path for {0} / {1} / {2} is {3}..."; + logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + + return path; + } + + File getQueryPath() { + return getPath(); + } + + File getQueryPath(String type) { + assertType(type); + File path = getPath(type); + if (this.verbose) { + String msg = "Query path for {0} is {1}..."; + logger.info(MessageFormat.format(msg, type, path.getAbsolutePath())); + } + return path; + } + + File getQueryPath(String type, String subType) { + assertType(type); + assertSubType(subType); + File path = getPath(type, subType); + if (this.verbose) { + String msg = "Query path for {0} / {1} is {2}..."; + logger.info(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); + } + return path; + } + + File getQueryPath(String type, String subType, String id) { + assertType(type); + assertSubType(subType); + assertId(id); + File path = getPath(type, subType, id); + if (this.verbose) { + String msg = "Query path for {0} / {1} / {2} is {3}..."; + logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + return path; + } + + private void assertId(String id) { + if (StringHelper.isEmpty(id)) + throw new XmlPersistenceException( + "The id can not be empty! An object must always be handled with at least the type and id!"); + } + + private void assertType(String type) { + if (StringHelper.isEmpty(type)) + throw new XmlPersistenceException( + "The type can not be empty! An object must always be handled with at least the type and id!"); + } + + private void assertSubType(String subType) { + if (StringHelper.isEmpty(subType)) + throw new XmlPersistenceException("The subType can not be empty!"); + } + + private void assertFilename(String filename) { + if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') + throw new XmlPersistenceException("The filename does not have a . at index " + + (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java new file mode 100644 index 000000000..7294e331d --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceStreamWriter { + + private XMLStreamWriter writer; + + public XmlPersistenceStreamWriter(XMLStreamWriter writer) { + this.writer = writer; + } + + /** + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String) + */ + public void writeEmptyElement(String localName) throws XMLStreamException { + this.writer.writeEmptyElement(localName); + } + + /** + * @param localName + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String) + */ + public void writeElement(String localName) throws XMLStreamException { + this.writer.writeStartElement(localName); + } + + /** + * Note: Don't call this method to close an element written by {@link #writeEmptyElement(String)} + * + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeEndElement() + */ + public void endElement() throws XMLStreamException { + this.writer.writeEndElement(); + } + + /** + * @param localName + * @param value + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String) + */ + public void writeAttribute(String localName, String value) throws XMLStreamException { + this.writer.writeAttribute(localName, value); + } + + /** + * @param data + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCData(java.lang.String) + */ + public void writeCData(String data) throws XMLStreamException { + this.writer.writeCData(data); + } + + /** + * @param text + * @throws XMLStreamException + * @see javax.xml.stream.XMLStreamWriter#writeCharacters(java.lang.String) + */ + public void writeCharacters(String text) throws XMLStreamException { + this.writer.writeCharacters(text); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/Main.java b/src/test/java/ch/eitchnet/xmlpers/test/Main.java new file mode 100644 index 000000000..bc61911d5 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/Main.java @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test; + +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.List; + +import javanet.staxutils.IndentingXMLStreamWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.utils.exceptions.XmlException; +import ch.eitchnet.utils.helper.XmlHelper; +import ch.eitchnet.xmlpers.test.model.Parameter; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class Main { + + private static final Logger logger = LoggerFactory.getLogger(Main.class); + + private static Resource res; + + public static void main(String[] args) throws Exception { + + res = new Resource(); + res.setId("id1"); + res.setName("name1"); + res.setType("type1"); + + Parameter param1 = new Parameter(); + param1.setId("paramId1"); + param1.setName("paramName1"); + param1.setType("paramType1"); + param1.setValue("paramValue1"); + res.addParameter(param1); + + Parameter param2 = new Parameter(); + param2.setId("paramId2"); + param2.setName("paramName2"); + param2.setType("paramType2"); + param2.setValue("paramValue2"); + res.addParameter(param2); + + Parameter param3 = new Parameter(); + param3.setId("paramId3"); + param3.setName("paramName3"); + param3.setType("paramType3"); + param3.setValue("paramValue3"); + res.addParameter(param3); + + logger.info("Writing Res:\n" + res); + + writeSax(res); + writeDom(res); + + List resoures; + resoures = readDom(); + logger.info("Parsed Resources:\n" + resoures); + resoures = readSax(); + logger.info("Parsed Resources:\n" + resoures); + } + + /** + * @return + * + */ + private static List readDom() throws Exception { + + File file = new File("target/res_dom.xml"); + DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); + Document document = docBuilder.parse(file); + Element rootElement = document.getDocumentElement(); + + List resources = new ArrayList(); + + NodeList resElements = rootElement.getElementsByTagName("Resource"); + for (int i = 0; i < resElements.getLength(); i++) { + Element resElement = (Element) resElements.item(i); + String id = resElement.getAttribute("id"); + String name = resElement.getAttribute("name"); + String type = resElement.getAttribute("type"); + + Resource res = new Resource(); + res.setId(id); + res.setName(name); + res.setType(type); + + NodeList paramElements = resElement.getElementsByTagName("Parameter"); + parseParameters(res, paramElements); + + resources.add(res); + } + + logger.info("DOM parsed file " + file.getAbsolutePath()); + + return resources; + } + + /** + * @param res2 + * @param paramElements + */ + private static void parseParameters(Resource res, NodeList paramElements) { + for (int i = 0; i < paramElements.getLength(); i++) { + Element paramElement = (Element) paramElements.item(i); + String id = paramElement.getAttribute("id"); + String name = paramElement.getAttribute("name"); + String type = paramElement.getAttribute("type"); + String value = paramElement.getAttribute("value"); + + Parameter param = new Parameter(); + param.setId(id); + param.setName(name); + param.setType(type); + param.setValue(value); + + res.addParameter(param); + } + } + + /** + * @return + * + */ + private static List readSax() throws Exception { + + final List resources = new ArrayList<>(); + final Resource[] currentRes = new Resource[1]; + + DefaultHandler xmlHandler = new DefaultHandler() { + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) + throws SAXException { + + switch (qName) { + case "Resource": + Resource res = new Resource(); + res.setId(attributes.getValue("id")); + res.setName(attributes.getValue("name")); + res.setType(attributes.getValue("type")); + currentRes[0] = res; + resources.add(res); + break; + case "Parameter": + Parameter param = new Parameter(); + param.setId(attributes.getValue("id")); + param.setName(attributes.getValue("name")); + param.setType(attributes.getValue("type")); + param.setValue(attributes.getValue("value")); + currentRes[0].addParameter(param); + break; + case "model": + break; + default: + throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); + } + } + }; + + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser sp = spf.newSAXParser(); + File file = new File("target/res_sax.xml"); + sp.parse(file, xmlHandler); + + logger.info("SAX parsed file " + file.getAbsolutePath()); + + return resources; + } + + private static void writeDom(Resource res) throws Exception { + + DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); + Document doc = docBuilder.newDocument(); + + Element resElement = doc.createElement("Resource"); + resElement.setAttribute("id", res.getId()); + resElement.setAttribute("name", res.getName()); + resElement.setAttribute("type", res.getType()); + + for (String paramId : res.getParameterKeySet()) { + Parameter param = res.getParameterBy(paramId); + Element paramElement = doc.createElement("Parameter"); + paramElement.setAttribute("id", param.getId()); + paramElement.setAttribute("name", param.getName()); + paramElement.setAttribute("type", param.getType()); + paramElement.setAttribute("value", param.getValue()); + resElement.appendChild(paramElement); + } + + Element rootElement = doc.createElement("model"); + rootElement.appendChild(resElement); + + doc.appendChild(rootElement); + + String lineSep = System.getProperty(XmlHelper.PROP_LINE_SEPARATOR); + try { + + String encoding = doc.getInputEncoding(); + if (encoding == null || encoding.isEmpty()) { + logger.info("No encoding passed. Using default encoding " + XmlHelper.DEFAULT_ENCODING); + encoding = XmlHelper.DEFAULT_ENCODING; + } + + if (!lineSep.equals("\n")) { + logger.info("Overriding line separator to \\n"); + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, "\n"); + } + + // Set up a transformer + TransformerFactory transfac = TransformerFactory.newInstance(); + Transformer transformer = transfac.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.ENCODING, encoding); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); + // transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\t"); + + // Transform to file + File file = new File("target/res_dom.xml"); + StreamResult result = new StreamResult(file); + Source xmlSource = new DOMSource(doc); + transformer.transform(xmlSource, result); + + logger.info("Wrote DOM to " + file.getAbsolutePath()); + + } catch (Exception e) { + + throw new XmlException("Exception while exporting to file: " + e, e); + + } finally { + + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep); + } + } + + private static void writeSax(Resource res) throws Exception { + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + + File file = new File("target/res_sax.xml"); + XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file)); + + writer = new IndentingXMLStreamWriter(writer); + + writer.writeStartDocument("utf-8", "1.0"); + writer.writeStartElement("model"); + + writer.writeStartElement("Resource"); + writer.writeAttribute("id", res.getId()); + writer.writeAttribute("name", res.getName()); + writer.writeAttribute("type", res.getType()); + + for (String paramId : res.getParameterKeySet()) { + Parameter param = res.getParameterBy(paramId); + writer.writeEmptyElement("Parameter"); + writer.writeAttribute("id", param.getId()); + writer.writeAttribute("name", param.getName()); + writer.writeAttribute("type", param.getType()); + writer.writeAttribute("value", param.getValue()); + } + + //writer.writeEmptyElement("data"); + //writer.writeAttribute("name", "value"); + ////writer.writeEndElement(); + //writer.writeEmptyElement("stuff"); + //writer.writeAttribute("attr", "attrVal"); + + writer.writeEndElement(); + writer.writeEndDocument(); + + writer.flush(); + writer.close(); + logger.info("Wrote SAX to " + file.getAbsolutePath()); + + //Transformer transformer = TransformerFactory.newInstance().newTransformer(); + //Result outputTarget = new StaxR; + //Source xmlSource; + //transformer.transform(xmlSource, outputTarget); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java index 12aeb4314..7e6eb3048 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java @@ -21,6 +21,7 @@ package ch.eitchnet.xmlpers.test; import java.io.File; import java.util.List; +import java.util.Properties; import java.util.Set; import org.junit.Assert; @@ -30,12 +31,12 @@ import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import ch.eitchnet.utils.objectfilter.ITransactionObject; -import ch.eitchnet.xmlpers.XmlPersistenceExecption; -import ch.eitchnet.xmlpers.XmlPersistenceHandler; -import ch.eitchnet.xmlpers.XmlPersistenceTransaction; -import ch.eitchnet.xmlpers.test.impl.MyClass; -import ch.eitchnet.xmlpers.test.impl.MyDaoFactory; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.api.XmlPersistenceHandler; +import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; +import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; +import ch.eitchnet.xmlpers.test.model.Resource; /** * @author Robert von Burg @@ -45,6 +46,12 @@ public class XmlPersistenceTest { private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTest.class.getName()); + private static final String RES_TYPE = "@subType"; + private static final String RES_TYPE_INEXISTANT = "@inexistant"; + private static final String RES_NAME = "@name"; + private static final String RES_NAME_MODIFIED = "@name_modified"; + private static final String RES_ID = "@id"; + private static XmlPersistenceHandler persistenceHandler; /** @@ -60,13 +67,13 @@ public class XmlPersistenceTest { if (!basePathF.exists() && !basePathF.mkdirs()) Assert.fail("Could not create temporaray database store in " + basePathF.getAbsolutePath()); - System.setProperty(XmlPersistenceHandler.CONFIG_BASEPATH, "target/testdb"); - System.setProperty(XmlPersistenceHandler.CONFIG_VERBOSE, "true"); - System.setProperty(XmlPersistenceHandler.CONFIG_DAO_FACTORY_CLASS, MyDaoFactory.class.getName()); + Properties props = new Properties(); + props.setProperty(XmlPersistenceConstants.PROP_BASEPATH, "target/testdb"); + props.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); + props.setProperty(XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, TestModelDaoFactory.class.getName()); XmlPersistenceTest.persistenceHandler = new XmlPersistenceHandler(); - XmlPersistenceTest.persistenceHandler.initialize(); - + XmlPersistenceTest.persistenceHandler.initialize(props); XmlPersistenceTest.logger.info("Initialized persistence handler."); } catch (Exception e) { @@ -101,12 +108,12 @@ public class XmlPersistenceTest { XmlPersistenceTest.logger.info("Trying to create..."); // new instance - MyClass myClass = new MyClass("@id", "@name", "@subtype"); + Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); // persist instance XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - tx.add(myClass); - XmlPersistenceTest.persistenceHandler.commitTx(); + tx.add(resource); + tx.commit(); XmlPersistenceTest.logger.info("Done creating."); @@ -121,11 +128,11 @@ public class XmlPersistenceTest { try { XmlPersistenceTest.logger.info("Trying to read..."); - // query MyClass with id @id + // query Resource with id @id XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - XmlPersistenceTest.logger.info("Found MyClass: " + myClass); - XmlPersistenceTest.persistenceHandler.commitTx(); + Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); + XmlPersistenceTest.logger.info("Found Resource: " + resource); + tx.commit(); XmlPersistenceTest.logger.info("Done reading."); @@ -142,15 +149,15 @@ public class XmlPersistenceTest { // query the instance XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - XmlPersistenceTest.logger.info("Found MyClass: " + myClass); + Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); + XmlPersistenceTest.logger.info("Found Resource: " + resource); // modify the instance - myClass.setName("@name_modified"); + resource.setName(RES_NAME_MODIFIED); // update the instance - tx.update(myClass); - XmlPersistenceTest.persistenceHandler.commitTx(); + tx.update(resource); + tx.commit(); XmlPersistenceTest.logger.info("Done updating."); @@ -166,39 +173,35 @@ public class XmlPersistenceTest { // query the instance XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - XmlPersistenceTest.logger.info("Found MyClass: " + myClass); + Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); + XmlPersistenceTest.logger.info("Found Resource: " + resource); - tx.remove(myClass); - XmlPersistenceTest.persistenceHandler.commitTx(); + tx.remove(resource); + tx.commit(); XmlPersistenceTest.logger.info("Done removing."); } - /** - * - */ @Test public void testQueryFail() { + XmlPersistenceTransaction tx = null; try { XmlPersistenceTest.logger.info("Trying to query removed object..."); - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - MyClass myClass = tx.queryById(MyClass.class.getName(), "@subtype", "@id"); - XmlPersistenceTest.logger.info("Found MyClass: " + myClass); + tx = XmlPersistenceTest.persistenceHandler.openTx(); + Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); + XmlPersistenceTest.logger.info("Found Resource: " + resource); XmlPersistenceTest.logger.info("Done querying removed object"); - } catch (XmlPersistenceExecption e) { + } catch (XmlPersistenceException e) { Assert.assertEquals("Wrong error message. Expected error that object does not exist", - "No object exists for ch.eitchnet.xmlpers.test.impl.MyClass / @subtype / @id", + "No object exists for ch.eitchnet.xmlpers.test.impl.Resource / @subtype / @id", e.getLocalizedMessage()); } finally { - XmlPersistenceTest.persistenceHandler.commitTx(); + if (tx != null) + tx.commit(); } } - /** - * - */ @Test public void testReCreate() { @@ -206,12 +209,12 @@ public class XmlPersistenceTest { XmlPersistenceTest.logger.info("Trying to recreate..."); // new instance - MyClass myClass = new MyClass("@id", "@name", "@subtype"); + Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); // persist instance XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - tx.add(myClass); - XmlPersistenceTest.persistenceHandler.commitTx(); + tx.add(resource); + tx.commit(); XmlPersistenceTest.logger.info("Done creating."); @@ -221,101 +224,94 @@ public class XmlPersistenceTest { } } - /** - * - */ @Test @Ignore public void testQueryFromTo() { Assert.fail("Not yet implemented"); } - /** - * - */ @Test public void testQueryAll() { + XmlPersistenceTransaction tx = null; try { XmlPersistenceTest.logger.info("Trying to query all..."); // query all - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - List list = tx.queryAll(MyClass.class.getName()); + tx = XmlPersistenceTest.persistenceHandler.openTx(); + List list = tx.queryAll(Resource.class.getName()); Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); // also with subtype - list = tx.queryAll(MyClass.class.getName(), "@subtype"); + list = tx.queryAll(Resource.class.getName(), RES_TYPE); Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); // and now something useless - list = tx.queryAll(MyClass.class.getName(), "@inexistant"); + list = tx.queryAll(Resource.class.getName(), RES_TYPE_INEXISTANT); Assert.assertTrue("Expected no objects, found " + list.size(), list.size() == 0); XmlPersistenceTest.logger.info("Done querying."); } finally { - XmlPersistenceTest.persistenceHandler.commitTx(); + if (tx != null) + tx.commit(); } } - /** - * - */ @Test public void testKeySet() { + XmlPersistenceTransaction tx = null; try { - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); + tx = XmlPersistenceTest.persistenceHandler.openTx(); - Set keySet = tx.queryKeySet(MyClass.class.getName()); + Set keySet = tx.queryKeySet(Resource.class.getName()); Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); // also with subtype - keySet = tx.queryKeySet(MyClass.class.getName(), "@subtype"); + keySet = tx.queryKeySet(Resource.class.getName(), RES_TYPE); Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); // and now something useless - keySet = tx.queryKeySet(MyClass.class.getName(), "@inexistant"); + keySet = tx.queryKeySet(Resource.class.getName(), RES_TYPE_INEXISTANT); Assert.assertTrue("Expected no keys, found " + keySet, keySet.size() == 0); } finally { - XmlPersistenceTest.persistenceHandler.commitTx(); + if (tx != null) + tx.commit(); } } - /** - * - */ @Test public void testRemoveAll() { + XmlPersistenceTransaction tx = null; try { - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); + tx = XmlPersistenceTest.persistenceHandler.openTx(); - List objects = tx.queryAll(MyClass.class.getName(), "@subType"); + List objects = tx.queryAll(Resource.class.getName(), RES_TYPE); tx.removeAll(objects); } finally { - XmlPersistenceTest.persistenceHandler.commitTx(); + if (tx != null) + tx.commit(); } } - /** - * - */ @Test public void testSize() { + XmlPersistenceTransaction tx = null; try { - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); + tx = XmlPersistenceTest.persistenceHandler.openTx(); - long size = tx.querySize(MyClass.class.getName(), "@subType"); + long size = tx.querySize(Resource.class.getName(), RES_TYPE); Assert.assertTrue("Expected size = 0, found: " + size, size == 0); } finally { - XmlPersistenceTest.persistenceHandler.commitTx(); + if (tx != null) + tx.commit(); } } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java new file mode 100644 index 000000000..54ec38957 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl; + +/** + * @author Robert von Burg + * + */ +public class Book { + + private final Long id; + private String title; + private String author; + private String press; + private double price; + + /** + * + */ + public Book(Long id) { + if (id == null) + throw new IllegalArgumentException("Id may not be null!"); + this.id = id; + } + + /** + * @return the id + */ + public Long getId() { + return this.id; + } + + /** + * @return the title + */ + public String getTitle() { + return this.title; + } + + /** + * @param title + * the title to set + */ + public void setTitle(String title) { + this.title = title; + } + + /** + * @return the author + */ + public String getAuthor() { + return this.author; + } + + /** + * @param author + * the author to set + */ + public void setAuthor(String author) { + this.author = author; + } + + /** + * @return the press + */ + public String getPress() { + return this.press; + } + + /** + * @param press + * the press to set + */ + public void setPress(String press) { + this.press = press; + } + + /** + * @return the price + */ + public double getPrice() { + return this.price; + } + + /** + * @param price + * the price to set + */ + public void setPrice(double price) { + this.price = price; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java new file mode 100644 index 000000000..26f1800d0 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.impl.AbstractXmlDao; + +/** + * @author Robert von Burg + * + */ +public abstract class BookDao extends AbstractXmlDao { + + @Override + protected String getType() { + return Book.class.getSimpleName(); + } + + @Override + protected String getId(Book object) { + return object.getId().toString(); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java deleted file mode 100644 index a0c1d3e2c..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClass.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test.impl; - -import ch.eitchnet.utils.objectfilter.ITransactionObject; - -/** - * @author Robert von Burg - * - */ -public class MyClass implements ITransactionObject { - - private long txId; - private String id; - private String name; - private String type; - - /** - * @param id - * @param name - * @param type - */ - public MyClass(String id, String name, String type) { - super(); - this.id = id; - this.name = name; - this.type = type; - } - - /** - * @return the id - */ - public String getId() { - return this.id; - } - - /** - * @param id - * the id to set - */ - public void setId(String id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return this.name; - } - - /** - * @param name - * the name to set - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the type - */ - public String getType() { - return this.type; - } - - /** - * @param type - * the type to set - */ - public void setType(String type) { - this.type = type; - } - - /** - * @see ch.eitchnet.utils.objectfilter.ITransactionObject#setTransactionID(long) - */ - @Override - public void setTransactionID(long id) { - this.txId = id; - } - - /** - * @see ch.eitchnet.utils.objectfilter.ITransactionObject#getTransactionID() - */ - @Override - public long getTransactionID() { - return this.txId; - } - - /** - * @see ch.eitchnet.utils.objectfilter.ITransactionObject#resetTransactionID() - */ - @Override - public void resetTransactionID() { - this.txId = ITransactionObject.UNSET; - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java similarity index 83% rename from src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java index 8a8a80609..fef67ed53 100644 --- a/src/main/java/ch/eitchnet/xmlpers/XmlSaxWriter.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java @@ -19,13 +19,16 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers; - +package ch.eitchnet.xmlpers.test.impl; /** * @author Robert von Burg - * + * */ -public interface XmlSaxWriter { +public class MyTypeResourceDao extends ResourceDao { + @Override + public String getSubType() { + return "MyType"; + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java new file mode 100644 index 000000000..3f7517370 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.impl.AbstractXmlDao; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public abstract class ResourceDao extends AbstractXmlDao { + + @Override + public String getType() { + return Resource.class.getSimpleName(); + } + + @Override + public abstract String getSubType(); + + @Override + public String getId(Resource object) { + return object.getId(); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java new file mode 100644 index 000000000..2a267cbba --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.test.impl; + +import java.io.File; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Text; + +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public abstract class ResourceDomDao extends ResourceDao { + + @Override + protected Resource read(File filePath) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected void write(Resource object, File filePath) { + // TODO Auto-generated method stub + + } + + public Element serializeToDom(Resource object, Document document) { + + Element element = document.createElement("Resource"); + + element.setAttribute("id", object.getId()); + element.setAttribute("type", object.getType()); + + Element nameElement = document.createElement("Name"); + element.appendChild(nameElement); + Text textNode = document.createTextNode(object.getName()); + nameElement.appendChild(textNode); + + return element; + } + + public Resource parseFromDom(Element element) { + + String id = element.getAttribute("id"); + String type = element.getAttribute("type"); + Element nameElement = (Element) element.getElementsByTagName("Name").item(0); + String name = nameElement.getTextContent(); + + Resource Resource = new Resource(id, name, type); + + return Resource; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java similarity index 50% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java index 9e426d13a..c31e9018c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyClassDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java @@ -19,83 +19,29 @@ */ package ch.eitchnet.xmlpers.test.impl; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Text; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; -import ch.eitchnet.xmlpers.XmlDao; +import ch.eitchnet.xmlpers.test.model.Resource; /** * @author Robert von Burg * */ -public class MyClassDao implements XmlDao { +public class ResourceSaxDao extends ResourceDao { - @Override - public String getType(MyClass object) { - return MyClass.class.getName(); - } - - @Override - public String getSubType(MyClass object) { - return object.getType(); - } - - @Override - public String getId(MyClass object) { - return object.getId(); - } - - @Override - public Element serializeToDom(MyClass object, Document document) { - - Element element = document.createElement("MyClass"); - - element.setAttribute("id", object.getId()); - element.setAttribute("type", object.getType()); - - Element nameElement = document.createElement("Name"); - element.appendChild(nameElement); - Text textNode = document.createTextNode(object.getName()); - nameElement.appendChild(textNode); - - return element; - } - - /** - * @see ch.eitchnet.xmlpers.XmlDao#parseFromDom(org.w3c.dom.Element) - */ - @Override - public MyClass parseFromDom(Element element) { - - String id = element.getAttribute("id"); - String type = element.getAttribute("type"); - Element nameElement = (Element) element.getElementsByTagName("Name").item(0); - String name = nameElement.getTextContent(); - - MyClass myClass = new MyClass(id, name, type); - - return myClass; - } - - /** - * @see ch.eitchnet.xmlpers.XmlDao#serializeToSax(java.lang.Object, org.xml.sax.ContentHandler) - */ - @Override - public void serializeToSax(MyClass object, ContentHandler contentHandler) { + public void serializeToSax(Resource object, ContentHandler contentHandler) { try { contentHandler.startDocument(); - // MyClass element / root + // Resource element / root { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "", "id", "", object.getId()); atts.addAttribute("", "", "type", "", object.getType()); - contentHandler.startElement("", "", "MyClass", atts); + contentHandler.startElement("", "", "Resource", atts); // name element { @@ -105,8 +51,8 @@ public class MyClassDao implements XmlDao { contentHandler.endElement("", "", "name"); } - // MyClass end - contentHandler.endElement("", "", "MyClass"); + // Resource end + contentHandler.endElement("", "", "Resource"); } // end document diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java new file mode 100644 index 000000000..abd7c9e45 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.test.impl; + +import java.util.Properties; + +import ch.eitchnet.xmlpers.api.XmlPersistenceDao; +import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class TestModelDaoFactory implements XmlPersistenceDaoFactory { + + @Override + public void initialize(XmlPersistenceFileDao fileDao, Properties properties) { + // TODO Auto-generated method stub + + } + + @Override + public XmlPersistenceDao createDaoInstance(T object) { + + if (object.getClass() != Resource.class) + throw new IllegalArgumentException("The object with class " + object.getClass() + " is not handled!"); + + Resource resource = (Resource) object; + String type = resource.getType(); + XmlPersistenceDao dao; + switch (type) { + case "MyType": + dao = new MyTypeResourceDao(); + break; + default: + throw new IllegalArgumentException("The resource with type " + type + " is not handled!"); + } + + // inject the DAO or SAX handler... + + @SuppressWarnings("unchecked") + XmlPersistenceDao xmlDao = (XmlPersistenceDao) dao; + return xmlDao; + } + + @Override + public XmlPersistenceDao createDaoInstance(String type) { + // TODO Auto-generated method stub + return null; + } + + @Override + public XmlPersistenceDao createDaoInstance(String type, String subType) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java new file mode 100644 index 000000000..99fa52403 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.model; + +public class Parameter { + + private String id; + private String name; + private String type; + private String value; + + /** + * + */ + public Parameter() { + // empty constructor + } + + /** + * @param id + * @param name + * @param type + * @param value + */ + public Parameter(String id, String name, String type, String value) { + super(); + this.id = id; + this.name = name; + this.type = type; + this.value = value; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Parameter [id="); + builder.append(this.id); + builder.append(", name="); + builder.append(this.name); + builder.append(", type="); + builder.append(this.type); + builder.append(", value="); + builder.append(this.value); + builder.append("]"); + return builder.toString(); + } + + /** + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return this.name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the type + */ + public String getType() { + return this.type; + } + + /** + * @param type + * the type to set + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return the value + */ + public String getValue() { + return this.value; + } + + /** + * @param value + * the value to set + */ + public void setValue(String value) { + this.value = value; + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java new file mode 100644 index 000000000..283b758d5 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.model; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +public class Resource { + + private String id; + private String name; + private String type; + private Map parameters = new HashMap(); + + /** + * + */ + public Resource() { + // empty constructor + } + + /** + * @param id + * @param name + * @param type + */ + public Resource(String id, String name, String type) { + super(); + this.id = id; + this.name = name; + this.type = type; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("Resource [id="); + builder.append(this.id); + builder.append(", name="); + builder.append(this.name); + builder.append(", type="); + builder.append(this.type); + builder.append(", parameters="); + for (Entry param : this.parameters.entrySet()) { + builder.append("\n"); + builder.append(" " + param.getKey() + " = " + param.getValue()); + } + builder.append("]"); + return builder.toString(); + } + + /** + * @return the id + */ + public String getId() { + return this.id; + } + + /** + * @param id + * the id to set + */ + public void setId(String id) { + this.id = id; + } + + /** + * @return the name + */ + public String getName() { + return this.name; + } + + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the type + */ + public String getType() { + return this.type; + } + + /** + * @param type + * the type to set + */ + public void setType(String type) { + this.type = type; + } + + public void addParameter(Parameter parameter) { + this.parameters.put(parameter.getId(), parameter); + } + + public Set getParameterKeySet() { + return this.parameters.keySet(); + } + + public Parameter getParameterBy(String id) { + return this.parameters.get(id); + } +} \ No newline at end of file From 289cee3f51af698a6b3f83fac105473fff70d3d7 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 14 Sep 2013 08:45:12 +0200 Subject: [PATCH 20/87] [Major] major rewrite, now implemented SAX and DOM methods. SAX works, DOM does not yet work. Simpler implementation now by not having to modify domain objects so they can be persisted. --- .../xmlpers/api/AbstractDaoFactory.java | 91 ++++ .../xmlpers/{impl => api}/AbstractXmlDao.java | 117 +++-- .../java/ch/eitchnet/xmlpers/api/DomUtil.java | 43 ++ .../ch/eitchnet/xmlpers/api/XmlIoMode.java} | 9 +- .../xmlpers/api/XmlPersistenceConstants.java | 8 +- .../xmlpers/api/XmlPersistenceDao.java | 6 - .../xmlpers/api/XmlPersistenceDaoFactory.java | 8 +- .../xmlpers/api/XmlPersistenceHandler.java | 90 +--- .../api/XmlPersistenceMetadataDao.java | 14 +- .../api/XmlPersistenceTransaction.java | 255 ++-------- .../eitchnet/xmlpers/impl/MetadataXmlDao.java | 53 +-- .../impl/TransactionDaoFactoryFacade.java | 107 +++++ .../impl/XmlPersistenceDomHandler.java | 18 +- .../xmlpers/impl/XmlPersistenceFileDao.java | 257 +++++++++-- .../impl/XmlPersistenceHandlerImpl.java | 90 ++++ .../impl/XmlPersistencePathBuilder.java | 173 ++++--- .../XmlPersistenceSaxHandler.java | 7 +- .../impl/XmlPersistenceTransactionImpl.java | 224 +++++++++ .../test/AbstractXmlPersistenceTest.java | 434 ++++++++++++++++++ .../xmlpers/test/XmlPersistenceDomTest.java | 51 ++ .../xmlpers/test/XmlPersistenceSaxTest.java | 49 ++ .../xmlpers/test/XmlPersistenceTest.java | 317 ------------- .../ch/eitchnet/xmlpers/test/impl/Book.java | 16 + .../eitchnet/xmlpers/test/impl/BookDao.java | 2 +- .../xmlpers/test/impl/BookDomDao.java | 89 ++++ .../xmlpers/test/impl/BookSaxDao.java | 113 +++++ .../xmlpers/test/impl/ResourceDao.java | 12 +- .../xmlpers/test/impl/ResourceDomDao.java | 73 ++- .../xmlpers/test/impl/ResourceSaxDao.java | 114 ++++- .../xmlpers/test/impl/TestConstants.java | 34 ++ .../test/impl/TestModelDaoFactory.java | 90 ++-- 31 files changed, 2030 insertions(+), 934 deletions(-) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java rename src/main/java/ch/eitchnet/xmlpers/{impl => api}/AbstractXmlDao.java (51%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java => main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java} (83%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java rename src/main/java/ch/eitchnet/xmlpers/{api => impl}/XmlPersistenceSaxHandler.java (93%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java new file mode 100644 index 000000000..09a21cc29 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.impl.MetadataXmlDao; +import ch.eitchnet.xmlpers.impl.XmlPersistenceDomHandler; +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; +import ch.eitchnet.xmlpers.impl.XmlPersistenceSaxHandler; +import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; + +/** + * @author Robert von Burg + */ +public abstract class AbstractDaoFactory implements XmlPersistenceDaoFactory { + + private static final Logger logger = LoggerFactory.getLogger(AbstractDaoFactory.class); + + private XmlIoMode xmlIoMode; + private XmlPersistenceFileDao fileDao; + + @Override + public void initialize(XmlPersistenceFileDao fileDao, Properties properties) { + this.fileDao = fileDao; + // TODO catch and throw proper exception + String xmlIoModeS = PropertiesHelper.getProperty(properties, TestModelDaoFactory.class.getName(), + XmlPersistenceConstants.PROP_XML_IO_MOD, XmlIoMode.SAX.name()); + this.xmlIoMode = XmlIoMode.valueOf(xmlIoModeS.toUpperCase()); + logger.info("Defaut Xml IO Mode is " + this.xmlIoMode.name()); + } + + /** + * @return + * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getMetadataDao() + */ + @Override + public XmlPersistenceMetadataDao getMetadataDao() { + MetadataXmlDao metadataDao = new MetadataXmlDao(); + metadataDao.initialize(this.fileDao); + return metadataDao; + } + + protected XmlIoMode getXmlIoMode() { + return this.xmlIoMode; + } + + protected XmlPersistenceDao initializeDao(XmlPersistenceDao dao) { + if (!(dao instanceof AbstractXmlDao)) { + throw new IllegalArgumentException("Your dao implementation does not extend from " + + AbstractXmlDao.class.getName() + "!"); + } + AbstractXmlDao abstractXmlDao = (AbstractXmlDao) dao; + abstractXmlDao.initialize(this.fileDao, getXmlFileHandler(this.xmlIoMode)); + return dao; + } + + protected XmlPersistenceFileHandler getXmlFileHandler(XmlIoMode ioMode) { + switch (ioMode) { + case DOM: + return new XmlPersistenceDomHandler(); + case SAX: + return new XmlPersistenceSaxHandler(); + default: + throw new IllegalArgumentException("The XmlIoMode " + ioMode + " is not yet supported!"); + } + } +} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java b/src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java similarity index 51% rename from src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java rename to src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java index 7d4491855..321958b0c 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/AbstractXmlDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java @@ -19,16 +19,16 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.impl; +package ch.eitchnet.xmlpers.api; import java.io.File; +import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Set; import ch.eitchnet.utils.exceptions.XmlException; -import ch.eitchnet.xmlpers.api.XmlPersistenceDao; -import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; +import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; /** * @author Robert von Burg @@ -40,17 +40,23 @@ public abstract class AbstractXmlDao implements XmlPersistenceDao { private XmlPersistenceFileHandler fileHandler; // TODO think about setting some methods to final - // TODO maybe decouple the write and load method into their own class // TODO if no sub type is given, then don't search recursively - it means subType does not exist - @Override - public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao) { + void initialize(XmlPersistenceFileDao fileDao, XmlPersistenceFileHandler fileHandler) { + if (fileDao == null || fileHandler == null) + throw new IllegalArgumentException("Neither fileDao nor fileHandler may be null!"); + if (this.fileDao != null) + throw new IllegalStateException("DAO is already initialized!"); this.fileDao = fileDao; + this.fileHandler = fileHandler; } - @Override - public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler) { - this.fileHandler = fileHandler; + protected XmlPersistenceFileDao getXmlPersistenceFileDao() { + return this.fileDao; + } + + protected XmlPersistenceFileHandler getXmlPersistenceFileHandler() { + return this.fileHandler; } /** @@ -69,45 +75,69 @@ public abstract class AbstractXmlDao implements XmlPersistenceDao { @Override public void remove(T object) { - this.fileDao.remove(getType(), getSubType(), getId(object)); + if (getSubType() == null) + this.fileDao.remove(getType(), getId(object)); + else + this.fileDao.remove(getType(), getSubType(), getId(object)); } @Override public void removeById(String id) { - this.fileDao.remove(getType(), getSubType(), id); + if (getSubType() == null) + this.fileDao.remove(getType(), id); + else + this.fileDao.remove(getType(), getSubType(), id); } @Override public void removeAll() { - this.fileDao.removeAll(getType(), getSubType()); + if (getSubType() == null) + this.fileDao.removeAll(getType()); + else + this.fileDao.removeAll(getType(), getSubType()); } @Override public Set queryKeySet() { + if (getSubType() == null) + return this.fileDao.queryKeySet(getType()); return this.fileDao.queryKeySet(getType(), getSubType()); } @Override public long querySize() { + if (getSubType() == null) + return this.fileDao.querySize(getType()); return this.fileDao.querySize(getType(), getSubType()); } @Override public List queryAll() { - File queryPath = this.fileDao.getPathBuilder().getPath(getType(), getSubType()); - String msg = "Can not read persistence unit for {0} / {1} at {2}"; - return queryAll(queryPath, msg, getType(), getSubType(), queryPath); - } - private List queryAll(File queryPath, String errorMsg, Object... msgArgs) { - File[] persistenceUnits = queryPath.listFiles(); - List result = new ArrayList<>(); - for (File persistenceUnit : persistenceUnits) { - if (!persistenceUnit.isFile()) - continue; + if (getSubType() == null) { - assertReadable(persistenceUnit, errorMsg, msgArgs); - T object = read(persistenceUnit); + Set idsByType = this.fileDao.queryKeySet(getType()); + List result = new ArrayList<>(idsByType.size()); + + for (String id : idsByType) { + File objectPath = this.fileDao.getReadPath(getType(), id); + String msg = "Can not read persistence units for {0} / {1} at {2}"; + assertReadable(objectPath, msg, getType(), id, objectPath); + T object = read(objectPath); + result.add(object); + } + + return result; + } + + Set idsByType = this.fileDao.queryKeySet(getType(), getSubType()); + List result = new ArrayList<>(idsByType.size()); + + for (String id : idsByType) { + File objectPath = this.fileDao.getReadPath(getType(), getSubType(), id); + String msg = "Can not read persistence units for {0} / {1} / {2} at {3}"; + assertReadable(objectPath, msg, getType(), getSubType(), id, objectPath); + T object = read(objectPath); result.add(object); } @@ -116,36 +146,51 @@ public abstract class AbstractXmlDao implements XmlPersistenceDao { private void assertReadable(File persistenceUnit, String errorMsg, Object... msgArgs) { if (!persistenceUnit.canRead()) { - String msg = String.format(errorMsg, msgArgs); + String msg = MessageFormat.format(errorMsg, msgArgs); throw new XmlException(msg); } } @Override public T queryById(String id) { - File persistenceUnit = this.fileDao.getPathBuilder().getPath(getType(), getSubType(), id); - String msg = "Can not read persistence unit for {0} / {1} / {2} at {3}"; - return queryById(persistenceUnit, msg, getType(), getSubType(), id, persistenceUnit); - } + if (getSubType() == null) { + File persistenceUnit = this.fileDao.getReadPath(getType(), id); + if (!persistenceUnit.exists()) + return null; + String msg = "Can not read persistence unit for {0} / {1} at {2}"; + assertReadable(persistenceUnit, msg, getType(), id, persistenceUnit); + T object = read(persistenceUnit); + return object; + } - private T queryById(File persistenceUnit, String msg, Object... msgArgs) { - assertReadable(persistenceUnit, msg, msgArgs); + File persistenceUnit = this.fileDao.getReadPath(getType(), getSubType(), id); + if (!persistenceUnit.exists()) + return null; + String msg = "Can not read persistence unit for {0} / {1} / {2} at {3}"; + assertReadable(persistenceUnit, msg, getType(), getSubType(), id, persistenceUnit); T object = read(persistenceUnit); return object; } @Override public void add(T object) { - XmlPersistencePathBuilder pathBuilder = this.fileDao.getPathBuilder(); - File addPath = pathBuilder.getAddPath(getType(), getSubType(), getId(object)); + + File addPath; + if (getSubType() == null) + addPath = this.fileDao.getAddPath(getType(), getId(object)); + else + addPath = this.fileDao.getAddPath(getType(), getSubType(), getId(object)); write(object, addPath); } @Override public void update(T object) { - XmlPersistencePathBuilder pathBuilder = this.fileDao.getPathBuilder(); - File updatePath = pathBuilder.getUpdatePath(getType(), getSubType(), getId(object)); - write(object, updatePath); + File addPath; + if (getSubType() == null) + addPath = this.fileDao.getUpdatePath(getType(), getId(object)); + else + addPath = this.fileDao.getUpdatePath(getType(), getSubType(), getId(object)); + write(object, addPath); } /** diff --git a/src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java b/src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java new file mode 100644 index 000000000..54959a342 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +/** + * @author Robert von Burg + * + */ +public class DomUtil { + + public static DocumentBuilder createDocumentBuilder() { + try { + DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); + return docBuilder; + } catch (ParserConfigurationException e) { + throw new XmlPersistenceException("No Xml Parser could be loaded: " + e.getMessage(), e); + } + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java similarity index 83% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java rename to src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java index fef67ed53..e0a89f617 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyTypeResourceDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java @@ -19,16 +19,13 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl; +package ch.eitchnet.xmlpers.api; /** * @author Robert von Burg * */ -public class MyTypeResourceDao extends ResourceDao { +public enum XmlIoMode { - @Override - public String getSubType() { - return "MyType"; - } + DOM, SAX; } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java index 050c9789a..3fd3266e4 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java @@ -27,7 +27,9 @@ package ch.eitchnet.xmlpers.api; */ public class XmlPersistenceConstants { - public static final String PROP_VERBOSE = "ch.eitchnet.xmlpers.verbose"; - public static final String PROP_BASEPATH = "ch.eitchnet.xmlpers.basepath"; - public static final String PROP_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers.daoFactoryClass"; + private static final String PROP_PREFIX = "ch.eitchnet.xmlpers."; + public static final String PROP_VERBOSE = "ch.eitchnet.xmlpers." + "verbose"; + public static final String PROP_BASEPATH = "ch.eitchnet.xmlpers." + "basePath"; + public static final String PROP_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers." + "daoFactoryClass"; + public static final String PROP_XML_IO_MOD = PROP_PREFIX + "ioMode"; } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java index e034d9c76..8923211fc 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java @@ -22,17 +22,11 @@ package ch.eitchnet.xmlpers.api; import java.util.List; import java.util.Set; -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; - /** * @author Robert von Burg */ public interface XmlPersistenceDao { - public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao); - - public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler); - public void add(T object); public void update(T object); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java index 76ac22cad..4b5ac1782 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java @@ -30,11 +30,11 @@ public interface XmlPersistenceDaoFactory { public void initialize(XmlPersistenceFileDao fileDao, Properties properties); - public XmlPersistenceMetadataDao getMetadataDao(); - + public XmlPersistenceMetadataDao getMetadataDao(); + public XmlPersistenceDao getDao(T object); - public XmlPersistenceDao getDao(String type); + public XmlPersistenceDao getDaoBy(String type); - public XmlPersistenceDao getDao(String type, String subType); + public XmlPersistenceDao getDaoBy(String type, String subType); } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java index 8a1106aa5..9f814a05a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java @@ -1,83 +1,31 @@ /* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers + * Copyright (c) 2012, Robert von Burg * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * All rights reserved. * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. + * This file is part of the XXX. * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . */ package ch.eitchnet.xmlpers.api; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.PropertiesHelper; -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; -import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; - /** * @author Robert von Burg * */ -public class XmlPersistenceHandler { +public interface XmlPersistenceHandler { - protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandler.class); - - protected boolean initialized; - protected boolean verbose; - protected XmlPersistenceDaoFactory daoFactory; - - public void initialize(Properties properties) { - if (this.initialized) - throw new IllegalStateException("Already initialized!"); - - // get properties - String context = XmlPersistenceHandler.class.getSimpleName(); - boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, - Boolean.FALSE).booleanValue(); - String daoFactoryClassName = PropertiesHelper.getProperty(properties, context, - XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, null); - - // load dao factory - XmlPersistenceDaoFactory daoFactory; - try { - @SuppressWarnings("unchecked") - Class xmlDaoFactoryClass = (Class) Class.forName(daoFactoryClassName); - - daoFactory = xmlDaoFactoryClass.newInstance(); - - } catch (ClassNotFoundException e) { - throw new XmlPersistenceException("XmlDaoFactory class does not exist " + daoFactoryClassName, e); - } catch (Exception e) { - throw new XmlPersistenceException("Failed to load class " + daoFactoryClassName, e); - } - - // initialize the dao factory - XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(properties); - XmlPersistenceFileDao fileDao = new XmlPersistenceFileDao(pathBuilder, properties); - daoFactory.initialize(fileDao, properties); - - this.daoFactory = daoFactory; - this.verbose = verbose; - } - - public XmlPersistenceTransaction openTx() { - - XmlPersistenceTransaction tx = new XmlPersistenceTransaction(this.daoFactory, this.verbose); - XmlPersistenceTransaction.setTx(tx); - return tx; - } -} + public abstract XmlPersistenceTransaction openTx(); +} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java index 36039f7dd..4f8e74b40 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java @@ -21,26 +21,22 @@ package ch.eitchnet.xmlpers.api; import java.util.Set; -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; - /** * @author Robert von Burg */ public interface XmlPersistenceMetadataDao { - public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao); + public Set queryTypeSet(); - public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler); - - public void removeAll(); - - public Set queryKeySet(); + public Set queryTypeSet(String type); public Set queryKeySet(String type); public Set queryKeySet(String type, String subType); - public long querySize(); + public long queryTypeSize(); + + public long querySubTypeSize(String type); public long querySize(String type); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java index 1e5e9151f..ae6545d15 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java @@ -1,267 +1,76 @@ /* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers + * Copyright (c) 2012, Robert von Burg * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. + * All rights reserved. * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. + * This file is part of the XXX. * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . */ package ch.eitchnet.xmlpers.api; import java.util.List; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.objectfilter.ObjectFilter; /** * @author Robert von Burg + * */ -public class XmlPersistenceTransaction { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTransaction.class); - - private static final ThreadLocal TX_THREADLOCAL_THREAD_LOCAL; - static { - TX_THREADLOCAL_THREAD_LOCAL = new ThreadLocal<>(); - } - - private final XmlPersistenceDaoFactory daoFactory; - private final boolean verbose; - private final ObjectFilter objectFilter; - - /** - * @param verbose - */ - public XmlPersistenceTransaction(XmlPersistenceDaoFactory daoFactory, boolean verbose) { - this.daoFactory = daoFactory; - this.verbose = verbose; - this.objectFilter = new ObjectFilter(); - } - - /* - * modifying methods - */ +public interface XmlPersistenceTransaction { /** * @param object */ - public void add(T object) { - this.objectFilter.add(object); - } + public abstract void add(T object); /** * @param objects */ - @SuppressWarnings("unchecked") - public void addAll(List objects) { - this.objectFilter.addAll((List) objects); - } + public abstract void addAll(List objects); /** * @param object */ - public void update(T object) { - this.objectFilter.update(object); - } + public abstract void update(T object); /** * @param objects */ - @SuppressWarnings("unchecked") - public void updateAll(List objects) { - this.objectFilter.updateAll((List) objects); - } + public abstract void updateAll(List objects); /** * @param object */ - public void remove(T object) { - this.objectFilter.remove(object); - } + public abstract void remove(T object); /** * @param objects */ - @SuppressWarnings("unchecked") - public void removeAll(List objects) { - this.objectFilter.removeAll((List) objects); - } - - /* - * querying methods - */ + public abstract void removeAll(List objects); /** - * @param type - * @return + * @return the daoFactory */ - public Set queryKeySet() { - return this.daoFactory.getMetadataDao().queryKeySet(); - } - - /** - * @param type - * @return - */ - public Set queryKeySet(String type) { - return this.daoFactory.getMetadataDao().queryKeySet(type); - } - - /** - * @param type - * @param subType - * @return - */ - public Set queryKeySet(String type, String subType) { - return this.daoFactory.getMetadataDao().queryKeySet(type, subType); - } - - /** - * @param type - * @return - */ - public long querySize(String type) { - return querySize(type, null); - } - - /** - * @param type - * @param subType - * @return - */ - public long querySize(String type, String subType) { - return this.daoFactory.getDao(type, subType).querySize(); - } - - /** - * @param type - * @return - */ - public List queryAll(String type) { - XmlPersistenceDao dao = this.daoFactory.getDao(type); - List objects = dao.queryAll(type); - return objects; - } - - /** - * @param type - * @param subType - * @return - */ - public List queryAll(String type, String subType) { - XmlPersistenceDao dao = this.daoFactory.getDao(type, subType); - List objects = dao.queryAll(type, subType); - return objects; - } - - /** - * @param type - * @param id - * @return - */ - public T queryById(String type, String id) { - return queryById(type, id); - } - - /** - * @param type - * @param subType - * @param id - * @return - */ - public T queryById(String type, String subType, String id) { - XmlPersistenceDao dao = this.daoFactory.getDao(type, subType); - T object = dao.queryById(id); - return object; - } + public abstract XmlPersistenceDaoFactory getDaoFactory(); /** * */ - public void commit() { + public abstract void commit(); - if (this.verbose) - XmlPersistenceTransaction.logger.info("Committing TX..."); - - Set keySet = this.objectFilter.keySet(); - if (keySet.isEmpty()) - return; - - for (String key : keySet) { - - List removed = this.objectFilter.getRemoved(key); - if (removed.isEmpty()) { - if (this.verbose) - XmlPersistenceTransaction.logger.info("No objects removed in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransaction.logger.info(removed.size() + " objects removed in this tx."); - - for (Object object : removed) { - XmlPersistenceDao dao = this.daoFactory.getDao(object); - dao.remove(object); - } - } - - List updated = this.objectFilter.getUpdated(key); - if (updated.isEmpty()) { - if (this.verbose) - XmlPersistenceTransaction.logger.info("No objects updated in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransaction.logger.info(updated.size() + " objects updated in this tx."); - - for (Object object : updated) { - - XmlPersistenceDao dao = this.daoFactory.getDao(object); - dao.update(object); - } - } - - List added = this.objectFilter.getAdded(key); - if (added.isEmpty()) { - if (this.verbose) - XmlPersistenceTransaction.logger.info("No objects added in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransaction.logger.info(added.size() + " objects added in this tx."); - - for (Object object : added) { - - XmlPersistenceDao dao = this.daoFactory.getDao(object); - dao.add(object); - } - } - } - - this.objectFilter.clearCache(); - XmlPersistenceTransaction.logger.info("Completed TX"); - } - - public static XmlPersistenceTransaction getTx() { - XmlPersistenceTransaction tx = TX_THREADLOCAL_THREAD_LOCAL.get(); - if (tx == null) - throw new IllegalStateException("No transaction is currently open!"); - return tx; - } - - public static void setTx(XmlPersistenceTransaction tx) { - if (TX_THREADLOCAL_THREAD_LOCAL.get() != null) - throw new IllegalStateException("A transaction is already open!"); - TX_THREADLOCAL_THREAD_LOCAL.set(tx); - } -} + /** + * + */ + public abstract void clear(); +} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java index 019a2ad71..80dbd6317 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java @@ -23,53 +23,39 @@ package ch.eitchnet.xmlpers.impl; import java.util.Set; -import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; /** * @author Robert von Burg * */ -public abstract class MetadataXmlDao implements XmlPersistenceMetadataDao { +public class MetadataXmlDao implements XmlPersistenceMetadataDao { private XmlPersistenceFileDao fileDao; - private XmlPersistenceFileHandler fileHandler; - // TODO think about setting some methods to final - // TODO maybe decouple the write and load method into their own class - - @Override - public void setXmlPersistenceFileDao(XmlPersistenceFileDao fileDao) { + public void initialize(XmlPersistenceFileDao fileDao) { + if (fileDao == null) + throw new IllegalArgumentException("fileDao may not be null!"); + if (this.fileDao != null) + throw new IllegalStateException("DAO is already initialized!"); this.fileDao = fileDao; } - @Override - public void setXmlPersistenceFileHandler(XmlPersistenceFileHandler fileHandler) { - this.fileHandler = fileHandler; - } - - /** - * @return the fileHandler - */ - protected XmlPersistenceFileHandler getFileHandler() { - return this.fileHandler; - } - /** * @return the fileDao */ protected XmlPersistenceFileDao getFileDao() { return this.fileDao; } - + @Override - public void removeAll() { - this.fileDao.removeAll(); + public Set queryTypeSet() { + return this.fileDao.queryTypeSet(); } @Override - public Set queryKeySet(String type, String subType) { - return this.fileDao.queryKeySet(type, subType); + public Set queryTypeSet(String type) { + return this.fileDao.queryTypeSet(type); } @Override @@ -78,13 +64,18 @@ public abstract class MetadataXmlDao implements XmlPersistenceMetadataDao { } @Override - public Set queryKeySet() { - return this.fileDao.queryKeySet(); + public Set queryKeySet(String type, String subType) { + return this.fileDao.queryKeySet(type, subType); } @Override - public long querySize(String type, String subType) { - return this.fileDao.querySize(type, subType); + public long queryTypeSize() { + return this.fileDao.queryTypeSize(); + } + + @Override + public long querySubTypeSize(String type) { + return this.fileDao.queryTypeSize(type); } @Override @@ -93,7 +84,7 @@ public abstract class MetadataXmlDao implements XmlPersistenceMetadataDao { } @Override - public long querySize() { - return this.fileDao.querySize(); + public long querySize(String type, String subType) { + return this.fileDao.querySize(type, subType); } } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java b/src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java new file mode 100644 index 000000000..3aa95a8ec --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import java.util.Properties; + +import ch.eitchnet.xmlpers.api.XmlPersistenceDao; +import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; + +/** + * @author Robert von Burg + * + */ +public class TransactionDaoFactoryFacade implements XmlPersistenceDaoFactory { + + private XmlPersistenceDaoFactory daoFactory; + private XmlPersistenceTransactionImpl tx; + + TransactionDaoFactoryFacade(XmlPersistenceDaoFactory daoFactory) { + this.daoFactory = daoFactory; + } + + void setTx(XmlPersistenceTransactionImpl tx) { + this.tx = tx; + } + + /** + * @throws UnsupportedOperationException + * as this method may not be called on the facade + */ + @Override + public void initialize(XmlPersistenceFileDao fileDao, Properties properties) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + /** + * @return + * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getMetadataDao() + */ + @Override + public XmlPersistenceMetadataDao getMetadataDao() { + assertTxOpen(); + return this.daoFactory.getMetadataDao(); + } + + /** + * @param object + * @return + * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getDao(java.lang.Object) + */ + @Override + public XmlPersistenceDao getDao(T object) { + assertTxOpen(); + return this.daoFactory.getDao(object); + } + + /** + * @param type + * @return + * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getDaoBy(java.lang.String) + */ + @Override + public XmlPersistenceDao getDaoBy(String type) { + assertTxOpen(); + return this.daoFactory.getDaoBy(type); + } + + /** + * @param type + * @param subType + * @return + * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getDaoBy(java.lang.String, java.lang.String) + */ + @Override + public XmlPersistenceDao getDaoBy(String type, String subType) { + assertTxOpen(); + return this.daoFactory.getDaoBy(type, subType); + } + + private void assertTxOpen() { + if (this.tx.isCleared()) { + throw new XmlPersistenceException( + "The transaction has already been closed, thus no operation may be performed anymore with this dao factory instance"); + } + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java index 102c7738a..30484e387 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java @@ -25,8 +25,6 @@ import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; @@ -43,6 +41,7 @@ import org.xml.sax.SAXException; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.XmlHelper; +import ch.eitchnet.xmlpers.api.DomUtil; import ch.eitchnet.xmlpers.api.XmlPersistenceContextData; import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; import ch.eitchnet.xmlpers.api.XmlPersistenceException; @@ -56,12 +55,6 @@ public class XmlPersistenceDomHandler implements XmlPersistenceFileHandler { private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceDomHandler.class); - public DocumentBuilder createDocumentBuilder() throws ParserConfigurationException { - DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); - DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); - return docBuilder; - } - @Override public void read(XmlPersistenceContextData contextData) { @@ -72,11 +65,11 @@ public class XmlPersistenceDomHandler implements XmlPersistenceFileHandler { throw new IllegalStateException("No file has been set on the context data!"); try { - DocumentBuilder docBuilder = createDocumentBuilder(); + DocumentBuilder docBuilder = DomUtil.createDocumentBuilder(); File file = cd.getFile(); Document document = docBuilder.parse(file); cd.setDocument(document); - } catch (ParserConfigurationException | SAXException | IOException e) { + } catch (SAXException | IOException e) { throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); } @@ -119,12 +112,11 @@ public class XmlPersistenceDomHandler implements XmlPersistenceFileHandler { // transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\t"); // Transform to file - File file = new File("target/res_dom.xml"); - StreamResult result = new StreamResult(file); + StreamResult result = new StreamResult(cd.getFile()); Source xmlSource = new DOMSource(document); transformer.transform(xmlSource, result); - logger.info("Wrote DOM to " + file.getAbsolutePath()); + logger.info("Wrote DOM to " + cd.getFile().getAbsolutePath()); } catch (TransformerFactoryConfigurationError | TransformerException e) { throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java index 4697d8e58..58ec57411 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java @@ -21,6 +21,7 @@ package ch.eitchnet.xmlpers.impl; import java.io.File; import java.text.MessageFormat; +import java.util.Collections; import java.util.HashSet; import java.util.Properties; import java.util.Set; @@ -28,7 +29,6 @@ import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import ch.eitchnet.utils.helper.FileHelper; import ch.eitchnet.utils.helper.PropertiesHelper; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.api.XmlPersistenceException; @@ -56,52 +56,98 @@ public class XmlPersistenceFileDao { } /** - * @return the pathBuilder + * Does a recursive and complete deletion of all objects, types and sub-types */ - public XmlPersistencePathBuilder getPathBuilder() { - return this.pathBuilder; - } - public void removeAll() { - File removePath = this.pathBuilder.getRemovePath(); - String failMsg = "Deletion of persistence units at {1} failed! Check file permissions!"; - remove(removePath, failMsg, removePath); + Set types = queryTypeSet(); + for (String type : types) { + + Set idsByType = queryKeySet(type); + for (String id : idsByType) { + remove(type, id); + } + + Set subTypes = queryTypeSet(type); + for (String subType : subTypes) { + + Set idsBySubType = queryKeySet(type, subType); + for (String id : idsBySubType) { + remove(type, subType, id); + } + } + } } - + public void removeAll(String type) { - File removePath = this.pathBuilder.getRemovePath(type); - String failMsg = "Deletion of persistence units for {0} at {1} failed! Check file permissions!"; - remove(removePath, failMsg, type, removePath); + Set idsByType = queryKeySet(type); + for (String id : idsByType) { + remove(type, id); + } + + Set subTypes = queryTypeSet(type); + for (String subType : subTypes) { + + Set idsBySubType = queryKeySet(type, subType); + for (String id : idsBySubType) { + remove(type, subType, id); + } + } } public void removeAll(String type, String subType) { - File removePath = this.pathBuilder.getRemovePath(type, subType); - String failMsg = "Deletion of persistence units for {0} / {1} at {2} failed! Check file permissions!"; - remove(removePath, failMsg, type, subType, removePath); + Set idsBySubType = queryKeySet(type, subType); + for (String id : idsBySubType) { + remove(type, subType, id); + } } public void remove(String type, String id) { File removePath = this.pathBuilder.getRemovePath(type, id); String failMsg = "Deletion of persistence units for {0} / {1} at {2} failed! Check file permissions!"; remove(removePath, failMsg, type, id, removePath); + + // if no more objects with this type exist, then delete the path + failMsg = "Deletion of empty directory for {0} at {2} failed! Check file permissions!"; + File parentFile = removePath.getParentFile(); + deleteEmptyDirectory(parentFile, failMsg, type, parentFile); } public void remove(String type, String subType, String id) { File removePath = this.pathBuilder.getRemovePath(type, subType, id); String failMsg = "Deletion of persistence units for {0} / {1} / {2} at {3} failed! Check file permissions!"; remove(removePath, failMsg, type, subType, id, removePath); + + // if no more objects with this subType exist, then delete the path + failMsg = "Deletion of empty directory for {0} / {1} at {2} failed! Check file permissions!"; + File parentFile = removePath.getParentFile(); + deleteEmptyDirectory(parentFile, failMsg, type, subType, parentFile); } - private void remove(File removePath, String failMsg, Object... msgParts) { - File[] removePaths = new File[] { removePath }; - boolean removed = FileHelper.deleteFiles(removePaths, this.verbose); - if (!removed) { - String msg = MessageFormat.format(failMsg, msgParts); - throw new XmlPersistenceException(msg); - } + public File getAddPath(String type, String id) { + return this.pathBuilder.getAddPath(type, id); + } + + public File getAddPath(String type, String subType, String id) { + return this.pathBuilder.getAddPath(type, subType, id); + } + + public File getReadPath(String type, String id) { + return this.pathBuilder.getReadPath(type, id); + } + + public File getReadPath(String type, String subType, String id) { + return this.pathBuilder.getReadPath(type, subType, id); + } + + public File getUpdatePath(String type, String id) { + return this.pathBuilder.getUpdatePath(type, id); + } + + public File getUpdatePath(String type, String subType, String id) { + return this.pathBuilder.getUpdatePath(type, subType, id); } /** @@ -109,9 +155,9 @@ public class XmlPersistenceFileDao { * * @return */ - public Set queryKeySet() { + public Set queryTypeSet() { File queryPath = this.pathBuilder.getQueryPath(); - Set keySet = queryKeySet(queryPath); + Set keySet = queryTypeSet(queryPath); if (this.verbose) XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " types"); return keySet; @@ -120,6 +166,19 @@ public class XmlPersistenceFileDao { /** * Returns the set of sub types for the given type * + * @return + */ + public Set queryTypeSet(String type) { + File queryPath = this.pathBuilder.getQueryPath(type); + Set keySet = queryTypeSet(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " subTypes of type " + type); + return keySet; + } + + /** + * Returns the object ids for the given type + * * @param type * * @return @@ -133,7 +192,7 @@ public class XmlPersistenceFileDao { } /** - * Returns the set of ids for the objects with the give type and sub type + * Returns the object ids for the give type and sub type * * @param type * @param subType @@ -148,30 +207,22 @@ public class XmlPersistenceFileDao { return keySet; } - /** - * @param queryPath - * @return - */ - private Set queryKeySet(File queryPath) { - Set keySet = new HashSet(); - - File[] subTypeFiles = queryPath.listFiles(); - for (File subTypeFile : subTypeFiles) { - if (subTypeFile.isFile()) - keySet.add(this.pathBuilder.getId(subTypeFile.getName())); - } - - return keySet; - } - - public long querySize() { + public long queryTypeSize() { File queryPath = this.pathBuilder.getQueryPath(); - long numberOfFiles = querySize(queryPath); + long numberOfFiles = queryTypeSize(queryPath); if (this.verbose) XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " types"); return numberOfFiles; } + public long queryTypeSize(String type) { + File queryPath = this.pathBuilder.getQueryPath(type); + long numberOfFiles = queryTypeSize(queryPath); + if (this.verbose) + XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " elements for " + type); + return numberOfFiles; + } + public long querySize(String type) { File queryPath = this.pathBuilder.getQueryPath(type); long numberOfFiles = querySize(queryPath); @@ -188,7 +239,99 @@ public class XmlPersistenceFileDao { return numberOfFiles; } + /** + * Returns the types, i.e. directories in the given query path + * + * @param queryPath + * the path for which the types should be gathered + * + * @return a set of types in the given query path + */ + private Set queryTypeSet(File queryPath) { + Set keySet = new HashSet(); + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + if (subTypeFile.isFile()) { + String filename = subTypeFile.getName(); + String id = this.pathBuilder.getId(filename); + keySet.add(id); + } + } + + return keySet; + } + + /** + * Returns the ids of all objects in the given query path, i.e. the id part of all the files in the given query path + * + * @param queryPath + * the path for which the ids should be gathered + * + * @return a set of ids for the objects in the given query path + */ + private Set queryKeySet(File queryPath) { + if (!queryPath.exists()) + return Collections.emptySet(); + if (!queryPath.isDirectory()) + throw new IllegalArgumentException("The path is not a directory, thus can not query key set for it: " + + queryPath.getAbsolutePath()); + + Set keySet = new HashSet(); + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + if (subTypeFile.isFile()) { + String filename = subTypeFile.getName(); + String id = this.pathBuilder.getId(filename); + keySet.add(id); + } + } + + return keySet; + } + + /** + * Returns the number of all types, i.e. directories in the given query path + * + * @param queryPath + * the path in which to count the types + * + * @return the number of types in the given query path + */ + private long queryTypeSize(File queryPath) { + if (!queryPath.exists()) + return 0L; + if (!queryPath.isDirectory()) + throw new IllegalArgumentException("The path is not a directory, thus can not query type size for it: " + + queryPath.getAbsolutePath()); + + long numberOfFiles = 0l; + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isDirectory()) + numberOfFiles++; + } + return numberOfFiles; + } + + /** + * Returns the number of all objects in the given query path + * + * @param queryPath + * the path in which to count the objects + * + * @return the number of objects in the given query path + */ private long querySize(File queryPath) { + if (!queryPath.exists()) + return 0L; + if (!queryPath.isDirectory()) + throw new IllegalArgumentException("The path is not a directory, thus can not query key size for it: " + + queryPath.getAbsolutePath()); + long numberOfFiles = 0l; File[] subTypeFiles = queryPath.listFiles(); @@ -199,4 +342,30 @@ public class XmlPersistenceFileDao { } return numberOfFiles; } + + private void remove(File removePath, String failMsg, Object... msgParts) { + if (!removePath.isFile()) + throw new IllegalArgumentException("The given path for deletion is not a file:" + + removePath.getAbsolutePath()); + if (!removePath.delete()) { + String msg = MessageFormat.format(failMsg, msgParts); + throw new XmlPersistenceException(msg); + } + } + + private void deleteEmptyDirectory(File directoryPath, String failMsg, Object... msgArgs) { + if (!directoryPath.isDirectory()) + throw new IllegalArgumentException("The given path for deletion when empty is not a directory:" + + directoryPath.getAbsolutePath()); + if (directoryPath.list().length == 0) { + if (this.verbose) { + String msg = "Deleting empty directory for type {0} at {1}"; + logger.info(MessageFormat.format(msg, directoryPath.getName(), directoryPath)); + } + if (!directoryPath.delete()) { + String msg = MessageFormat.format(failMsg, msgArgs); + throw new XmlPersistenceException(msg); + } + } + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java new file mode 100644 index 000000000..98790ba01 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.impl; + +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.api.XmlPersistenceHandler; +import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceHandlerImpl implements XmlPersistenceHandler { + + protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandlerImpl.class); + + protected boolean initialized; + protected boolean verbose; + protected XmlPersistenceDaoFactory daoFactory; + + public void initialize(Properties properties) { + if (this.initialized) + throw new IllegalStateException("Already initialized!"); + + // get properties + String context = XmlPersistenceHandlerImpl.class.getSimpleName(); + boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, + Boolean.FALSE).booleanValue(); + String daoFactoryClassName = PropertiesHelper.getProperty(properties, context, + XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, null); + + // load dao factory + XmlPersistenceDaoFactory daoFactory; + try { + @SuppressWarnings("unchecked") + Class xmlDaoFactoryClass = (Class) Class + .forName(daoFactoryClassName); + + daoFactory = xmlDaoFactoryClass.newInstance(); + + } catch (ClassNotFoundException e) { + throw new XmlPersistenceException("XmlDaoFactory class does not exist " + daoFactoryClassName, e); + } catch (Exception e) { + throw new XmlPersistenceException("Failed to load class " + daoFactoryClassName, e); + } + + // initialize the dao factory + XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(properties); + XmlPersistenceFileDao fileDao = new XmlPersistenceFileDao(pathBuilder, properties); + daoFactory.initialize(fileDao, properties); + + this.daoFactory = daoFactory; + this.verbose = verbose; + } + + @Override + public XmlPersistenceTransaction openTx() { + + TransactionDaoFactoryFacade daoFactoryFacade = new TransactionDaoFactoryFacade(this.daoFactory); + XmlPersistenceTransactionImpl tx = new XmlPersistenceTransactionImpl(daoFactoryFacade, this.verbose); + daoFactoryFacade.setTx(tx); + XmlPersistenceTransactionImpl.setTx(tx); + return tx; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java index 952669c7a..4c0b3c9af 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java @@ -56,25 +56,26 @@ public class XmlPersistencePathBuilder { // validate base path exists and is writable File basePathF = new File(basePath); if (!basePathF.exists()) - throw new XmlPersistenceException("The database store path does not exist at " - + basePathF.getAbsolutePath()); + throw new XmlPersistenceException(MessageFormat.format("The database store path does not exist at {0}", + basePathF.getAbsolutePath())); if (!basePathF.canWrite()) - throw new XmlPersistenceException("The database store path is not writeable at " - + basePathF.getAbsolutePath()); + throw new XmlPersistenceException(MessageFormat.format("The database store path is not writeable at {0}", + basePathF.getAbsolutePath())); // we want a clean base path String canonicalBasePath; try { canonicalBasePath = basePathF.getCanonicalPath(); } catch (IOException e) { - throw new XmlPersistenceException("Failed to build canonical path from " + basePath, e); + throw new XmlPersistenceException( + MessageFormat.format("Failed to build canonical path from {0}", basePath), e); } // this.basePathF = basePathF; this.basePath = canonicalBasePath; this.verbose = verbose; - logger.info("Using base path " + basePath); + logger.info(MessageFormat.format("Using base path {0}", basePath)); } String getFilename(String id) { @@ -105,26 +106,21 @@ public class XmlPersistencePathBuilder { return sb.toString(); } - File getPath() { - return new File(getPathAsString(null, null, null)); - } - - File getPath(String type) { + File getAddPath(String type, String id) { assertType(type); - return new File(getPathAsString(type, null, null)); - } - - File getPath(String type, String subType) { - assertType(type); - assertSubType(subType); - return new File(getPathAsString(type, subType, null)); - } - - File getPath(String type, String subType, String id) { - assertType(type); - assertSubType(subType); assertId(id); - return new File(getPathAsString(type, subType, id)); + + File path = new File(getPathAsString(type, null, id)); + + // assert path exists + String msg = "Persistence unit already exists for {0} / {1} at {2}"; + assertPathNotExists(path, msg, type, id, path.getAbsolutePath()); + + // check if parent path exists + msg = "Could not create parent path for {0} / {1} at {2}"; + createMissingParents(path, msg, type, id, path.getAbsolutePath()); + + return path; } File getAddPath(String type, String subType, String id) { @@ -132,20 +128,51 @@ public class XmlPersistencePathBuilder { assertSubType(subType); assertId(id); - File path = getPath(type, subType, id); + File path = new File(getPathAsString(type, subType, id)); - if (path.exists()) { - String msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; - throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } + // assert path exists + String msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; + assertPathNotExists(path, msg, type, subType, id, path.getAbsolutePath()); // check if parent path exists + msg = "Could not create parent path for {0} / {1} / {2} at {3}"; + createMissingParents(path, msg, type, subType, id, path.getAbsolutePath()); + + return path; + } + + File getReadPath(String type, String id) { + assertType(type); + assertId(id); + File path = new File(getPathAsString(type, null, id)); + if (this.verbose) { + String msg = "Query path for {0} / {1} is {2}..."; + logger.info(MessageFormat.format(msg, type, id, path.getAbsolutePath())); + } + return path; + } + + File getReadPath(String type, String subType, String id) { + assertType(type); + assertSubType(subType); + assertId(id); + File path = new File(getPathAsString(type, subType, id)); + if (this.verbose) { + String msg = "Query path for {0} / {1} / {2} is {3}..."; + logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); + } + return path; + } + + File getUpdatePath(String type, String id) { + assertType(type); + assertId(id); + + File path = new File(getPathAsString(type, null, id)); + if (!path.exists()) { - File parentFile = path.getParentFile(); - if (!parentFile.exists() && !parentFile.mkdirs()) { - String msg = "Could not create parent path for {0} / {1} / {2} at {3}"; - throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } + String msg = "Persistence unit does not exist for {0} / {1} at {2}"; + throw new XmlPersistenceException(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } return path; @@ -156,7 +183,7 @@ public class XmlPersistencePathBuilder { assertSubType(subType); assertId(id); - File path = getPath(type, subType, id); + File path = new File(getPathAsString(type, subType, id)); if (!path.exists()) { String msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; @@ -166,52 +193,19 @@ public class XmlPersistencePathBuilder { return path; } - File getRemovePath() { - - File path = getPath(); - if (!path.exists()) { - String msg = "No Persistence units exist at {0}"; - throw new XmlPersistenceException(MessageFormat.format(msg, path.getAbsolutePath())); - } - - if (this.verbose) { - String msg = "Remove path for all is {0}..."; - logger.info(MessageFormat.format(msg, path.getAbsolutePath())); - } - - return path; - } - - File getRemovePath(String type) { + File getRemovePath(String type, String id) { assertType(type); + assertId(id); - File path = getPath(type); - if (!path.exists()) { - String msg = "No Persistence units exist for {0} at {1}"; - throw new XmlPersistenceException(MessageFormat.format(msg, type, path.getAbsolutePath())); - } - - if (this.verbose) { - String msg = "Remove path for {0} is {1}..."; - logger.info(MessageFormat.format(msg, type, path.getAbsolutePath())); - } - - return path; - } - - File getRemovePath(String type, String subType) { - assertType(type); - assertSubType(subType); - - File path = getPath(type, subType); + File path = new File(getPathAsString(type, null, id)); if (!path.exists()) { String msg = "No Persistence units exist for {0} / {1} at {2}"; - throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); + throw new XmlPersistenceException(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } if (this.verbose) { String msg = "Remove path for {0} / {1} is {2}..."; - logger.info(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); + logger.info(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } return path; @@ -222,7 +216,7 @@ public class XmlPersistencePathBuilder { assertSubType(subType); assertId(id); - File path = getPath(type, subType, id); + File path = new File(getPathAsString(type, subType, id)); if (!path.exists()) { String msg = "Persistence unit for {0} / {1} / {2} does not exist at {3}"; throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); @@ -237,12 +231,12 @@ public class XmlPersistencePathBuilder { } File getQueryPath() { - return getPath(); + return new File(getPathAsString(null, null, null)); } File getQueryPath(String type) { assertType(type); - File path = getPath(type); + File path = new File(getPathAsString(type, null, null)); if (this.verbose) { String msg = "Query path for {0} is {1}..."; logger.info(MessageFormat.format(msg, type, path.getAbsolutePath())); @@ -253,7 +247,7 @@ public class XmlPersistencePathBuilder { File getQueryPath(String type, String subType) { assertType(type); assertSubType(subType); - File path = getPath(type, subType); + File path = new File(getPathAsString(type, subType, null)); if (this.verbose) { String msg = "Query path for {0} / {1} is {2}..."; logger.info(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); @@ -261,18 +255,6 @@ public class XmlPersistencePathBuilder { return path; } - File getQueryPath(String type, String subType, String id) { - assertType(type); - assertSubType(subType); - assertId(id); - File path = getPath(type, subType, id); - if (this.verbose) { - String msg = "Query path for {0} / {1} / {2} is {3}..."; - logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } - return path; - } - private void assertId(String id) { if (StringHelper.isEmpty(id)) throw new XmlPersistenceException( @@ -295,4 +277,17 @@ public class XmlPersistencePathBuilder { throw new XmlPersistenceException("The filename does not have a . at index " + (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); } + + private void assertPathNotExists(File path, String msg, Object... args) { + if (path.exists()) { + throw new XmlPersistenceException(MessageFormat.format(msg, args)); + } + } + + private void createMissingParents(File path, String msg, Object... args) { + File parentFile = path.getParentFile(); + if (!parentFile.exists() && !parentFile.mkdirs()) { + throw new XmlPersistenceException(MessageFormat.format(msg, args)); + } + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java similarity index 93% rename from src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java rename to src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java index f9029ac60..52c5ef0cf 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxHandler.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.api; +package ch.eitchnet.xmlpers.impl; import java.io.File; import java.io.FileWriter; @@ -41,7 +41,10 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.api.XmlPersistenceContextData; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; +import ch.eitchnet.xmlpers.api.XmlPersistenceSaxContextData; /** * @author Robert von Burg diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java new file mode 100644 index 000000000..a8cdbb7ac --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.impl; + +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.objectfilter.ObjectFilter; +import ch.eitchnet.xmlpers.api.XmlPersistenceDao; +import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; +import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; + +/** + * @author Robert von Burg + */ +public class XmlPersistenceTransactionImpl implements XmlPersistenceTransaction { + + private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTransactionImpl.class); + + private static final ThreadLocal TX_THREADLOCAL_THREAD_LOCAL; + static { + TX_THREADLOCAL_THREAD_LOCAL = new ThreadLocal<>(); + } + + private XmlPersistenceDaoFactory daoFactory; + private ObjectFilter objectFilter; + private boolean verbose; + private boolean cleared; + + /** + * @param verbose + */ + public XmlPersistenceTransactionImpl(XmlPersistenceDaoFactory daoFactory, boolean verbose) { + this.daoFactory = daoFactory; + this.verbose = verbose; + this.objectFilter = new ObjectFilter(); + } + + /* + * modifying methods + */ + + /** + * @param object + */ + @Override + public void add(T object) { + this.objectFilter.add(object); + } + + /** + * @param objects + */ + @Override + @SuppressWarnings("unchecked") + public void addAll(List objects) { + this.objectFilter.addAll((List) objects); + } + + /** + * @param object + */ + @Override + public void update(T object) { + this.objectFilter.update(object); + } + + /** + * @param objects + */ + @Override + @SuppressWarnings("unchecked") + public void updateAll(List objects) { + this.objectFilter.updateAll((List) objects); + } + + /** + * @param object + */ + @Override + public void remove(T object) { + this.objectFilter.remove(object); + } + + /** + * @param objects + */ + @Override + @SuppressWarnings("unchecked") + public void removeAll(List objects) { + this.objectFilter.removeAll((List) objects); + } + + /** + * @return the daoFactory + */ + @Override + public XmlPersistenceDaoFactory getDaoFactory() { + return this.daoFactory; + } + + /** + * + */ + @Override + public void commit() { + + try { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info("Committing TX..."); + Set keySet = this.objectFilter.keySet(); + if (keySet.isEmpty()) + return; + for (String key : keySet) { + + List removed = this.objectFilter.getRemoved(key); + if (removed.isEmpty()) { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info("No objects removed in this tx."); + } else { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info(removed.size() + " objects removed in this tx."); + + for (Object object : removed) { + XmlPersistenceDao dao = this.daoFactory.getDao(object); + dao.remove(object); + } + } + + List updated = this.objectFilter.getUpdated(key); + if (updated.isEmpty()) { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info("No objects updated in this tx."); + } else { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info(updated.size() + " objects updated in this tx."); + + for (Object object : updated) { + + XmlPersistenceDao dao = this.daoFactory.getDao(object); + dao.update(object); + } + } + + List added = this.objectFilter.getAdded(key); + if (added.isEmpty()) { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info("No objects added in this tx."); + } else { + if (this.verbose) + XmlPersistenceTransactionImpl.logger.info(added.size() + " objects added in this tx."); + + for (Object object : added) { + + XmlPersistenceDao dao = this.daoFactory.getDao(object); + dao.add(object); + } + } + } + + XmlPersistenceTransactionImpl.logger.info("Completed TX"); + + } finally { + // clean up + clear(); + } + } + + /** + * Clears the object filter and releases the transaction. After calling this method, this transaction instance can + * not be used anymore + */ + @Override + public void clear() { + if (!this.cleared) { + this.objectFilter.clearCache(); + this.objectFilter = null; + + this.daoFactory = null; + TX_THREADLOCAL_THREAD_LOCAL.set(null); + this.cleared = true; + } + } + + /** + * @return + */ + public boolean isCleared() { + return this.cleared; + } + + public static XmlPersistenceTransaction getTx() { + XmlPersistenceTransaction tx = TX_THREADLOCAL_THREAD_LOCAL.get(); + if (tx == null) + throw new IllegalStateException("No transaction is currently open!"); + return tx; + } + + public static void setTx(XmlPersistenceTransactionImpl tx) { + if (TX_THREADLOCAL_THREAD_LOCAL.get() != null) + throw new IllegalStateException("A transaction is already open!"); + TX_THREADLOCAL_THREAD_LOCAL.set(tx); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java new file mode 100644 index 000000000..706c40441 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java @@ -0,0 +1,434 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.test; + +import java.io.File; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceDao; +import ch.eitchnet.xmlpers.api.XmlPersistenceHandler; +import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; +import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; +import ch.eitchnet.xmlpers.impl.XmlPersistenceHandlerImpl; +import ch.eitchnet.xmlpers.test.impl.Book; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Parameter; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + */ +public abstract class AbstractXmlPersistenceTest { + + protected static final Logger logger = LoggerFactory.getLogger(AbstractXmlPersistenceTest.class.getName()); + + protected static final String RES_TYPE = "@subType"; + protected static final String RES_TYPE_INEXISTANT = "@inexistant"; + protected static final String RES_NAME = "@name"; + protected static final String RES_NAME_MODIFIED = "@name_modified"; + protected static final String RES_ID = "@id"; + + protected static final String PARAM_TYPE = "@paramType"; + protected static final String PARAM_NAME = "@paramName"; + protected static final String PARAM_ID = "@paramId"; + protected static final String PARAM_VALUE_1 = "@paramValue1"; + protected static final String PARAM_VALUE_2 = "@paramValue2"; + + protected static final long BOOK_ID = 10L; + protected static final String BOOK_TITLE = "Nick Hornby"; + protected static final String BOOK_AUTHOR = "A long way down"; + protected static final String BOOK_PRESS_1 = "Some press"; + protected static final String BOOK_PRESS_2 = "Another press"; + protected static final double BOOK_PRICE = 45.55D; + + protected static XmlPersistenceHandler persistenceHandler; + + protected XmlPersistenceTransaction tx; + + /** + * @throws Exception + * if something goes wrong + */ + public static void init(Properties props) throws Exception { + try { + String userDir = System.getProperty("user.dir"); + String basePath = userDir + "/target/testdb"; + File basePathF = new File(basePath); + if (!basePathF.exists() && !basePathF.mkdirs()) + Assert.fail("Could not create temporaray database store in " + basePathF.getAbsolutePath()); + + AbstractXmlPersistenceTest.persistenceHandler = new XmlPersistenceHandlerImpl(); + ((XmlPersistenceHandlerImpl) AbstractXmlPersistenceTest.persistenceHandler).initialize(props); + AbstractXmlPersistenceTest.logger.info("Initialized persistence handler."); + + } catch (Exception e) { + AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); + + throw new RuntimeException("Initialization failed: " + e.getLocalizedMessage(), e); + } + } + + @AfterClass + public static void afterClass() { + String userDir = System.getProperty("user.dir"); + String basePath = userDir + "/target/testdb"; + File basePathF = new File(basePath); + if (basePathF.exists() && !FileHelper.deleteFile(basePathF, true)) + Assert.fail("Could not delete temporaray database store at " + basePathF.getAbsolutePath()); + } + + @After + public void tearDown() { + if (this.tx != null) + this.tx.clear(); + } + + /** + * Tests the following story: + *
    + *
  • create book
  • + *
  • read book
  • + *
  • update book
  • + *
  • remove book
  • + *
+ */ + @Test + public void testBookPersistence() { + + // create + Book book = createBook(); + assertBook(book); + this.tx = persistenceHandler.openTx(); + this.tx.add(book); + this.tx.commit(); + + // read + this.tx = persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDao(book); + Book persistedBook = dao.queryById(String.valueOf(BOOK_ID)); + assertBook(persistedBook); + + // update + persistedBook.setPress(BOOK_PRESS_2); + this.tx.update(persistedBook); + this.tx.commit(); + + // read + this.tx = persistenceHandler.openTx(); + dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_BOOK); + persistedBook = dao.queryById(String.valueOf(BOOK_ID)); + assertBookUpdated(persistedBook); + + // delete + this.tx.remove(book); + this.tx.commit(); + + // fail to read + this.tx = persistenceHandler.openTx(); + dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_BOOK); + persistedBook = dao.queryById(String.valueOf(BOOK_ID)); + Assert.assertNull(persistedBook); + } + + /** + * Tests the following story: + *
    + *
  • create resource
  • + *
  • read resource
  • + *
  • update resource
  • + *
  • remove resource
  • + *
+ */ + @Test + public void testResourcePersistence() { + + persistResource(); + readResource(); + updateResource(); + removeResource(); + } + + private void persistResource() { + + try { + AbstractXmlPersistenceTest.logger.info("Trying to create..."); + + // new instance + Resource resource = createResource(); + assertResource(resource); + + // persist instance + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + this.tx.add(resource); + this.tx.commit(); + + AbstractXmlPersistenceTest.logger.info("Done creating."); + + } catch (Exception e) { + AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); + Assert.fail("Failed by exception: " + e.getLocalizedMessage()); + } + } + + private void readResource() { + + try { + AbstractXmlPersistenceTest.logger.info("Trying to read..."); + + // query Resource + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + Resource resource = dao.queryById(RES_ID); + AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); + assertResource(resource); + this.tx.commit(); + + AbstractXmlPersistenceTest.logger.info("Done reading."); + + } catch (Exception e) { + AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); + Assert.fail("Failed by exception: " + e.getLocalizedMessage()); + } + } + + private void updateResource() { + + try { + AbstractXmlPersistenceTest.logger.info("Trying to update an object..."); + + // query the instance + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + Resource resource = dao.queryById(RES_ID); + AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); + assertResource(resource); + + // modify the instance + resource.setName(RES_NAME_MODIFIED); + resource.getParameterBy(PARAM_ID).setValue(PARAM_VALUE_2); + + // update the instance + this.tx.update(resource); + this.tx.commit(); + + // re-read and validate + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + resource = dao.queryById(RES_ID); + this.tx.commit(); + AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); + assertResourceUpdated(resource); + + AbstractXmlPersistenceTest.logger.info("Done updating."); + + } catch (Exception e) { + AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); + Assert.fail("Failed by exception: " + e.getLocalizedMessage()); + } + } + + private void removeResource() { + + AbstractXmlPersistenceTest.logger.info("Trying to remove..."); + + // query the instance + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + Resource resource = dao.queryById(RES_ID); + AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); + assertResourceUpdated(resource); + + this.tx.remove(resource); + this.tx.commit(); + + AbstractXmlPersistenceTest.logger.info("Done removing."); + } + + @Test + public void testQueryFail() { + + AbstractXmlPersistenceTest.logger.info("Trying to query removed object..."); + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + Resource resource = dao.queryById(RES_ID); + this.tx.commit(); + Assert.assertNull("Expected resource not to be found!", resource); + } + + @Test + public void testReCreate() { + + try { + AbstractXmlPersistenceTest.logger.info("Trying to recreate..."); + + Resource resource = createResource(); + assertResource(resource); + + // persist instance + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + this.tx.add(resource); + this.tx.commit(); + + AbstractXmlPersistenceTest.logger.info("Done creating."); + + } catch (Exception e) { + AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); + Assert.fail("Failed by exception: " + e.getLocalizedMessage()); + } + } + + @Test + @Ignore + public void testQueryFromTo() { + Assert.fail("Not yet implemented"); + } + + @Test + public void testQueryAll() { + + AbstractXmlPersistenceTest.logger.info("Trying to query all..."); + + // query all + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + List list = dao.queryAll(); + Assert.assertEquals("Expected only one object, found " + list, 1, list.size()); + + // and now something useless + dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE_INEXISTANT); + list = dao.queryAll(); + this.tx.commit(); + Assert.assertEquals("Expected no objects, found " + list, 0, list.size()); + + AbstractXmlPersistenceTest.logger.info("Done querying."); + } + + @Test + public void testKeySet() { + + // first prepare by creating a resource + createResource(); + + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceMetadataDao metadataDao = this.tx.getDaoFactory().getMetadataDao(); + + // query by type only, which should return nothing on this level + Set keySet = metadataDao.queryKeySet(TestConstants.TYPE_RES); + Assert.assertEquals("A resource can only be queried by type/subtype, but dao returned values!", 0, + keySet.size()); + + // now we shoud find our resource with the given type + keySet = metadataDao.queryKeySet(TestConstants.TYPE_RES, RES_TYPE); + Assert.assertEquals("Expected one key, found " + keySet, 1, keySet.size()); + + // and now something useless + keySet = metadataDao.queryKeySet(TestConstants.TYPE_RES, RES_TYPE_INEXISTANT); + Assert.assertEquals("Expected no keys, found " + keySet, 0, keySet.size()); + + this.tx.commit(); + } + + @Test + public void testRemoveAll() { + + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); + List objects = dao.queryAll(); + this.tx.removeAll(objects); + this.tx.commit(); + } + + @Test + public void testSize() { + + this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); + XmlPersistenceMetadataDao metadataDao = this.tx.getDaoFactory().getMetadataDao(); + long size = metadataDao.querySize(TestConstants.TYPE_RES, RES_TYPE); + this.tx.commit(); + Assert.assertEquals("Expected size = 0, found: " + size, 0, size); + } + + private Book createBook() { + Book book = new Book(BOOK_ID, BOOK_TITLE, BOOK_AUTHOR, BOOK_PRESS_1, BOOK_PRICE); + return book; + } + + private void assertBook(Book book) { + Assert.assertNotNull(book); + Assert.assertEquals(BOOK_ID, book.getId().longValue()); + Assert.assertEquals(BOOK_TITLE, book.getTitle()); + Assert.assertEquals(BOOK_AUTHOR, book.getAuthor()); + Assert.assertEquals(BOOK_PRESS_1, book.getPress()); + Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); + } + + private void assertBookUpdated(Book book) { + Assert.assertNotNull(book); + Assert.assertEquals(BOOK_ID, book.getId().longValue()); + Assert.assertEquals(BOOK_TITLE, book.getTitle()); + Assert.assertEquals(BOOK_AUTHOR, book.getAuthor()); + Assert.assertEquals(BOOK_PRESS_2, book.getPress()); + Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); + } + + private Resource createResource() { + Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); + Parameter param = new Parameter(PARAM_ID, PARAM_NAME, PARAM_TYPE, PARAM_VALUE_1); + resource.addParameter(param); + return resource; + } + + private void assertResource(Resource resource) { + Assert.assertNotNull(resource); + Assert.assertEquals(RES_ID, resource.getId()); + Assert.assertEquals(RES_NAME, resource.getName()); + Assert.assertEquals(RES_TYPE, resource.getType()); + Parameter param = resource.getParameterBy(PARAM_ID); + Assert.assertNotNull(param); + Assert.assertEquals(PARAM_ID, param.getId()); + Assert.assertEquals(PARAM_NAME, param.getName()); + Assert.assertEquals(PARAM_TYPE, param.getType()); + Assert.assertEquals(PARAM_VALUE_1, param.getValue()); + } + + private void assertResourceUpdated(Resource resource) { + Assert.assertNotNull(resource); + Assert.assertEquals(RES_ID, resource.getId()); + Assert.assertEquals(RES_NAME_MODIFIED, resource.getName()); + Assert.assertEquals(RES_TYPE, resource.getType()); + Parameter param = resource.getParameterBy(PARAM_ID); + Assert.assertNotNull(param); + Assert.assertEquals(PARAM_ID, param.getId()); + Assert.assertEquals(PARAM_NAME, param.getName()); + Assert.assertEquals(PARAM_TYPE, param.getType()); + Assert.assertEquals(PARAM_VALUE_2, param.getValue()); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java new file mode 100644 index 000000000..35448c2c0 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.test; + +import java.util.Properties; + +import org.junit.BeforeClass; +import org.junit.Ignore; + +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; + +/** + * @author Robert von Burg + */ +@Ignore +public class XmlPersistenceDomTest extends AbstractXmlPersistenceTest { + + /** + * @throws Exception + * if something goes wrong + */ + @BeforeClass + public static void init() throws Exception { + + Properties props = new Properties(); + props.setProperty(XmlPersistenceConstants.PROP_BASEPATH, "target/testdb"); + props.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); + props.setProperty(XmlPersistenceConstants.PROP_XML_IO_MOD, "dom"); + props.setProperty(XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, TestModelDaoFactory.class.getName()); + + init(props); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java new file mode 100644 index 000000000..fba8c2eb2 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.test; + +import java.util.Properties; + +import org.junit.BeforeClass; + +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; + +/** + * @author Robert von Burg + */ +public class XmlPersistenceSaxTest extends AbstractXmlPersistenceTest { + + /** + * @throws Exception + * if something goes wrong + */ + @BeforeClass + public static void init() throws Exception { + + Properties props = new Properties(); + props.setProperty(XmlPersistenceConstants.PROP_BASEPATH, "target/testdb"); + props.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); + props.setProperty(XmlPersistenceConstants.PROP_XML_IO_MOD, "sax"); + props.setProperty(XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, TestModelDaoFactory.class.getName()); + + init(props); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java deleted file mode 100644 index 7e6eb3048..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceTest.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test; - -import java.io.File; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.api.XmlPersistenceHandler; -import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; -import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceTest { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTest.class.getName()); - - private static final String RES_TYPE = "@subType"; - private static final String RES_TYPE_INEXISTANT = "@inexistant"; - private static final String RES_NAME = "@name"; - private static final String RES_NAME_MODIFIED = "@name_modified"; - private static final String RES_ID = "@id"; - - private static XmlPersistenceHandler persistenceHandler; - - /** - * @throws Exception - * if something goes wrong - */ - @BeforeClass - public static void init() throws Exception { - try { - String userDir = System.getProperty("user.dir"); - String basePath = userDir + "/target/testdb"; - File basePathF = new File(basePath); - if (!basePathF.exists() && !basePathF.mkdirs()) - Assert.fail("Could not create temporaray database store in " + basePathF.getAbsolutePath()); - - Properties props = new Properties(); - props.setProperty(XmlPersistenceConstants.PROP_BASEPATH, "target/testdb"); - props.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); - props.setProperty(XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, TestModelDaoFactory.class.getName()); - - XmlPersistenceTest.persistenceHandler = new XmlPersistenceHandler(); - XmlPersistenceTest.persistenceHandler.initialize(props); - XmlPersistenceTest.logger.info("Initialized persistence handler."); - - } catch (Exception e) { - XmlPersistenceTest.logger.error(e.getMessage(), e); - - throw new RuntimeException("Initialization failed: " + e.getLocalizedMessage(), e); - } - } - - /** - * Tests the following story: - *
    - *
  • create object
  • - *
  • read object
  • - *
  • update object
  • - *
  • remove object
  • - *
- * - */ - @Test - public void testPersistenceStory() { - - createObject(); - readObject(); - updateObject(); - removeObject(); - } - - private void createObject() { - - try { - XmlPersistenceTest.logger.info("Trying to create..."); - - // new instance - Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); - - // persist instance - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - tx.add(resource); - tx.commit(); - - XmlPersistenceTest.logger.info("Done creating."); - - } catch (Exception e) { - XmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed: " + e.getLocalizedMessage()); - } - } - - private void readObject() { - - try { - XmlPersistenceTest.logger.info("Trying to read..."); - - // query Resource with id @id - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); - XmlPersistenceTest.logger.info("Found Resource: " + resource); - tx.commit(); - - XmlPersistenceTest.logger.info("Done reading."); - - } catch (Exception e) { - XmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed: " + e.getLocalizedMessage()); - } - } - - private void updateObject() { - - try { - XmlPersistenceTest.logger.info("Trying to update an object..."); - - // query the instance - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); - XmlPersistenceTest.logger.info("Found Resource: " + resource); - - // modify the instance - resource.setName(RES_NAME_MODIFIED); - - // update the instance - tx.update(resource); - tx.commit(); - - XmlPersistenceTest.logger.info("Done updating."); - - } catch (Exception e) { - XmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed: " + e.getLocalizedMessage()); - } - } - - private void removeObject() { - - XmlPersistenceTest.logger.info("Trying to remove..."); - - // query the instance - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); - XmlPersistenceTest.logger.info("Found Resource: " + resource); - - tx.remove(resource); - tx.commit(); - - XmlPersistenceTest.logger.info("Done removing."); - } - - @Test - public void testQueryFail() { - - XmlPersistenceTransaction tx = null; - try { - XmlPersistenceTest.logger.info("Trying to query removed object..."); - tx = XmlPersistenceTest.persistenceHandler.openTx(); - Resource resource = tx.queryById(Resource.class.getName(), RES_TYPE, RES_ID); - XmlPersistenceTest.logger.info("Found Resource: " + resource); - XmlPersistenceTest.logger.info("Done querying removed object"); - } catch (XmlPersistenceException e) { - Assert.assertEquals("Wrong error message. Expected error that object does not exist", - "No object exists for ch.eitchnet.xmlpers.test.impl.Resource / @subtype / @id", - e.getLocalizedMessage()); - } finally { - if (tx != null) - tx.commit(); - } - } - - @Test - public void testReCreate() { - - try { - XmlPersistenceTest.logger.info("Trying to recreate..."); - - // new instance - Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); - - // persist instance - XmlPersistenceTransaction tx = XmlPersistenceTest.persistenceHandler.openTx(); - tx.add(resource); - tx.commit(); - - XmlPersistenceTest.logger.info("Done creating."); - - } catch (Exception e) { - XmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed: " + e.getLocalizedMessage()); - } - } - - @Test - @Ignore - public void testQueryFromTo() { - Assert.fail("Not yet implemented"); - } - - @Test - public void testQueryAll() { - - XmlPersistenceTransaction tx = null; - try { - - XmlPersistenceTest.logger.info("Trying to query all..."); - - // query all - tx = XmlPersistenceTest.persistenceHandler.openTx(); - List list = tx.queryAll(Resource.class.getName()); - Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); - - // also with subtype - list = tx.queryAll(Resource.class.getName(), RES_TYPE); - Assert.assertTrue("Expected only one object, found " + list.size(), list.size() == 1); - - // and now something useless - list = tx.queryAll(Resource.class.getName(), RES_TYPE_INEXISTANT); - Assert.assertTrue("Expected no objects, found " + list.size(), list.size() == 0); - - XmlPersistenceTest.logger.info("Done querying."); - - } finally { - if (tx != null) - tx.commit(); - } - } - - @Test - public void testKeySet() { - - XmlPersistenceTransaction tx = null; - try { - tx = XmlPersistenceTest.persistenceHandler.openTx(); - - Set keySet = tx.queryKeySet(Resource.class.getName()); - Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); - - // also with subtype - keySet = tx.queryKeySet(Resource.class.getName(), RES_TYPE); - Assert.assertTrue("Expected one key, found " + keySet.size(), keySet.size() == 1); - - // and now something useless - keySet = tx.queryKeySet(Resource.class.getName(), RES_TYPE_INEXISTANT); - Assert.assertTrue("Expected no keys, found " + keySet, keySet.size() == 0); - - } finally { - if (tx != null) - tx.commit(); - } - } - - @Test - public void testRemoveAll() { - - XmlPersistenceTransaction tx = null; - try { - tx = XmlPersistenceTest.persistenceHandler.openTx(); - - List objects = tx.queryAll(Resource.class.getName(), RES_TYPE); - tx.removeAll(objects); - - } finally { - if (tx != null) - tx.commit(); - } - } - - @Test - public void testSize() { - - XmlPersistenceTransaction tx = null; - try { - tx = XmlPersistenceTest.persistenceHandler.openTx(); - - long size = tx.querySize(Resource.class.getName(), RES_TYPE); - Assert.assertTrue("Expected size = 0, found: " + size, size == 0); - - } finally { - if (tx != null) - tx.commit(); - } - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java index 54ec38957..7df3b66b9 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java @@ -33,6 +33,22 @@ public class Book { private String press; private double price; + /** + * @param id + * @param title + * @param author + * @param press + * @param price + */ + public Book(Long id, String title, String author, String press, double price) { + super(); + this.id = id; + this.title = title; + this.author = author; + this.press = press; + this.price = price; + } + /** * */ diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java index 26f1800d0..a6b1f05bd 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java @@ -21,7 +21,7 @@ */ package ch.eitchnet.xmlpers.test.impl; -import ch.eitchnet.xmlpers.impl.AbstractXmlDao; +import ch.eitchnet.xmlpers.api.AbstractXmlDao; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java new file mode 100644 index 000000000..bf3f3480c --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl; + +import java.io.File; + +import javax.xml.parsers.DocumentBuilder; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import ch.eitchnet.xmlpers.api.DomUtil; +import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; + +/** + * @author Robert von Burg + * + */ +public class BookDomDao extends BookDao { + + @Override + protected Book read(File filePath) { + + XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); + cd.setFile(filePath); + getFileHandler().read(cd); + Document document = cd.getDocument(); + Book book = parseFromDom(document.getDocumentElement()); + return book; + } + + @Override + protected void write(Book book, File filePath) { + + XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); + cd.setFile(filePath); + DocumentBuilder documentBuilder = DomUtil.createDocumentBuilder(); + Document document = documentBuilder.getDOMImplementation().createDocument(null, null, null); + serializeToDom(book, document); + cd.setDocument(document); + getFileHandler().write(cd); + } + + public Element serializeToDom(Book book, Document document) { + + Element element = document.createElement("Book"); + + element.setAttribute("id", Long.toString(book.getId())); + element.setAttribute("title", book.getTitle()); + element.setAttribute("author", book.getAuthor()); + element.setAttribute("press", book.getPress()); + element.setAttribute("price", Double.toString(book.getPrice())); + + return element; + } + + public Book parseFromDom(Element element) { + + String idS = element.getAttribute("id"); + long id = Long.parseLong(idS); + String title = element.getAttribute("title"); + String author = element.getAttribute("author"); + String press = element.getAttribute("press"); + String priceS = element.getAttribute("price"); + double price = Double.parseDouble(priceS); + + Book book = new Book(id, title, author, press, price); + return book; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java new file mode 100644 index 000000000..65a5fd113 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl; + +import java.io.File; + +import javax.xml.stream.XMLStreamException; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.xmlpers.api.XmlPersistenceSaxContextData; +import ch.eitchnet.xmlpers.api.XmlPersistenceSaxWriter; +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; + +/** + * @author Robert von Burg + * + */ +public class BookSaxDao extends BookDao { + + @Override + protected Book read(File filePath) { + + XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); + cd.setFile(filePath); + BookDefaultHandler bookDefaultHandler = new BookDefaultHandler(); + cd.setDefaultHandler(bookDefaultHandler); + + getFileHandler().read(cd); + + return bookDefaultHandler.getBook(); + } + + @Override + protected void write(Book book, File filePath) { + + XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); + cd.setFile(filePath); + cd.setXmlWriter(new BookSaxWriter(book)); + + getFileHandler().write(cd); + } + + private class BookSaxWriter implements XmlPersistenceSaxWriter { + + private final Book book; + + public BookSaxWriter(Book book) { + this.book = book; + } + + @Override + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + writer.writeEmptyElement("Book"); + writer.writeAttribute("id", Long.toString(this.book.getId())); + writer.writeAttribute("title", this.book.getTitle()); + writer.writeAttribute("author", this.book.getAuthor()); + writer.writeAttribute("press", this.book.getPress()); + writer.writeAttribute("price", Double.toString(this.book.getPrice())); + } + } + + private class BookDefaultHandler extends DefaultHandler { + + private Book book; + + public Book getBook() { + return this.book; + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + + switch (qName) { + case "Book": + String idS = attributes.getValue("id"); + long id = Long.parseLong(idS); + Book book = new Book(id); + book.setTitle(attributes.getValue("title")); + book.setAuthor(attributes.getValue("author")); + book.setPress(attributes.getValue("press")); + String priceS = attributes.getValue("price"); + double price = Double.parseDouble(priceS); + book.setPrice(price); + this.book = book; + break; + default: + throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); + } + } + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java index 3f7517370..ce61da6a3 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java @@ -21,7 +21,7 @@ */ package ch.eitchnet.xmlpers.test.impl; -import ch.eitchnet.xmlpers.impl.AbstractXmlDao; +import ch.eitchnet.xmlpers.api.AbstractXmlDao; import ch.eitchnet.xmlpers.test.model.Resource; /** @@ -30,13 +30,21 @@ import ch.eitchnet.xmlpers.test.model.Resource; */ public abstract class ResourceDao extends AbstractXmlDao { + private final String subType; + + public ResourceDao(String subType) { + this.subType = subType; + } + @Override public String getType() { return Resource.class.getSimpleName(); } @Override - public abstract String getSubType(); + public String getSubType() { + return this.subType; + } @Override public String getId(Resource object) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java index 2a267cbba..f1cac5029 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java @@ -21,41 +21,70 @@ package ch.eitchnet.xmlpers.test.impl; import java.io.File; +import javax.xml.parsers.DocumentBuilder; + import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Text; +import org.w3c.dom.NodeList; +import ch.eitchnet.xmlpers.api.DomUtil; +import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; +import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; /** * @author Robert von Burg * */ -public abstract class ResourceDomDao extends ResourceDao { +public class ResourceDomDao extends ResourceDao { + + /** + * @param subType + */ + public ResourceDomDao(String subType) { + super(subType); + } @Override protected Resource read(File filePath) { - // TODO Auto-generated method stub - return null; + + XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); + cd.setFile(filePath); + getFileHandler().read(cd); + Document document = cd.getDocument(); + Resource resource = parseFromDom(document.getDocumentElement()); + return resource; } @Override - protected void write(Resource object, File filePath) { - // TODO Auto-generated method stub + protected void write(Resource resource, File filePath) { + XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); + cd.setFile(filePath); + DocumentBuilder documentBuilder = DomUtil.createDocumentBuilder(); + Document document = documentBuilder.getDOMImplementation().createDocument(null, null, null); + serializeToDom(resource, document); + cd.setDocument(document); + getFileHandler().write(cd); } - public Element serializeToDom(Resource object, Document document) { + public Element serializeToDom(Resource resource, Document document) { Element element = document.createElement("Resource"); - element.setAttribute("id", object.getId()); - element.setAttribute("type", object.getType()); + element.setAttribute("id", resource.getId()); + element.setAttribute("name", resource.getName()); + element.setAttribute("type", resource.getType()); - Element nameElement = document.createElement("Name"); - element.appendChild(nameElement); - Text textNode = document.createTextNode(object.getName()); - nameElement.appendChild(textNode); + for (String paramId : resource.getParameterKeySet()) { + Parameter param = resource.getParameterBy(paramId); + Element paramElement = document.createElement("Parameter"); + + paramElement.setAttribute("id", param.getId()); + paramElement.setAttribute("name", param.getName()); + paramElement.setAttribute("type", param.getType()); + paramElement.setAttribute("value", param.getType()); + } return element; } @@ -63,12 +92,22 @@ public abstract class ResourceDomDao extends ResourceDao { public Resource parseFromDom(Element element) { String id = element.getAttribute("id"); + String name = element.getAttribute("name"); String type = element.getAttribute("type"); - Element nameElement = (Element) element.getElementsByTagName("Name").item(0); - String name = nameElement.getTextContent(); - Resource Resource = new Resource(id, name, type); + Resource resource = new Resource(id, name, type); - return Resource; + NodeList paramElements = element.getElementsByTagName("Parameter"); + for (int i = 0; i < paramElements.getLength(); i++) { + String paramId = element.getAttribute("id"); + String paramName = element.getAttribute("name"); + String paramType = element.getAttribute("type"); + String paramValue = element.getAttribute("value"); + + Parameter param = new Parameter(paramId, paramName, paramType, paramValue); + resource.addParameter(param); + } + + return resource; } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java index c31e9018c..657a54da0 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java @@ -19,10 +19,18 @@ */ package ch.eitchnet.xmlpers.test.impl; -import org.xml.sax.ContentHandler; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; +import java.io.File; +import javax.xml.stream.XMLStreamException; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.xmlpers.api.XmlPersistenceSaxContextData; +import ch.eitchnet.xmlpers.api.XmlPersistenceSaxWriter; +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; /** @@ -31,35 +39,91 @@ import ch.eitchnet.xmlpers.test.model.Resource; */ public class ResourceSaxDao extends ResourceDao { - public void serializeToSax(Resource object, ContentHandler contentHandler) { + /** + * @param subType + */ + public ResourceSaxDao(String subType) { + super(subType); + } - try { - contentHandler.startDocument(); + @Override + protected Resource read(File filePath) { - // Resource element / root - { - AttributesImpl atts = new AttributesImpl(); - atts.addAttribute("", "", "id", "", object.getId()); - atts.addAttribute("", "", "type", "", object.getType()); - contentHandler.startElement("", "", "Resource", atts); + XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); + cd.setFile(filePath); + ResourceDefaultHandler bookDefaultHandler = new ResourceDefaultHandler(); + cd.setDefaultHandler(bookDefaultHandler); - // name element - { - contentHandler.startElement("", "", "Name", null); - char[] nameArr = object.getName().toCharArray(); - contentHandler.characters(nameArr, 0, nameArr.length); - contentHandler.endElement("", "", "name"); - } + getFileHandler().read(cd); - // Resource end - contentHandler.endElement("", "", "Resource"); + return bookDefaultHandler.getResource(); + } + + @Override + protected void write(Resource resource, File filePath) { + + XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); + cd.setFile(filePath); + cd.setXmlWriter(new ResourceSaxWriter(resource)); + + getFileHandler().write(cd); + } + + private class ResourceSaxWriter implements XmlPersistenceSaxWriter { + + private final Resource resource; + + public ResourceSaxWriter(Resource resource) { + this.resource = resource; + } + + @Override + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + writer.writeElement("Resource"); + writer.writeAttribute("id", this.resource.getId()); + writer.writeAttribute("name", this.resource.getName()); + writer.writeAttribute("type", this.resource.getType()); + for (String paramId : this.resource.getParameterKeySet()) { + Parameter param = this.resource.getParameterBy(paramId); + writer.writeElement("Parameter"); + writer.writeAttribute("id", param.getId()); + writer.writeAttribute("name", param.getName()); + writer.writeAttribute("type", param.getType()); + writer.writeAttribute("value", param.getValue()); } + } + } - // end document - contentHandler.endDocument(); + private class ResourceDefaultHandler extends DefaultHandler { - } catch (SAXException e) { - throw new RuntimeException("Failed to serialize " + object + " to SAX", e); + private Resource resource; + + public Resource getResource() { + return this.resource; + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + + switch (qName) { + case "Resource": + String id = attributes.getValue("id"); + String name = attributes.getValue("name"); + String type = attributes.getValue("type"); + Resource resource = new Resource(id, name, type); + this.resource = resource; + break; + case "Parameter": + id = attributes.getValue("id"); + name = attributes.getValue("name"); + type = attributes.getValue("type"); + String value = attributes.getValue("value"); + Parameter param = new Parameter(id, name, type, value); + this.resource.addParameter(param); + break; + default: + throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); + } } } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java new file mode 100644 index 000000000..5ec56aaa5 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class TestConstants { + + public static final String TYPE_RES = Resource.class.getSimpleName(); + public static final String TYPE_BOOK = Book.class.getSimpleName(); +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java index abd7c9e45..43474a8d4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java @@ -19,59 +19,79 @@ */ package ch.eitchnet.xmlpers.test.impl; -import java.util.Properties; +import java.text.MessageFormat; +import ch.eitchnet.xmlpers.api.AbstractDaoFactory; +import ch.eitchnet.xmlpers.api.XmlIoMode; import ch.eitchnet.xmlpers.api.XmlPersistenceDao; -import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; import ch.eitchnet.xmlpers.test.model.Resource; /** * @author Robert von Burg * */ -public class TestModelDaoFactory implements XmlPersistenceDaoFactory { +public class TestModelDaoFactory extends AbstractDaoFactory { @Override - public void initialize(XmlPersistenceFileDao fileDao, Properties properties) { - // TODO Auto-generated method stub + public XmlPersistenceDao getDao(T object) { - } - - @Override - public XmlPersistenceDao createDaoInstance(T object) { - - if (object.getClass() != Resource.class) - throw new IllegalArgumentException("The object with class " + object.getClass() + " is not handled!"); - - Resource resource = (Resource) object; - String type = resource.getType(); - XmlPersistenceDao dao; - switch (type) { - case "MyType": - dao = new MyTypeResourceDao(); - break; - default: - throw new IllegalArgumentException("The resource with type " + type + " is not handled!"); + XmlPersistenceDao dao; + if (object instanceof Resource) { + dao = getDaoBy(object.getClass().getSimpleName(), ((Resource) object).getType()); + } else if (object instanceof Book) { + dao = getDaoBy(Book.class.getSimpleName()); + } else { + String msg = "The object with class {0} is not handled!"; + msg = MessageFormat.format(msg, object.getClass()); + throw new IllegalArgumentException(msg); } - // inject the DAO or SAX handler... - - @SuppressWarnings("unchecked") - XmlPersistenceDao xmlDao = (XmlPersistenceDao) dao; - return xmlDao; + return dao; } + @SuppressWarnings("unchecked") @Override - public XmlPersistenceDao createDaoInstance(String type) { - // TODO Auto-generated method stub - return null; + public XmlPersistenceDao getDaoBy(String type) { + + XmlPersistenceDao dao; + if (TestConstants.TYPE_BOOK.equals(type)) { + XmlIoMode ioMode = getXmlIoMode(); + if (ioMode == XmlIoMode.DOM) { + dao = (XmlPersistenceDao) new BookDomDao(); + } else if (ioMode == XmlIoMode.SAX) { + dao = (XmlPersistenceDao) new BookSaxDao(); + } else { + throw new IllegalArgumentException("The XmlIoMode " + ioMode + " is not yet supported!"); + } + } else { + String msg = "The object with type {0} is not handled!"; + msg = MessageFormat.format(msg, type); + throw new IllegalArgumentException(msg); + } + + return initializeDao(dao); } + @SuppressWarnings("unchecked") @Override - public XmlPersistenceDao createDaoInstance(String type, String subType) { - // TODO Auto-generated method stub - return null; - } + public XmlPersistenceDao getDaoBy(String type, String subType) { + XmlPersistenceDao dao; + if (TestConstants.TYPE_RES.equals(type)) { + XmlIoMode ioMode = getXmlIoMode(); + if (ioMode == XmlIoMode.DOM) { + dao = (XmlPersistenceDao) new ResourceDomDao(subType); + } else if (ioMode == XmlIoMode.SAX) { + dao = (XmlPersistenceDao) new ResourceSaxDao(subType); + } else { + throw new IllegalArgumentException("The XmlIoMode " + ioMode + " is not yet supported!"); + } + } else { + String msg = "The object with type {0} and subType {1} is not handled!"; + msg = MessageFormat.format(msg, type, subType); + throw new IllegalArgumentException(msg); + } + + return initializeDao(dao); + } } From 23cbca6f89065922e1aab1da89071be494381de2 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 15 Sep 2013 20:55:16 +0200 Subject: [PATCH 21/87] [Minor] fixed compile error due to wrong import to test classes --- src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java index 09a21cc29..33ad1db95 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java @@ -31,7 +31,6 @@ import ch.eitchnet.xmlpers.impl.MetadataXmlDao; import ch.eitchnet.xmlpers.impl.XmlPersistenceDomHandler; import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; import ch.eitchnet.xmlpers.impl.XmlPersistenceSaxHandler; -import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; /** * @author Robert von Burg @@ -47,7 +46,7 @@ public abstract class AbstractDaoFactory implements XmlPersistenceDaoFactory { public void initialize(XmlPersistenceFileDao fileDao, Properties properties) { this.fileDao = fileDao; // TODO catch and throw proper exception - String xmlIoModeS = PropertiesHelper.getProperty(properties, TestModelDaoFactory.class.getName(), + String xmlIoModeS = PropertiesHelper.getProperty(properties, AbstractDaoFactory.class.getName(), XmlPersistenceConstants.PROP_XML_IO_MOD, XmlIoMode.SAX.name()); this.xmlIoMode = XmlIoMode.valueOf(xmlIoModeS.toUpperCase()); logger.info("Defaut Xml IO Mode is " + this.xmlIoMode.name()); From fed2bffa3693db84c51e49beb4a96a7642e227b8 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 15 Sep 2013 21:41:00 +0200 Subject: [PATCH 22/87] [Major] major rewrite, now implemented SAX and DOM methods. Now DOM implementation is working as well with a test scenario --- .../test/AbstractXmlPersistenceTest.java | 8 +++++-- .../xmlpers/test/XmlPersistenceDomTest.java | 1 - .../test/{Main.java => XmlTestMain.java} | 4 ++-- .../xmlpers/test/impl/BookDomDao.java | 2 +- .../xmlpers/test/impl/ResourceDomDao.java | 22 +++++++++++++------ 5 files changed, 24 insertions(+), 13 deletions(-) rename src/test/java/ch/eitchnet/xmlpers/test/{Main.java => XmlTestMain.java} (98%) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java index 706c40441..aaf424ef4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java @@ -78,7 +78,11 @@ public abstract class AbstractXmlPersistenceTest { * if something goes wrong */ public static void init(Properties props) throws Exception { + try { + + cleanUpDb(); + String userDir = System.getProperty("user.dir"); String basePath = userDir + "/target/testdb"; File basePathF = new File(basePath); @@ -90,14 +94,14 @@ public abstract class AbstractXmlPersistenceTest { AbstractXmlPersistenceTest.logger.info("Initialized persistence handler."); } catch (Exception e) { - AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); + AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); throw new RuntimeException("Initialization failed: " + e.getLocalizedMessage(), e); } } @AfterClass - public static void afterClass() { + public static void cleanUpDb() { String userDir = System.getProperty("user.dir"); String basePath = userDir + "/target/testdb"; File basePathF = new File(basePath); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java index 35448c2c0..7cd7e6c17 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java @@ -30,7 +30,6 @@ import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; /** * @author Robert von Burg */ -@Ignore public class XmlPersistenceDomTest extends AbstractXmlPersistenceTest { /** diff --git a/src/test/java/ch/eitchnet/xmlpers/test/Main.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java similarity index 98% rename from src/test/java/ch/eitchnet/xmlpers/test/Main.java rename to src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index bc61911d5..9045ae228 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/Main.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -59,9 +59,9 @@ import ch.eitchnet.xmlpers.test.model.Resource; * @author Robert von Burg * */ -public class Main { +public class XmlTestMain { - private static final Logger logger = LoggerFactory.getLogger(Main.class); + private static final Logger logger = LoggerFactory.getLogger(XmlTestMain.class); private static Resource res; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java index bf3f3480c..36a0f098a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java @@ -63,7 +63,7 @@ public class BookDomDao extends BookDao { public Element serializeToDom(Book book, Document document) { Element element = document.createElement("Book"); - + document.appendChild(element); element.setAttribute("id", Long.toString(book.getId())); element.setAttribute("title", book.getTitle()); element.setAttribute("author", book.getAuthor()); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java index f1cac5029..0267b70eb 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java @@ -25,6 +25,7 @@ import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; +import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ch.eitchnet.xmlpers.api.DomUtil; @@ -71,6 +72,7 @@ public class ResourceDomDao extends ResourceDao { public Element serializeToDom(Resource resource, Document document) { Element element = document.createElement("Resource"); + document.appendChild(element); element.setAttribute("id", resource.getId()); element.setAttribute("name", resource.getName()); @@ -79,11 +81,12 @@ public class ResourceDomDao extends ResourceDao { for (String paramId : resource.getParameterKeySet()) { Parameter param = resource.getParameterBy(paramId); Element paramElement = document.createElement("Parameter"); + element.appendChild(paramElement); paramElement.setAttribute("id", param.getId()); paramElement.setAttribute("name", param.getName()); paramElement.setAttribute("type", param.getType()); - paramElement.setAttribute("value", param.getType()); + paramElement.setAttribute("value", param.getValue()); } return element; @@ -97,12 +100,17 @@ public class ResourceDomDao extends ResourceDao { Resource resource = new Resource(id, name, type); - NodeList paramElements = element.getElementsByTagName("Parameter"); - for (int i = 0; i < paramElements.getLength(); i++) { - String paramId = element.getAttribute("id"); - String paramName = element.getAttribute("name"); - String paramType = element.getAttribute("type"); - String paramValue = element.getAttribute("value"); + NodeList children = element.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node item = children.item(i); + if (!item.getNodeName().equals("Parameter")) + continue; + + Element paramElement = (Element) item; + String paramId = paramElement.getAttribute("id"); + String paramName = paramElement.getAttribute("name"); + String paramType = paramElement.getAttribute("type"); + String paramValue = paramElement.getAttribute("value"); Parameter param = new Parameter(paramId, paramName, paramType, paramValue); resource.addParameter(param); From c7ba5054def21fec477aef68d89265e30dec9f56 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 15 Sep 2013 21:42:04 +0200 Subject: [PATCH 23/87] [Minor] fixed compiler warnings --- .../java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java index 7cd7e6c17..2143e62b4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java @@ -22,7 +22,6 @@ package ch.eitchnet.xmlpers.test; import java.util.Properties; import org.junit.BeforeClass; -import org.junit.Ignore; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; From f9c613ca46791765548d592fe711d48caafe049c Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 15 Sep 2013 21:43:52 +0200 Subject: [PATCH 24/87] [Minor] fixed compiler warnings --- .../staxutils/IndentingXMLStreamWriter.java | 172 ++++++++++-------- .../helpers/StreamWriterDelegate.java | 160 +++++++++------- 2 files changed, 194 insertions(+), 138 deletions(-) diff --git a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java index 9e09a7be0..dd5438e24 100644 --- a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java +++ b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java @@ -101,21 +101,24 @@ public class IndentingXMLStreamWriter extends StreamWriterDelegate implements In /** newLine followed by copies of indent. */ private char[] linePrefix = null; - public void setIndent(String indent) { + @Override + public void setIndent(String indent) { if (!indent.equals(this.indent)) { this.indent = indent; - linePrefix = null; + this.linePrefix = null; } } - public String getIndent() { - return indent; + @Override + public String getIndent() { + return this.indent; } - public void setNewLine(String newLine) { + @Override + public void setNewLine(String newLine) { if (!newLine.equals(this.newLine)) { this.newLine = newLine; - linePrefix = null; + this.linePrefix = null; } } @@ -127,141 +130,162 @@ public class IndentingXMLStreamWriter extends StreamWriterDelegate implements In try { return System.getProperty("line.separator"); } catch (SecurityException ignored) { + // } return NORMAL_END_OF_LINE; } - public String getNewLine() { - return newLine; + @Override + public String getNewLine() { + return this.newLine; } - public void writeStartDocument() throws XMLStreamException { + @Override + public void writeStartDocument() throws XMLStreamException { beforeMarkup(); - out.writeStartDocument(); + this.out.writeStartDocument(); afterMarkup(); } - public void writeStartDocument(String version) throws XMLStreamException { + @Override + public void writeStartDocument(String version) throws XMLStreamException { beforeMarkup(); - out.writeStartDocument(version); + this.out.writeStartDocument(version); afterMarkup(); } - public void writeStartDocument(String encoding, String version) throws XMLStreamException { + @Override + public void writeStartDocument(String encoding, String version) throws XMLStreamException { beforeMarkup(); - out.writeStartDocument(encoding, version); + this.out.writeStartDocument(encoding, version); afterMarkup(); } - public void writeDTD(String dtd) throws XMLStreamException { + @Override + public void writeDTD(String dtd) throws XMLStreamException { beforeMarkup(); - out.writeDTD(dtd); + this.out.writeDTD(dtd); afterMarkup(); } - public void writeProcessingInstruction(String target) throws XMLStreamException { + @Override + public void writeProcessingInstruction(String target) throws XMLStreamException { beforeMarkup(); - out.writeProcessingInstruction(target); + this.out.writeProcessingInstruction(target); afterMarkup(); } - public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + @Override + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { beforeMarkup(); - out.writeProcessingInstruction(target, data); + this.out.writeProcessingInstruction(target, data); afterMarkup(); } - public void writeComment(String data) throws XMLStreamException { + @Override + public void writeComment(String data) throws XMLStreamException { beforeMarkup(); - out.writeComment(data); + this.out.writeComment(data); afterMarkup(); } - public void writeEmptyElement(String localName) throws XMLStreamException { + @Override + public void writeEmptyElement(String localName) throws XMLStreamException { beforeMarkup(); - out.writeEmptyElement(localName); + this.out.writeEmptyElement(localName); afterMarkup(); } - public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + @Override + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { beforeMarkup(); - out.writeEmptyElement(namespaceURI, localName); + this.out.writeEmptyElement(namespaceURI, localName); afterMarkup(); } - public void writeEmptyElement(String prefix, String localName, String namespaceURI) + @Override + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { beforeMarkup(); - out.writeEmptyElement(prefix, localName, namespaceURI); + this.out.writeEmptyElement(prefix, localName, namespaceURI); afterMarkup(); } - public void writeStartElement(String localName) throws XMLStreamException { + @Override + public void writeStartElement(String localName) throws XMLStreamException { beforeStartElement(); - out.writeStartElement(localName); + this.out.writeStartElement(localName); afterStartElement(); } - public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + @Override + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { beforeStartElement(); - out.writeStartElement(namespaceURI, localName); + this.out.writeStartElement(namespaceURI, localName); afterStartElement(); } - public void writeStartElement(String prefix, String localName, String namespaceURI) + @Override + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { beforeStartElement(); - out.writeStartElement(prefix, localName, namespaceURI); + this.out.writeStartElement(prefix, localName, namespaceURI); afterStartElement(); } - public void writeCharacters(String text) throws XMLStreamException { - out.writeCharacters(text); + @Override + public void writeCharacters(String text) throws XMLStreamException { + this.out.writeCharacters(text); afterData(); } - public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - out.writeCharacters(text, start, len); + @Override + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + this.out.writeCharacters(text, start, len); afterData(); } - public void writeCData(String data) throws XMLStreamException { - out.writeCData(data); + @Override + public void writeCData(String data) throws XMLStreamException { + this.out.writeCData(data); afterData(); } - public void writeEntityRef(String name) throws XMLStreamException { - out.writeEntityRef(name); + @Override + public void writeEntityRef(String name) throws XMLStreamException { + this.out.writeEntityRef(name); afterData(); } - public void writeEndElement() throws XMLStreamException { + @Override + public void writeEndElement() throws XMLStreamException { beforeEndElement(); - out.writeEndElement(); + this.out.writeEndElement(); afterEndElement(); } - public void writeEndDocument() throws XMLStreamException { + @Override + public void writeEndDocument() throws XMLStreamException { try { - while (depth > 0) { + while (this.depth > 0) { writeEndElement(); // indented } } catch (Exception ignored) { ignored.printStackTrace(); } - out.writeEndDocument(); + this.out.writeEndDocument(); afterEndDocument(); } /** Prepare to write markup, by writing a new line and indentation. */ protected void beforeMarkup() { - int soFar = stack[depth]; + int soFar = this.stack[this.depth]; if ((soFar & WROTE_DATA) == 0 // no data in this scope - && (depth > 0 || soFar != 0)) // not the first line + && (this.depth > 0 || soFar != 0)) // not the first line { try { - writeNewLine(depth); - if (depth > 0 && getIndent().length() > 0) { + writeNewLine(this.depth); + if (this.depth > 0 && getIndent().length() > 0) { afterMarkup(); // indentation was written } } catch (Exception e) { @@ -272,37 +296,37 @@ public class IndentingXMLStreamWriter extends StreamWriterDelegate implements In /** Note that markup or indentation was written. */ protected void afterMarkup() { - stack[depth] |= WROTE_MARKUP; + this.stack[this.depth] |= WROTE_MARKUP; } /** Note that data were written. */ protected void afterData() { - stack[depth] |= WROTE_DATA; + this.stack[this.depth] |= WROTE_DATA; } /** Prepare to start an element, by allocating stack space. */ protected void beforeStartElement() { beforeMarkup(); - if (stack.length <= depth + 1) { + if (this.stack.length <= this.depth + 1) { // Allocate more space for the stack: - int[] newStack = new int[stack.length * 2]; - System.arraycopy(stack, 0, newStack, 0, stack.length); - stack = newStack; + int[] newStack = new int[this.stack.length * 2]; + System.arraycopy(this.stack, 0, newStack, 0, this.stack.length); + this.stack = newStack; } - stack[depth + 1] = 0; // nothing written yet + this.stack[this.depth + 1] = 0; // nothing written yet } /** Note that an element was started. */ protected void afterStartElement() { afterMarkup(); - ++depth; + ++this.depth; } /** Prepare to end an element, by writing a new line and indentation. */ protected void beforeEndElement() { - if (depth > 0 && stack[depth] == WROTE_MARKUP) { // but not data + if (this.depth > 0 && this.stack[this.depth] == WROTE_MARKUP) { // but not data try { - writeNewLine(depth - 1); + writeNewLine(this.depth - 1); } catch (Exception ignored) { ignored.printStackTrace(); } @@ -311,21 +335,21 @@ public class IndentingXMLStreamWriter extends StreamWriterDelegate implements In /** Note that an element was ended. */ protected void afterEndElement() { - if (depth > 0) { - --depth; + if (this.depth > 0) { + --this.depth; } } /** Note that a document was ended. */ protected void afterEndDocument() { - if (stack[depth = 0] == WROTE_MARKUP) { // but not data + if (this.stack[this.depth = 0] == WROTE_MARKUP) { // but not data try { writeNewLine(0); } catch (Exception ignored) { ignored.printStackTrace(); } } - stack[depth] = 0; // start fresh + this.stack[this.depth] = 0; // start fresh } /** Write a line separator followed by indentation. */ @@ -333,19 +357,19 @@ public class IndentingXMLStreamWriter extends StreamWriterDelegate implements In final int newLineLength = getNewLine().length(); final int prefixLength = newLineLength + (getIndent().length() * indentation); if (prefixLength > 0) { - if (linePrefix == null) { - linePrefix = (getNewLine() + getIndent()).toCharArray(); + if (this.linePrefix == null) { + this.linePrefix = (getNewLine() + getIndent()).toCharArray(); } - while (prefixLength > linePrefix.length) { + while (prefixLength > this.linePrefix.length) { // make linePrefix longer: char[] newPrefix = new char[newLineLength - + ((linePrefix.length - newLineLength) * 2)]; - System.arraycopy(linePrefix, 0, newPrefix, 0, linePrefix.length); - System.arraycopy(linePrefix, newLineLength, newPrefix, linePrefix.length, - linePrefix.length - newLineLength); - linePrefix = newPrefix; + + ((this.linePrefix.length - newLineLength) * 2)]; + System.arraycopy(this.linePrefix, 0, newPrefix, 0, this.linePrefix.length); + System.arraycopy(this.linePrefix, newLineLength, newPrefix, this.linePrefix.length, + this.linePrefix.length - newLineLength); + this.linePrefix = newPrefix; } - out.writeCharacters(linePrefix, 0, prefixLength); + this.out.writeCharacters(this.linePrefix, 0, prefixLength); } } diff --git a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java index edba1f7f5..49e70d88e 100644 --- a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java +++ b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java @@ -50,136 +50,168 @@ public abstract class StreamWriterDelegate implements XMLStreamWriter { protected XMLStreamWriter out; - public Object getProperty(String name) throws IllegalArgumentException { - return out.getProperty(name); + @Override + public Object getProperty(String name) throws IllegalArgumentException { + return this.out.getProperty(name); } - public NamespaceContext getNamespaceContext() { - return out.getNamespaceContext(); + @Override + public NamespaceContext getNamespaceContext() { + return this.out.getNamespaceContext(); } - public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { - out.setNamespaceContext(context); + @Override + public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { + this.out.setNamespaceContext(context); } - public void setDefaultNamespace(String uri) throws XMLStreamException { - out.setDefaultNamespace(uri); + @Override + public void setDefaultNamespace(String uri) throws XMLStreamException { + this.out.setDefaultNamespace(uri); } - public void writeStartDocument() throws XMLStreamException { - out.writeStartDocument(); + @Override + public void writeStartDocument() throws XMLStreamException { + this.out.writeStartDocument(); } - public void writeStartDocument(String version) throws XMLStreamException { - out.writeStartDocument(version); + @Override + public void writeStartDocument(String version) throws XMLStreamException { + this.out.writeStartDocument(version); } - public void writeStartDocument(String encoding, String version) throws XMLStreamException { - out.writeStartDocument(encoding, version); + @Override + public void writeStartDocument(String encoding, String version) throws XMLStreamException { + this.out.writeStartDocument(encoding, version); } - public void writeDTD(String dtd) throws XMLStreamException { - out.writeDTD(dtd); + @Override + public void writeDTD(String dtd) throws XMLStreamException { + this.out.writeDTD(dtd); } - public void writeProcessingInstruction(String target) throws XMLStreamException { - out.writeProcessingInstruction(target); + @Override + public void writeProcessingInstruction(String target) throws XMLStreamException { + this.out.writeProcessingInstruction(target); } - public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - out.writeProcessingInstruction(target, data); + @Override + public void writeProcessingInstruction(String target, String data) throws XMLStreamException { + this.out.writeProcessingInstruction(target, data); } - public void writeComment(String data) throws XMLStreamException { - out.writeComment(data); + @Override + public void writeComment(String data) throws XMLStreamException { + this.out.writeComment(data); } - public void writeEmptyElement(String localName) throws XMLStreamException { - out.writeEmptyElement(localName); + @Override + public void writeEmptyElement(String localName) throws XMLStreamException { + this.out.writeEmptyElement(localName); } - public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - out.writeEmptyElement(namespaceURI, localName); + @Override + public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { + this.out.writeEmptyElement(namespaceURI, localName); } - public void writeEmptyElement(String prefix, String localName, String namespaceURI) + @Override + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - out.writeEmptyElement(prefix, localName, namespaceURI); + this.out.writeEmptyElement(prefix, localName, namespaceURI); } - public void writeStartElement(String localName) throws XMLStreamException { - out.writeStartElement(localName); + @Override + public void writeStartElement(String localName) throws XMLStreamException { + this.out.writeStartElement(localName); } - public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - out.writeStartElement(namespaceURI, localName); + @Override + public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { + this.out.writeStartElement(namespaceURI, localName); } - public void writeStartElement(String prefix, String localName, String namespaceURI) + @Override + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - out.writeStartElement(prefix, localName, namespaceURI); + this.out.writeStartElement(prefix, localName, namespaceURI); } - public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { - out.writeDefaultNamespace(namespaceURI); + @Override + public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { + this.out.writeDefaultNamespace(namespaceURI); } - public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { - out.writeNamespace(prefix, namespaceURI); + @Override + public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { + this.out.writeNamespace(prefix, namespaceURI); } - public String getPrefix(String uri) throws XMLStreamException { - return out.getPrefix(uri); + @Override + public String getPrefix(String uri) throws XMLStreamException { + return this.out.getPrefix(uri); } - public void setPrefix(String prefix, String uri) throws XMLStreamException { - out.setPrefix(prefix, uri); + @Override + public void setPrefix(String prefix, String uri) throws XMLStreamException { + this.out.setPrefix(prefix, uri); } - public void writeAttribute(String localName, String value) throws XMLStreamException { - out.writeAttribute(localName, value); + @Override + public void writeAttribute(String localName, String value) throws XMLStreamException { + this.out.writeAttribute(localName, value); } - public void writeAttribute(String namespaceURI, String localName, String value) + @Override + public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { - out.writeAttribute(namespaceURI, localName, value); + this.out.writeAttribute(namespaceURI, localName, value); } - public void writeAttribute(String prefix, String namespaceURI, String localName, String value) + @Override + public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException { - out.writeAttribute(prefix, namespaceURI, localName, value); + this.out.writeAttribute(prefix, namespaceURI, localName, value); } - public void writeCharacters(String text) throws XMLStreamException { - out.writeCharacters(text); + @Override + public void writeCharacters(String text) throws XMLStreamException { + this.out.writeCharacters(text); } - public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - out.writeCharacters(text, start, len); + @Override + public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { + this.out.writeCharacters(text, start, len); } - public void writeCData(String data) throws XMLStreamException { - out.writeCData(data); + @Override + public void writeCData(String data) throws XMLStreamException { + this.out.writeCData(data); } - public void writeEntityRef(String name) throws XMLStreamException { - out.writeEntityRef(name); + @Override + public void writeEntityRef(String name) throws XMLStreamException { + this.out.writeEntityRef(name); } - public void writeEndElement() throws XMLStreamException { - out.writeEndElement(); + @Override + public void writeEndElement() throws XMLStreamException { + this.out.writeEndElement(); } - public void writeEndDocument() throws XMLStreamException { - out.writeEndDocument(); + @Override + public void writeEndDocument() throws XMLStreamException { + this.out.writeEndDocument(); } - public void flush() throws XMLStreamException { - out.flush(); + @Override + public void flush() throws XMLStreamException { + this.out.flush(); } - public void close() throws XMLStreamException { - out.close(); + @Override + public void close() throws XMLStreamException { + this.out.close(); } } From 15a118e0e592cac38a18981852b36e18fa0270a4 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 27 Sep 2013 20:23:48 +0200 Subject: [PATCH 25/87] [Major] major rewrite, re-thinking the API it is still not really nice how one has to use the persistence layer, thus in the test folder i am currently implementing a completely new API where simple use is central - but not forgetting SAX and DOM being used transparently. --- .../ch/eitchnet/xmlpers/api/DaoContext.java | 42 ++++ .../ch/eitchnet/xmlpers/api/IoContext.java | 31 +++ .../ch/eitchnet/xmlpers/api/XmlIoMode.java | 2 +- .../impl/XmlPersistenceFileIoHandler.java | 37 +++ .../impl/XmlPersistencePathBuilder.java | 101 ++++++++ .../test/AbstractXmlPersistenceTest.java | 96 ++------ .../ch/eitchnet/xmlpers/test/XmlTestMain.java | 27 +-- .../xmlpers/test/impl/rewrite/DomParser.java | 35 +++ .../xmlpers/test/impl/rewrite/FileDao.java | 61 +++++ .../test/impl/rewrite/FileDaoTest.java | 142 +++++++++++ .../xmlpers/test/impl/rewrite/FileIo.java | 222 ++++++++++++++++++ .../xmlpers/test/impl/rewrite/ObjectDao.java | 51 ++++ .../test/impl/rewrite/ParserFactory.java | 29 +++ .../test/impl/rewrite/PersistenceContext.java | 83 +++++++ .../test/impl/rewrite/ResourceDomParser.java | 105 +++++++++ .../impl/rewrite/ResourceParserFactory.java | 37 +++ .../test/impl/rewrite/ResourceSaxParser.java | 93 ++++++++ .../xmlpers/test/impl/rewrite/SaxParser.java | 39 +++ .../xmlpers/test/model/ModelBuilder.java | 117 +++++++++ 19 files changed, 1243 insertions(+), 107 deletions(-) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/IoContext.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java b/src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java new file mode 100644 index 000000000..0128f7bed --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +/** + * @author Robert von Burg + * + * @param + */ +public interface DaoContext { + + public String getType(); + + public String getSubType(); + + public String getId(); + + public boolean hasSubType(); + + public T getObject(); + + public U getIoContext(); +} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoContext.java b/src/main/java/ch/eitchnet/xmlpers/api/IoContext.java new file mode 100644 index 000000000..641eb3914 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/IoContext.java @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +/** + * @author Robert von Burg + * + */ +public interface IoContext { + + // marker interface +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java index e0a89f617..99592ff6c 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java @@ -27,5 +27,5 @@ package ch.eitchnet.xmlpers.api; */ public enum XmlIoMode { - DOM, SAX; + DEFAULT, DOM, SAX; } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java new file mode 100644 index 000000000..35f377dd9 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; + +import ch.eitchnet.xmlpers.api.DaoContext; + +/** + * @author Robert von Burg + * + */ +public interface XmlPersistenceFileIoHandler { + + public void read(DaoContext context, File file); + + public void write(DaoContext context, File file); +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java index 4c0b3c9af..3e0c84535 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java @@ -31,6 +31,7 @@ import ch.eitchnet.utils.helper.PropertiesHelper; import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.test.impl.rewrite.PersistenceContext; /** * @author Robert von Burg @@ -44,6 +45,8 @@ public class XmlPersistencePathBuilder { private final boolean verbose; private final String basePath; + private File path; + public XmlPersistencePathBuilder(Properties properties) { // get properties @@ -290,4 +293,102 @@ public class XmlPersistencePathBuilder { throw new XmlPersistenceException(MessageFormat.format(msg, args)); } } + + private void logPath(String operation, File path, PersistenceContext context) { + if (this.verbose) { + String msg; + if (StringHelper.isEmpty(context.getSubType())) { + msg = "Path for operation {0} for {1} / {2} / is at {3}"; + msg = MessageFormat.format(msg, operation, context.getType(), context.getId(), path.getAbsolutePath()); + } else { + msg = "Path for operation {0} for {1} / {2} / {3} / is at {4}"; + msg = MessageFormat.format(msg, operation, context.getType(), context.getSubType(), context.getId(), + path.getAbsolutePath()); + } + } + } + + private void createMissingParents(File path, PersistenceContext context) { + File parentFile = path.getParentFile(); + if (!parentFile.exists() && !parentFile.mkdirs()) { + String msg; + if (StringHelper.isEmpty(context.getSubType())) { + msg = "Could not create parent path for {0} / {1} / at {2}"; + msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); + } else { + msg = "Could not create parent path for {0} / {1} / {2} at {3}"; + msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), + path.getAbsolutePath()); + } + + throw new XmlPersistenceException(msg); + } + } + + private void assertPathExists(File path, PersistenceContext context) { + if (!path.exists()) { + String msg; + if (StringHelper.isEmpty(context.getSubType())) { + msg = "Persistence unit does not exist for {0} / {1} at {2}"; + msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); + } else { + msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; + msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), + path.getAbsolutePath()); + } + + throw new XmlPersistenceException(msg); + } + } + + private void assertPathNotExists(File path, PersistenceContext context) { + if (path.exists()) { + String msg; + if (StringHelper.isEmpty(context.getSubType())) { + msg = "Persistence unit already exists for {0} / {1} at {2}"; + msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); + } else { + msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; + msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), + path.getAbsolutePath()); + } + + throw new XmlPersistenceException(msg); + } + } + + public File getCreatePath(PersistenceContext context) { + File path = getPath(context); + logPath("CREATE", path, context); + assertPathNotExists(path, context); + createMissingParents(path, context); + return path; + } + + public File getDeletePath(PersistenceContext context) { + File path = getPath(context); + logPath("DELETE", path, context); + assertPathExists(path, context); + return path; + } + + public File getUpdatePath(PersistenceContext context) { + File path = getPath(context); + logPath("UPDATE", path, context); + assertPathExists(path, context); + return path; + } + + public File getReadPath(PersistenceContext context) { + File path = getPath(context); + logPath("READ", path, context); + if (!path.exists()) + return null; + return path; + } + + private File getPath(PersistenceContext context) { + File path = new File(getPathAsString(context.getType(), context.getSubType(), context.getId())); + return path; + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java index aaf424ef4..a5224b98a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java @@ -19,6 +19,18 @@ */ package ch.eitchnet.xmlpers.test; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.BOOK_ID; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE_INEXISTANT; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertBook; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertBookUpdated; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createBook; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateBook; + import java.io.File; import java.util.List; import java.util.Properties; @@ -40,7 +52,7 @@ import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; import ch.eitchnet.xmlpers.impl.XmlPersistenceHandlerImpl; import ch.eitchnet.xmlpers.test.impl.Book; import ch.eitchnet.xmlpers.test.impl.TestConstants; -import ch.eitchnet.xmlpers.test.model.Parameter; +import ch.eitchnet.xmlpers.test.model.ModelBuilder; import ch.eitchnet.xmlpers.test.model.Resource; /** @@ -49,28 +61,7 @@ import ch.eitchnet.xmlpers.test.model.Resource; public abstract class AbstractXmlPersistenceTest { protected static final Logger logger = LoggerFactory.getLogger(AbstractXmlPersistenceTest.class.getName()); - - protected static final String RES_TYPE = "@subType"; - protected static final String RES_TYPE_INEXISTANT = "@inexistant"; - protected static final String RES_NAME = "@name"; - protected static final String RES_NAME_MODIFIED = "@name_modified"; - protected static final String RES_ID = "@id"; - - protected static final String PARAM_TYPE = "@paramType"; - protected static final String PARAM_NAME = "@paramName"; - protected static final String PARAM_ID = "@paramId"; - protected static final String PARAM_VALUE_1 = "@paramValue1"; - protected static final String PARAM_VALUE_2 = "@paramValue2"; - - protected static final long BOOK_ID = 10L; - protected static final String BOOK_TITLE = "Nick Hornby"; - protected static final String BOOK_AUTHOR = "A long way down"; - protected static final String BOOK_PRESS_1 = "Some press"; - protected static final String BOOK_PRESS_2 = "Another press"; - protected static final double BOOK_PRICE = 45.55D; - protected static XmlPersistenceHandler persistenceHandler; - protected XmlPersistenceTransaction tx; /** @@ -141,7 +132,7 @@ public abstract class AbstractXmlPersistenceTest { assertBook(persistedBook); // update - persistedBook.setPress(BOOK_PRESS_2); + updateBook(persistedBook); this.tx.update(persistedBook); this.tx.commit(); @@ -236,8 +227,7 @@ public abstract class AbstractXmlPersistenceTest { assertResource(resource); // modify the instance - resource.setName(RES_NAME_MODIFIED); - resource.getParameterBy(PARAM_ID).setValue(PARAM_VALUE_2); + ModelBuilder.updateResource(resource); // update the instance this.tx.update(resource); @@ -379,60 +369,4 @@ public abstract class AbstractXmlPersistenceTest { this.tx.commit(); Assert.assertEquals("Expected size = 0, found: " + size, 0, size); } - - private Book createBook() { - Book book = new Book(BOOK_ID, BOOK_TITLE, BOOK_AUTHOR, BOOK_PRESS_1, BOOK_PRICE); - return book; - } - - private void assertBook(Book book) { - Assert.assertNotNull(book); - Assert.assertEquals(BOOK_ID, book.getId().longValue()); - Assert.assertEquals(BOOK_TITLE, book.getTitle()); - Assert.assertEquals(BOOK_AUTHOR, book.getAuthor()); - Assert.assertEquals(BOOK_PRESS_1, book.getPress()); - Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); - } - - private void assertBookUpdated(Book book) { - Assert.assertNotNull(book); - Assert.assertEquals(BOOK_ID, book.getId().longValue()); - Assert.assertEquals(BOOK_TITLE, book.getTitle()); - Assert.assertEquals(BOOK_AUTHOR, book.getAuthor()); - Assert.assertEquals(BOOK_PRESS_2, book.getPress()); - Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); - } - - private Resource createResource() { - Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); - Parameter param = new Parameter(PARAM_ID, PARAM_NAME, PARAM_TYPE, PARAM_VALUE_1); - resource.addParameter(param); - return resource; - } - - private void assertResource(Resource resource) { - Assert.assertNotNull(resource); - Assert.assertEquals(RES_ID, resource.getId()); - Assert.assertEquals(RES_NAME, resource.getName()); - Assert.assertEquals(RES_TYPE, resource.getType()); - Parameter param = resource.getParameterBy(PARAM_ID); - Assert.assertNotNull(param); - Assert.assertEquals(PARAM_ID, param.getId()); - Assert.assertEquals(PARAM_NAME, param.getName()); - Assert.assertEquals(PARAM_TYPE, param.getType()); - Assert.assertEquals(PARAM_VALUE_1, param.getValue()); - } - - private void assertResourceUpdated(Resource resource) { - Assert.assertNotNull(resource); - Assert.assertEquals(RES_ID, resource.getId()); - Assert.assertEquals(RES_NAME_MODIFIED, resource.getName()); - Assert.assertEquals(RES_TYPE, resource.getType()); - Parameter param = resource.getParameterBy(PARAM_ID); - Assert.assertNotNull(param); - Assert.assertEquals(PARAM_ID, param.getId()); - Assert.assertEquals(PARAM_NAME, param.getName()); - Assert.assertEquals(PARAM_TYPE, param.getType()); - Assert.assertEquals(PARAM_VALUE_2, param.getValue()); - } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index 9045ae228..2575aa3c1 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -52,6 +52,7 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.XmlHelper; +import ch.eitchnet.xmlpers.test.model.ModelBuilder; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; @@ -67,31 +68,7 @@ public class XmlTestMain { public static void main(String[] args) throws Exception { - res = new Resource(); - res.setId("id1"); - res.setName("name1"); - res.setType("type1"); - - Parameter param1 = new Parameter(); - param1.setId("paramId1"); - param1.setName("paramName1"); - param1.setType("paramType1"); - param1.setValue("paramValue1"); - res.addParameter(param1); - - Parameter param2 = new Parameter(); - param2.setId("paramId2"); - param2.setName("paramName2"); - param2.setType("paramType2"); - param2.setValue("paramValue2"); - res.addParameter(param2); - - Parameter param3 = new Parameter(); - param3.setId("paramId3"); - param3.setName("paramName3"); - param3.setType("paramType3"); - param3.setValue("paramValue3"); - res.addParameter(param3); + res = ModelBuilder.createResource(); logger.info("Writing Res:\n" + res); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java new file mode 100644 index 000000000..d5850ef4b --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import org.w3c.dom.Document; + +public interface DomParser { + + public T getObject(); + + public void setObject(T object); + + public Document toDom(); + + public void fromDom(Document document); +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java new file mode 100644 index 000000000..b0fadcc77 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.io.File; + +import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; + +public class FileDao { + private XmlPersistencePathBuilder pathBuilder; + + public FileDao(XmlPersistencePathBuilder pathBuilder) { + this.pathBuilder = pathBuilder; + } + + void performCreate(PersistenceContext context) { + File path = this.pathBuilder.getCreatePath(context); + FileIo fileIo = new FileIo(path); + fileIo.write(context); + } + + void performRead(PersistenceContext context) { + File path = this.pathBuilder.getReadPath(context); + if (path == null) { + context.setObject(null); + } else { + FileIo fileIo = new FileIo(path); + fileIo.read(context); + } + } + + void performUpdate(PersistenceContext context) { + File path = this.pathBuilder.getUpdatePath(context); + FileIo fileIo = new FileIo(path); + fileIo.write(context); + } + + void performDelete(PersistenceContext context) { + File path = this.pathBuilder.getDeletePath(context); + path.delete(); + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java new file mode 100644 index 000000000..e8f51a178 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.util.Properties; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.XmlIoMode; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class FileDaoTest { + + private static final String TEST_PATH = "target/dbTest"; + + private FileDao fileDao; + private Properties properties; + + @BeforeClass + public static void beforeClass() { + File file = new File(TEST_PATH).getAbsoluteFile(); + if (file.exists() && file.isDirectory()) + if (!FileHelper.deleteFiles(file.listFiles(), true)) + throw new RuntimeException("Could not clean up path " + file.getAbsolutePath()); + + if (!file.exists() && !file.mkdir()) + throw new RuntimeException("Failed to create path " + file); + + File domFile = new File(file, "dom"); + if (!domFile.mkdir()) + throw new RuntimeException("Failed to create path " + domFile); + + File saxFile = new File(file, "sax"); + if (!saxFile.mkdir()) + throw new RuntimeException("Failed to create path " + saxFile); + } + + @Before + public void setUp() { + this.properties = new Properties(); + this.properties.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); + } + + @Test + public void testCrudSax() { + this.properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, TEST_PATH + "/sax/"); + XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(this.properties); + this.fileDao = new FileDao(pathBuilder); + + Resource resource = createResource(); + assertResource(resource); + XmlIoMode ioMode = XmlIoMode.SAX; + PersistenceContext context = createPersistenceContext(resource, ioMode); + testCrud(context); + } + + @Test + public void testCrudDom() { + this.properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, TEST_PATH + "/dom/"); + XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(this.properties); + this.fileDao = new FileDao(pathBuilder); + + Resource resource = createResource(); + assertResource(resource); + XmlIoMode ioMode = XmlIoMode.DOM; + PersistenceContext context = createPersistenceContext(resource, ioMode); + testCrud(context); + } + + private void testCrud(PersistenceContext context) { + + this.fileDao.performCreate(context); + + context.setObject(null); + this.fileDao.performRead(context); + assertResource(context.getObject()); + + updateResource(context.getObject()); + this.fileDao.performUpdate(context); + + context.setObject(null); + this.fileDao.performRead(context); + assertResourceUpdated(context.getObject()); + + this.fileDao.performDelete(context); + + context.setObject(null); + this.fileDao.performRead(context); + assertNull(context.getObject()); + + context.setObject(createResource()); + this.fileDao.performCreate(context); + } + + private PersistenceContext createPersistenceContext(Resource resource, XmlIoMode ioMode) { + PersistenceContext context = new PersistenceContext(); + context.setId(resource.getId()); + context.setType(TestConstants.TYPE_RES); + context.setSubType(resource.getType()); + context.setObject(resource); + context.setIoMode(ioMode); + context.setParserFactory(new ResourceParserFactory()); + + return context; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java new file mode 100644 index 000000000..06caa3a9b --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.text.MessageFormat; + +import javanet.staxutils.IndentingXMLStreamWriter; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.stream.FactoryConfigurationError; +import javax.xml.stream.XMLOutputFactory; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.utils.exceptions.XmlException; +import ch.eitchnet.utils.helper.XmlHelper; +import ch.eitchnet.xmlpers.api.DomUtil; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; + +public class FileIo { + + private static final Logger logger = LoggerFactory.getLogger(FileIo.class); + + private final File path; + + public FileIo(File path) { + this.path = path; + } + + public void write(PersistenceContext context) { + switch (context.getIoMode()) { + case DOM: + writeDom(context); + break; + case SAX: + writeSax(context); + break; + case DEFAULT: + logger.info("Using default XML IO Handler SAX"); + writeSax(context); + break; + default: + String msg = "The Xml IO Mode {0} is not supported!"; + msg = MessageFormat.format(msg, context.getIoMode()); + throw new UnsupportedOperationException(msg); + } + } + + public void read(PersistenceContext context) { + switch (context.getIoMode()) { + case DOM: + readDom(context); + break; + case SAX: + readSax(context); + break; + case DEFAULT: + logger.info("Using default XML IO Handler SAX"); + readSax(context); + break; + default: + String msg = "The Xml IO Mode {0} is not supported!"; + msg = MessageFormat.format(msg, context.getIoMode()); + throw new UnsupportedOperationException(msg); + } + } + + private void writeSax(PersistenceContext context) { + + XMLStreamWriter writer = null; + try { + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + writer = factory.createXMLStreamWriter(new FileWriter(this.path)); + writer = new IndentingXMLStreamWriter(writer); + + // start document + writer.writeStartDocument("utf-8", "1.0"); + + // then delegate object writing to caller + XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); + SaxParser saxParser = context.getParserFactor().getSaxParser(); + saxParser.setObject(context.getObject()); + saxParser.write(xmlWriter); + + // and now end + writer.writeEndDocument(); + writer.flush(); + + } catch (FactoryConfigurationError | XMLStreamException | IOException e) { + if (this.path.exists()) + this.path.delete(); + throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); + } finally { + if (writer != null) { + try { + writer.close(); + } catch (Exception e) { + logger.error("Failed to close stream: " + e.getMessage()); + } + } + } + + logger.info("Wrote SAX to " + this.path.getAbsolutePath()); + } + + private void readSax(PersistenceContext context) { + + try { + + SAXParserFactory spf = SAXParserFactory.newInstance(); + SAXParser sp = spf.newSAXParser(); + + SaxParser saxParser = context.getParserFactor().getSaxParser(); + DefaultHandler defaultHandler = saxParser.getDefaultHandler(); + sp.parse(this.path, defaultHandler); + context.setObject(saxParser.getObject()); + + } catch (ParserConfigurationException | SAXException | IOException e) { + + throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); + } + + logger.info("SAX parsed file " + this.path.getAbsolutePath()); + } + + private void writeDom(PersistenceContext context) { + String lineSep = System.getProperty(XmlHelper.PROP_LINE_SEPARATOR); + try { + DomParser domParser = context.getParserFactor().getDomParser(); + domParser.setObject(context.getObject()); + Document document = domParser.toDom(); + String encoding = document.getInputEncoding(); + if (encoding == null || encoding.isEmpty()) { + // logger.info("No encoding passed. Using default encoding " + XmlHelper.DEFAULT_ENCODING); + encoding = XmlHelper.DEFAULT_ENCODING; + } + + if (!lineSep.equals("\n")) { + logger.info("Overriding line separator to \\n"); + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, "\n"); + } + + // Set up a transformer + TransformerFactory transfac = TransformerFactory.newInstance(); + Transformer transformer = transfac.newTransformer(); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.ENCODING, encoding); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); + // transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\t"); + + // Transform to file + StreamResult result = new StreamResult(this.path); + Source xmlSource = new DOMSource(document); + transformer.transform(xmlSource, result); + + logger.info("Wrote DOM to " + this.path.getAbsolutePath()); + + } catch (TransformerFactoryConfigurationError | TransformerException e) { + if (this.path.exists()) + this.path.delete(); + throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); + } finally { + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep); + } + } + + private void readDom(PersistenceContext context) { + try { + DocumentBuilder docBuilder = DomUtil.createDocumentBuilder(); + Document document = docBuilder.parse(this.path); + DomParser domParser = context.getParserFactor().getDomParser(); + domParser.fromDom(document); + context.setObject(domParser.getObject()); + } catch (SAXException | IOException e) { + throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); + } + + logger.info("DOM parsed file " + this.path.getAbsolutePath()); + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java new file mode 100644 index 000000000..c5bc9684d --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.util.List; +import java.util.Set; + +/** + * @author Robert von Burg + * + */ +public class ObjectDao { + + public void add(PersistenceContext context){} + + public void update(PersistenceContext context){} + + public void remove(PersistenceContext context){} + + public void removeById(PersistenceContext context){} + + public void removeAll(PersistenceContext context){} + + public T queryById(PersistenceContext context){return null;} + + public List queryAll(PersistenceContext context){return null;} + + public Set queryKeySet(PersistenceContext context){return null;} + + public long querySize(PersistenceContext context){return 0L;} + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java new file mode 100644 index 000000000..1a7bcc396 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +public interface ParserFactory { + + public DomParser getDomParser(); + + public SaxParser getSaxParser(); +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java new file mode 100644 index 000000000..1b0d1ad42 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import ch.eitchnet.xmlpers.api.XmlIoMode; + +public class PersistenceContext { + + private T object; + private String type; + private String subType; + private String id; + + private XmlIoMode ioMode; + private ParserFactory parserFactory; + + public String getType() { + return this.type; + } + + public void setType(String type) { + this.type = type; + } + + public String getSubType() { + return this.subType; + } + + public void setSubType(String subType) { + this.subType = subType; + } + + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public T getObject() { + return this.object; + } + + public void setObject(T object) { + this.object = object; + } + + public XmlIoMode getIoMode() { + return this.ioMode; + } + + public void setIoMode(XmlIoMode ioMode) { + this.ioMode = ioMode; + } + + public ParserFactory getParserFactor() { + return this.parserFactory; + } + + public void setParserFactory(ParserFactory parserFactory) { + this.parserFactory = parserFactory; + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java new file mode 100644 index 000000000..ea5ea516d --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import javax.xml.parsers.DocumentBuilder; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import ch.eitchnet.xmlpers.api.DomUtil; +import ch.eitchnet.xmlpers.test.model.Parameter; +import ch.eitchnet.xmlpers.test.model.Resource; + +public class ResourceDomParser implements DomParser { + + private Resource resource; + + @Override + public Resource getObject() { + return this.resource; + } + + @Override + public void setObject(Resource resource) { + this.resource = resource; + } + + @Override + public Document toDom() { + + DocumentBuilder documentBuilder = DomUtil.createDocumentBuilder(); + Document document = documentBuilder.getDOMImplementation().createDocument(null, null, null); + + Element element = document.createElement("Resource"); + document.appendChild(element); + + element.setAttribute("id", this.resource.getId()); + element.setAttribute("name", this.resource.getName()); + element.setAttribute("type", this.resource.getType()); + + for (String paramId : this.resource.getParameterKeySet()) { + Parameter param = this.resource.getParameterBy(paramId); + Element paramElement = document.createElement("Parameter"); + element.appendChild(paramElement); + + paramElement.setAttribute("id", param.getId()); + paramElement.setAttribute("name", param.getName()); + paramElement.setAttribute("type", param.getType()); + paramElement.setAttribute("value", param.getValue()); + } + + return document; + } + + @Override + public void fromDom(Document document) { + + Element rootElement = document.getDocumentElement(); + + String id = rootElement.getAttribute("id"); + String name = rootElement.getAttribute("name"); + String type = rootElement.getAttribute("type"); + + Resource resource = new Resource(id, name, type); + + NodeList children = rootElement.getChildNodes(); + for (int i = 0; i < children.getLength(); i++) { + Node item = children.item(i); + if (!item.getNodeName().equals("Parameter")) + continue; + + Element paramElement = (Element) item; + String paramId = paramElement.getAttribute("id"); + String paramName = paramElement.getAttribute("name"); + String paramType = paramElement.getAttribute("type"); + String paramValue = paramElement.getAttribute("value"); + + Parameter param = new Parameter(paramId, paramName, paramType, paramValue); + resource.addParameter(param); + } + + this.resource = resource; + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java new file mode 100644 index 000000000..041dcabc3 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import ch.eitchnet.xmlpers.test.model.Resource; + +public class ResourceParserFactory implements ParserFactory { + + @Override + public DomParser getDomParser() { + return new ResourceDomParser(); + } + + @Override + public SaxParser getSaxParser() { + return new ResourceSaxParser(); + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java new file mode 100644 index 000000000..8a1fa6335 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import javax.xml.stream.XMLStreamException; + +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.test.model.Parameter; +import ch.eitchnet.xmlpers.test.model.Resource; + +class ResourceSaxParser extends DefaultHandler implements SaxParser { + + private Resource resource; + + @Override + public Resource getObject() { + return this.resource; + } + + @Override + public void setObject(Resource object) { + this.resource = object; + } + + @Override + public DefaultHandler getDefaultHandler() { + return this; + } + + @Override + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + + writer.writeElement("Resource"); + writer.writeAttribute("id", this.resource.getId()); + writer.writeAttribute("name", this.resource.getName()); + writer.writeAttribute("type", this.resource.getType()); + for (String paramId : this.resource.getParameterKeySet()) { + Parameter param = this.resource.getParameterBy(paramId); + writer.writeElement("Parameter"); + writer.writeAttribute("id", param.getId()); + writer.writeAttribute("name", param.getName()); + writer.writeAttribute("type", param.getType()); + writer.writeAttribute("value", param.getValue()); + } + } + + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + + switch (qName) { + case "Resource": + String id = attributes.getValue("id"); + String name = attributes.getValue("name"); + String type = attributes.getValue("type"); + Resource resource = new Resource(id, name, type); + this.resource = resource; + break; + case "Parameter": + id = attributes.getValue("id"); + name = attributes.getValue("name"); + type = attributes.getValue("type"); + String value = attributes.getValue("value"); + Parameter param = new Parameter(id, name, type, value); + this.resource.addParameter(param); + break; + default: + throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); + } + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java new file mode 100644 index 000000000..31b311717 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import javax.xml.stream.XMLStreamException; + +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; + +public interface SaxParser { + + public T getObject(); + + public void setObject(T object); + + public DefaultHandler getDefaultHandler(); + + public void write(XmlPersistenceStreamWriter xmlWriter) throws XMLStreamException; +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java new file mode 100644 index 000000000..bc7fd5a4a --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.model; + +import org.junit.Assert; + +import ch.eitchnet.xmlpers.test.impl.Book; + +/** + * @author Robert von Burg + * + */ +public class ModelBuilder { + + public static final String RES_TYPE = "@subType"; + public static final String RES_TYPE_INEXISTANT = "@inexistant"; + public static final String RES_NAME = "@name"; + public static final String RES_NAME_MODIFIED = "@name_modified"; + public static final String RES_ID = "@id"; + + public static final String PARAM_TYPE = "@paramType"; + public static final String PARAM_NAME = "@paramName"; + public static final String PARAM_ID = "@paramId"; + public static final String PARAM_VALUE_1 = "@paramValue1"; + public static final String PARAM_VALUE_2 = "@paramValue2"; + + public static final long BOOK_ID = 10L; + public static final String BOOK_TITLE = "Nick Hornby"; + public static final String BOOK_AUTHOR = "A long way down"; + public static final String BOOK_PRESS_1 = "Some press"; + public static final String BOOK_PRESS_2 = "Another press"; + public static final double BOOK_PRICE = 45.55D; + + public static Resource createResource() { + Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); + Parameter param = new Parameter(PARAM_ID, PARAM_NAME, PARAM_TYPE, PARAM_VALUE_1); + resource.addParameter(param); + return resource; + } + + public static void updateResource(Resource resource) { + resource.setName(RES_NAME_MODIFIED); + resource.getParameterBy(PARAM_ID).setValue(PARAM_VALUE_2); + } + + public static Book createBook() { + Book book = new Book(BOOK_ID, BOOK_TITLE, BOOK_AUTHOR, BOOK_PRESS_1, BOOK_PRICE); + return book; + } + + public static void updateBook(Book book) { + book.setPress(BOOK_PRESS_2); + } + + public static void assertBook(Book book) { + Assert.assertNotNull(book); + Assert.assertEquals(BOOK_ID, book.getId().longValue()); + Assert.assertEquals(BOOK_TITLE, book.getTitle()); + Assert.assertEquals(BOOK_AUTHOR, book.getAuthor()); + Assert.assertEquals(BOOK_PRESS_1, book.getPress()); + Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); + } + + public static void assertBookUpdated(Book book) { + Assert.assertNotNull(book); + Assert.assertEquals(BOOK_ID, book.getId().longValue()); + Assert.assertEquals(BOOK_TITLE, book.getTitle()); + Assert.assertEquals(BOOK_AUTHOR, book.getAuthor()); + Assert.assertEquals(BOOK_PRESS_2, book.getPress()); + Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); + } + + public static void assertResource(Resource resource) { + Assert.assertNotNull(resource); + Assert.assertEquals(RES_ID, resource.getId()); + Assert.assertEquals(RES_NAME, resource.getName()); + Assert.assertEquals(RES_TYPE, resource.getType()); + Parameter param = resource.getParameterBy(PARAM_ID); + Assert.assertNotNull(param); + Assert.assertEquals(PARAM_ID, param.getId()); + Assert.assertEquals(PARAM_NAME, param.getName()); + Assert.assertEquals(PARAM_TYPE, param.getType()); + Assert.assertEquals(PARAM_VALUE_1, param.getValue()); + } + + public static void assertResourceUpdated(Resource resource) { + Assert.assertNotNull(resource); + Assert.assertEquals(RES_ID, resource.getId()); + Assert.assertEquals(RES_NAME_MODIFIED, resource.getName()); + Assert.assertEquals(RES_TYPE, resource.getType()); + Parameter param = resource.getParameterBy(PARAM_ID); + Assert.assertNotNull(param); + Assert.assertEquals(PARAM_ID, param.getId()); + Assert.assertEquals(PARAM_NAME, param.getName()); + Assert.assertEquals(PARAM_TYPE, param.getType()); + Assert.assertEquals(PARAM_VALUE_2, param.getValue()); + } +} From 403f59b82ca97f6238095fd05869b86d896c4d37 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 27 Sep 2013 20:30:55 +0200 Subject: [PATCH 26/87] [Project] fixed reference of src/main/ to /src/test --- .../java/ch/eitchnet/xmlpers/api}/PersistenceContext.java | 4 ++-- .../ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java | 2 +- .../java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java | 1 + .../ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java | 1 + .../java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java | 1 + .../java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java | 2 ++ 6 files changed, 8 insertions(+), 3 deletions(-) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/PersistenceContext.java (94%) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java similarity index 94% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java rename to src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index 1b0d1ad42..bf132775f 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -19,9 +19,9 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; -import ch.eitchnet.xmlpers.api.XmlIoMode; +import ch.eitchnet.xmlpers.test.impl.rewrite.ParserFactory; public class PersistenceContext { diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java index 3e0c84535..43b0f9aff 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java @@ -29,9 +29,9 @@ import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.PropertiesHelper; import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.test.impl.rewrite.PersistenceContext; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java index b0fadcc77..8774d2549 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java @@ -23,6 +23,7 @@ package ch.eitchnet.xmlpers.test.impl.rewrite; import java.io.File; +import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; public class FileDao { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java index e8f51a178..11ac0036d 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java @@ -35,6 +35,7 @@ import org.junit.BeforeClass; import org.junit.Test; import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.api.XmlIoMode; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java index 06caa3a9b..759b55cec 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java @@ -54,6 +54,7 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.XmlHelper; import ch.eitchnet.xmlpers.api.DomUtil; +import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.api.XmlPersistenceException; import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java index c5bc9684d..cb5a9581b 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java @@ -24,6 +24,8 @@ package ch.eitchnet.xmlpers.test.impl.rewrite; import java.util.List; import java.util.Set; +import ch.eitchnet.xmlpers.api.PersistenceContext; + /** * @author Robert von Burg * From bacc6d72fd918f45dbfe16369108637fb5ea6ef1 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 27 Sep 2013 20:40:02 +0200 Subject: [PATCH 27/87] [Project] fixed /src/main to /src/test reference --- .../java/ch/eitchnet/xmlpers/api}/DomParser.java | 2 +- .../java/ch/eitchnet/xmlpers/api}/ParserFactory.java | 3 ++- src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java | 1 - .../java/ch/eitchnet/xmlpers/api}/SaxParser.java | 2 +- .../java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java | 2 ++ .../eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java | 1 + .../xmlpers/test/impl/rewrite/ResourceParserFactory.java | 3 +++ .../eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java | 1 + 8 files changed, 11 insertions(+), 4 deletions(-) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/DomParser.java (95%) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/ParserFactory.java (94%) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/SaxParser.java (95%) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java b/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java similarity index 95% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java rename to src/main/java/ch/eitchnet/xmlpers/api/DomParser.java index d5850ef4b..1c78ff5d3 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DomParser.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; import org.w3c.dom.Document; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java similarity index 94% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java rename to src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java index 1a7bcc396..5a4d8a2ec 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ParserFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java @@ -19,7 +19,8 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; + public interface ParserFactory { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index bf132775f..17e49e9bb 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -21,7 +21,6 @@ */ package ch.eitchnet.xmlpers.api; -import ch.eitchnet.xmlpers.test.impl.rewrite.ParserFactory; public class PersistenceContext { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java similarity index 95% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java rename to src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java index 31b311717..9fc8d1dd9 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/SaxParser.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; import javax.xml.stream.XMLStreamException; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java index 759b55cec..f23a3361d 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java @@ -53,8 +53,10 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.XmlHelper; +import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.DomUtil; import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.SaxParser; import ch.eitchnet.xmlpers.api.XmlPersistenceException; import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java index ea5ea516d..869664596 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java @@ -28,6 +28,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.DomUtil; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java index 041dcabc3..0e062b1ae 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java @@ -21,6 +21,9 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; +import ch.eitchnet.xmlpers.api.DomParser; +import ch.eitchnet.xmlpers.api.ParserFactory; +import ch.eitchnet.xmlpers.api.SaxParser; import ch.eitchnet.xmlpers.test.model.Resource; public class ResourceParserFactory implements ParserFactory { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java index 8a1fa6335..bf69b3e20 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java @@ -27,6 +27,7 @@ import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; +import ch.eitchnet.xmlpers.api.SaxParser; import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; From f81dec893979662ca3855a5cc263e7d5667d6a12 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 6 Oct 2013 12:32:57 +0200 Subject: [PATCH 28/87] [New] working on rewrite --- .../xmlpers/api/PersistenceContext.java | 17 ++ .../xmlpers/api/XmlPersistenceConstants.java | 6 +- .../impl/XmlPersistenceTransactionImpl.java | 5 +- .../test/impl/rewrite/BookDomParser.java | 59 +++++++ .../test/impl/rewrite/BookParserFactory.java | 45 +++++ .../test/impl/rewrite/BookSaxParser.java | 62 +++++++ .../DefaultPersistenceTransaction.java | 148 +++++++++++++++++ .../rewrite/DefaultXmlPersistenceManager.java | 63 +++++++ .../test/impl/rewrite/MetadataDao.java | 84 ++++++++++ .../xmlpers/test/impl/rewrite/ObjectDao.java | 155 ++++++++++++++++-- .../test/impl/rewrite/ObjectDaoTest.java | 81 +++++++++ .../rewrite/PersistenceContextFactory.java | 39 +++++ .../impl/rewrite/PersistenceTransaction.java | 39 +++++ .../TestPersistenceContextFactory.java | 101 ++++++++++++ .../impl/rewrite/XmlPersistenceManager.java | 32 ++++ .../rewrite/XmlPersistenceManagerLoader.java | 38 +++++ 16 files changed, 958 insertions(+), 16 deletions(-) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index 17e49e9bb..e50021892 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -21,6 +21,7 @@ */ package ch.eitchnet.xmlpers.api; +import ch.eitchnet.utils.helper.StringHelper; public class PersistenceContext { @@ -79,4 +80,20 @@ public class PersistenceContext { public void setParserFactory(ParserFactory parserFactory) { this.parserFactory = parserFactory; } + + public boolean hasSubType() { + return !StringHelper.isEmpty(this.subType); + } + + @Override + public PersistenceContext clone() { + PersistenceContext clone = new PersistenceContext<>(); + clone.type = this.type; + clone.subType = this.subType; + clone.id = this.id; + clone.ioMode = this.ioMode; + clone.parserFactory = this.parserFactory; + clone.object = this.object; + return clone; + } } \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java index 3fd3266e4..f1968952e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java @@ -28,8 +28,8 @@ package ch.eitchnet.xmlpers.api; public class XmlPersistenceConstants { private static final String PROP_PREFIX = "ch.eitchnet.xmlpers."; - public static final String PROP_VERBOSE = "ch.eitchnet.xmlpers." + "verbose"; - public static final String PROP_BASEPATH = "ch.eitchnet.xmlpers." + "basePath"; - public static final String PROP_DAO_FACTORY_CLASS = "ch.eitchnet.xmlpers." + "daoFactoryClass"; + public static final String PROP_VERBOSE = PROP_PREFIX + "verbose"; + public static final String PROP_BASEPATH = PROP_PREFIX + "basePath"; + public static final String PROP_DAO_FACTORY_CLASS = PROP_PREFIX + "daoFactoryClass"; public static final String PROP_XML_IO_MOD = PROP_PREFIX + "ioMode"; } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java index a8cdbb7ac..6b27aa0bd 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java @@ -25,6 +25,7 @@ import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.objectfilter.ObjectFilter; import ch.eitchnet.xmlpers.api.XmlPersistenceDao; import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; @@ -126,6 +127,7 @@ public class XmlPersistenceTransactionImpl implements XmlPersistenceTransaction public void commit() { try { + long start = System.nanoTime(); if (this.verbose) XmlPersistenceTransactionImpl.logger.info("Committing TX..."); Set keySet = this.objectFilter.keySet(); @@ -178,7 +180,8 @@ public class XmlPersistenceTransactionImpl implements XmlPersistenceTransaction } } - XmlPersistenceTransactionImpl.logger.info("Completed TX"); + long end = System.nanoTime(); + logger.info("Completed TX in " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ } finally { // clean up diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java new file mode 100644 index 000000000..35c584904 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import org.w3c.dom.Document; + +import ch.eitchnet.xmlpers.api.DomParser; +import ch.eitchnet.xmlpers.test.impl.Book; + +/** + * @author Robert von Burg + * + */ +public class BookDomParser implements DomParser { + + @Override + public Book getObject() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setObject(Book object) { + // TODO Auto-generated method stub + + } + + @Override + public Document toDom() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void fromDom(Document document) { + // TODO Auto-generated method stub + + } + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java new file mode 100644 index 000000000..01ab00143 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import ch.eitchnet.xmlpers.api.DomParser; +import ch.eitchnet.xmlpers.api.ParserFactory; +import ch.eitchnet.xmlpers.api.SaxParser; +import ch.eitchnet.xmlpers.test.impl.Book; + +/** + * @author Robert von Burg + * + */ +public class BookParserFactory implements ParserFactory { + + @Override + public DomParser getDomParser() { + return new BookDomParser(); + } + + @Override + public SaxParser getSaxParser() { + return new BookSaxParser(); + } + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java new file mode 100644 index 000000000..ab4d012f5 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import javax.xml.stream.XMLStreamException; + +import org.xml.sax.helpers.DefaultHandler; + +import ch.eitchnet.xmlpers.api.SaxParser; +import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.test.impl.Book; + +/** + * @author Robert von Burg + * + */ +public class BookSaxParser implements SaxParser { + + @Override + public Book getObject() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void setObject(Book object) { + // TODO Auto-generated method stub + + } + + @Override + public DefaultHandler getDefaultHandler() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void write(XmlPersistenceStreamWriter xmlWriter) throws XMLStreamException { + // TODO Auto-generated method stub + + } + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java new file mode 100644 index 000000000..27bdaf396 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.util.List; +import java.util.Set; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.utils.objectfilter.ObjectFilter; +import ch.eitchnet.xmlpers.api.PersistenceContext; + +/** + * @author Robert von Burg + * + */ +public class DefaultPersistenceTransaction implements PersistenceTransaction { + + private static final Logger logger = LoggerFactory.getLogger(DefaultPersistenceTransaction.class); + + private final FileDao fileDao; + private final ObjectDao objectDao; + private final MetadataDao metadataDao; + private final ObjectFilter objectFilter; + private final boolean verbose; + + private boolean closed; + + public DefaultPersistenceTransaction(FileDao fileDao, boolean verbose) { + this.fileDao = fileDao; + this.verbose = verbose; + this.objectFilter = new ObjectFilter(); + this.objectDao = new ObjectDao(this, this.fileDao, this.objectFilter); + this.metadataDao = new MetadataDao(this, this.fileDao); + } + + @Override + public ObjectDao getObjectDao() { + return this.objectDao; + } + + @Override + public MetadataDao getMetadataDao() { + return this.metadataDao; + } + + @Override + public void rollback() { + this.closed = true; + this.objectDao.rollback(); + this.objectFilter.clearCache(); + } + + @Override + public void commit(PersistenceContextFactory persistenceContextFactory) { + + try { + + long start = System.nanoTime(); + if (this.verbose) + logger.info("Committing TX..."); //$NON-NLS-1$ + + Set keySet = this.objectFilter.keySet(); + if (keySet.isEmpty()) + return; + for (String key : keySet) { + + List removed = this.objectFilter.getRemoved(key); + if (removed.isEmpty()) { + if (this.verbose) + logger.info("No objects removed in this tx."); //$NON-NLS-1$ + } else { + if (this.verbose) + logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$ + + for (Object object : removed) { + PersistenceContext context = persistenceContextFactory.createPersistenceContext(object); + this.fileDao.performDelete(context); + } + } + + List updated = this.objectFilter.getUpdated(key); + if (updated.isEmpty()) { + if (this.verbose) + logger.info("No objects updated in this tx."); //$NON-NLS-1$ + } else { + if (this.verbose) + logger.info(updated.size() + " objects updated in this tx."); //$NON-NLS-1$ + + for (Object object : updated) { + + PersistenceContext context = persistenceContextFactory.createPersistenceContext(object); + this.fileDao.performUpdate(context); + } + } + + List added = this.objectFilter.getAdded(key); + if (added.isEmpty()) { + if (this.verbose) + logger.info("No objects added in this tx."); //$NON-NLS-1$ + } else { + if (this.verbose) + logger.info(added.size() + " objects added in this tx."); //$NON-NLS-1$ + + for (Object object : added) { + + PersistenceContext context = persistenceContextFactory.createPersistenceContext(object); + this.fileDao.performCreate(context); + } + } + } + + long end = System.nanoTime(); + logger.info("Completed TX in " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ + + } finally { + // clean up + this.objectFilter.clearCache(); + this.closed = true; + } + } + + @Override + public boolean isClosed() { + return this.closed; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java new file mode 100644 index 000000000..eb5963ff2 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.impl.XmlPersistenceHandlerImpl; + +/** + * @author Robert von Burg + * + */ +public class DefaultXmlPersistenceManager implements XmlPersistenceManager { + + protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandlerImpl.class); + + protected boolean initialized; + protected boolean verbose; + + public void initialize(Properties properties) { + if (this.initialized) + throw new IllegalStateException("Already initialized!"); //$NON-NLS-1$ + + // get properties + String context = XmlPersistenceHandlerImpl.class.getSimpleName(); + boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, + Boolean.FALSE).booleanValue(); + + this.verbose = verbose; + } + + @Override + public PersistenceTransaction openTx() { + + PersistenceTransaction tx = null; + + return tx; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java new file mode 100644 index 000000000..617057bda --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.util.Set; + +/** + * @author Robert von Burg + * + */ +public class MetadataDao { + + private final DefaultPersistenceTransaction tx; + private final FileDao fileDao; + + public MetadataDao(DefaultPersistenceTransaction tx, FileDao fileDao) { + this.tx = tx; + this.fileDao = fileDao; + } + + public Set queryTypeSet() { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public Set queryTypeSet(String type) { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public Set queryKeySet(String type) { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public Set queryKeySet(String type, String subType) { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public long queryTypeSize() { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public long querySubTypeSize(String type) { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public long querySize(String type) { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + public long querySize(String type, String subType) { + assertNotClosed(); + throw new UnsupportedOperationException("Not yet implemented!"); + } + + private void assertNotClosed() { + if (this.tx.isClosed()) + throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java index cb5a9581b..6f554efcd 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java @@ -21,33 +21,164 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; +import java.text.MessageFormat; +import java.util.ArrayList; import java.util.List; import java.util.Set; +import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.utils.objectfilter.ObjectFilter; import ch.eitchnet.xmlpers.api.PersistenceContext; /** * @author Robert von Burg - * + * */ -public class ObjectDao { - - public void add(PersistenceContext context){} +public class ObjectDao { - public void update(PersistenceContext context){} + private final PersistenceTransaction tx; + private final ObjectFilter objectFilter; + private final FileDao fileDao; + private boolean closed; - public void remove(PersistenceContext context){} + public ObjectDao(PersistenceTransaction tx, FileDao fileDao, ObjectFilter objectFilter) { + this.tx = tx; + this.fileDao = fileDao; + this.objectFilter = objectFilter; + } - public void removeById(PersistenceContext context){} + public void add(Object object) { + assertNotClosed(); + assertNotNull(object); + this.objectFilter.add(object); + } - public void removeAll(PersistenceContext context){} + public void update(Object object) { + assertNotClosed(); + assertNotNull(object); + this.objectFilter.update(object); + } - public T queryById(PersistenceContext context){return null;} + public void remove(Object object) { + assertNotClosed(); + assertNotNull(object); + this.objectFilter.remove(object); + } - public List queryAll(PersistenceContext context){return null;} + public void removeById(PersistenceContext context) { + assertNotClosed(); + assertHasType(context); + assertHasId(context); + this.objectFilter.remove(context.clone()); + } - public Set queryKeySet(PersistenceContext context){return null;} + public void removeAll(PersistenceContext context) { + assertNotClosed(); + assertHasType(context); - public long querySize(PersistenceContext context){return 0L;} + Set keySet = queryKeySet(context); + for (String id : keySet) { + PersistenceContext clone = context.clone(); + clone.setId(id); + this.objectFilter.remove(clone); + } + } + public T queryById(PersistenceContext context) { + assertNotClosed(); + assertHasType(context); + assertHasId(context); + this.fileDao.performRead(context); + return context.getObject(); + } + + public List queryAll(PersistenceContext context) { + assertNotClosed(); + assertHasType(context); + + MetadataDao metadataDao = this.tx.getMetadataDao(); + Set keySet; + if (context.hasSubType()) + keySet = metadataDao.queryKeySet(context.getType(), context.getSubType()); + else + keySet = metadataDao.queryKeySet(context.getType()); + + List result = new ArrayList<>(); + PersistenceContext readContext = context.clone(); + for (String id : keySet) { + readContext.setId(id); + this.fileDao.performRead(readContext); + assertObjectRead(readContext); + result.add(readContext.getObject()); + } + + return result; + } + + public Set queryKeySet(PersistenceContext context) { + assertNotClosed(); + assertHasType(context); + + assertNotClosed(); + assertHasType(context); + + MetadataDao metadataDao = this.tx.getMetadataDao(); + Set keySet; + if (context.hasSubType()) + keySet = metadataDao.queryKeySet(context.getType(), context.getSubType()); + else + keySet = metadataDao.queryKeySet(context.getType()); + + return keySet; + } + + public long querySize(PersistenceContext context) { + assertNotClosed(); + assertHasType(context); + + assertNotClosed(); + assertHasType(context); + + MetadataDao metadataDao = this.tx.getMetadataDao(); + long size; + if (context.hasSubType()) + size = metadataDao.querySize(context.getType(), context.getSubType()); + else + size = metadataDao.querySize(context.getType()); + + return size; + } + + public void rollback() { + this.objectFilter.clearCache(); + this.closed = true; + } + + private void assertNotNull(Object object) { + if (object == null) + throw new RuntimeException("Object may not be null!"); //$NON-NLS-1$ + } + + private void assertObjectRead(PersistenceContext context) { + if (context.getObject() == null) { + String msg = "Failed to read object with for {0} / {1} / {2}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId()); + throw new RuntimeException(msg); + } + } + + private void assertHasType(PersistenceContext context) { + if (StringHelper.isEmpty(context.getType())) + throw new RuntimeException("Type is always needed on a persistence context!"); //$NON-NLS-1$ + } + + private void assertHasId(PersistenceContext context) { + if (StringHelper.isEmpty(context.getId())) + throw new RuntimeException("Id is not set on persistence context!"); //$NON-NLS-1$ + } + + private void assertNotClosed() { + if (this.closed || this.tx.isClosed()) + throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); //$NON-NLS-1$ + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java new file mode 100644 index 000000000..07c21d77d --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; + +import java.util.Properties; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class ObjectDaoTest { + + private static final Logger logger = LoggerFactory.getLogger(ObjectDaoTest.class); + + private PersistenceContextFactory persistenceContextFactory; + private XmlPersistenceManager persistenceManager; + private PersistenceTransaction tx; + + @BeforeClass + public static void beforeClass() { + } + + @Before + public void setUp() { + + this.persistenceContextFactory = new TestPersistenceContextFactory(); + + Properties properties = new Properties(); + this.persistenceManager = XmlPersistenceManagerLoader.load(properties); + } + + @After + public void tearDown() { + if (this.tx != null) { + this.tx.rollback(); + } + } + + @Test + @Ignore + public void testObjectDao() { + + this.tx = this.persistenceManager.openTx(); + + Resource resource = createResource(); + + this.tx.getObjectDao().add(resource); + this.tx.commit(this.persistenceContextFactory); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java new file mode 100644 index 000000000..8c299be3b --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import ch.eitchnet.xmlpers.api.PersistenceContext; + +/** + * @author Robert von Burg + * + */ +public interface PersistenceContextFactory { + + public PersistenceContext createPersistenceContext(String type, String subType, String id); + + public PersistenceContext createPersistenceContext(String type, String subType); + + public PersistenceContext createPersistenceContext(String type); + + public PersistenceContext createPersistenceContext(T t); +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java new file mode 100644 index 000000000..388b6a0f9 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +/** + * @author Robert von Burg + * + */ +public interface PersistenceTransaction { + + public void commit(PersistenceContextFactory persistenceContextFactory); + + public void rollback(); + + public boolean isClosed(); + + public ObjectDao getObjectDao(); + + public MetadataDao getMetadataDao(); +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java new file mode 100644 index 000000000..f83531824 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import ch.eitchnet.xmlpers.api.ParserFactory; +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.test.impl.Book; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class TestPersistenceContextFactory implements PersistenceContextFactory { + + @Override + public PersistenceContext createPersistenceContext(String type, String subType, String id) { + return buildPersistenceContext(type, subType, id); + } + + @Override + public PersistenceContext createPersistenceContext(String type, String subType) { + return buildPersistenceContext(type, subType, null); + } + + @Override + public PersistenceContext createPersistenceContext(String type) { + return buildPersistenceContext(type, null, null); + } + + @Override + public PersistenceContext createPersistenceContext(T t) { + if (t == null) + throw new RuntimeException("T may not be null!"); + + PersistenceContext context; + + if (t instanceof Resource) { + Resource resource = (Resource) t; + context = buildPersistenceContext(TestConstants.TYPE_RES, resource.getType(), resource.getId()); + } else if (t instanceof Book) { + context = buildPersistenceContext(TestConstants.TYPE_BOOK, null, ((Book) t).getId().toString()); + } else { + throw new UnsupportedOperationException("Handling of " + t.getClass().getName() + " is not implemented!"); + } + + context.setObject(t); + return context; + } + + private PersistenceContext buildPersistenceContext(String type, String subType, String id) { + + PersistenceContext context = new PersistenceContext<>(); + + context.setType(type); + context.setSubType(subType); + context.setId(id); + + context.setParserFactory(this. getParserFactoryInstance(type)); + + return context; + } + + /** + * @param type + * @return + */ + @SuppressWarnings("unchecked") + private ParserFactory getParserFactoryInstance(String type) { + + ParserFactory parserFactory; + if (type.equals(TestConstants.TYPE_RES)) + parserFactory = (ParserFactory) new ResourceParserFactory(); + else if (type.equals(TestConstants.TYPE_BOOK)) + parserFactory = (ParserFactory) new BookParserFactory(); + else + throw new UnsupportedOperationException("No ParserFactory can be returned for type " + type); + + return parserFactory; + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java new file mode 100644 index 000000000..e57d02ca8 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + + +/** + * @author Robert von Burg + * + */ +public interface XmlPersistenceManager { + + public PersistenceTransaction openTx(); +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java new file mode 100644 index 000000000..4fbc34527 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.util.Properties; + +/** + * @author Robert von Burg + * + */ +public class XmlPersistenceManagerLoader { + + public static XmlPersistenceManager load(Properties properties) { + + DefaultXmlPersistenceManager persistenceManager = new DefaultXmlPersistenceManager(); + persistenceManager.initialize(properties); + return persistenceManager; + } +} From ca9c21e0e2604189f2ff086826e9ed6ca0f7ce11 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 6 Oct 2013 18:42:55 +0200 Subject: [PATCH 29/87] [New] rewrite is now working as test. --- .../xmlpers/api/PersistenceContext.java | 4 + .../impl/XmlPersistencePathBuilder.java | 92 ++++++++------- .../xmlpers/test/impl/BookSaxDao.java | 4 + .../xmlpers/test/impl/ResourceSaxDao.java | 4 + .../DefaultPersistenceTransaction.java | 36 ++++-- .../rewrite/DefaultXmlPersistenceManager.java | 8 +- .../test/impl/rewrite/MetadataDao.java | 2 +- .../xmlpers/test/impl/rewrite/ObjectDao.java | 2 +- .../test/impl/rewrite/ObjectDaoTest.java | 111 +++++++++++++++--- .../rewrite/PersistenceContextFactory.java | 8 +- .../impl/rewrite/PersistenceTransaction.java | 10 +- .../test/impl/rewrite/ResourceSaxParser.java | 2 +- .../TestPersistenceContextFactory.java | 37 +++--- 13 files changed, 225 insertions(+), 95 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index e50021892..7ce34f7c7 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -32,6 +32,10 @@ public class PersistenceContext { private XmlIoMode ioMode; private ParserFactory parserFactory; + + public PersistenceContext() { + this.ioMode = XmlIoMode.DEFAULT; + } public String getType() { return this.type; diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java index 43b0f9aff..51d6f1791 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java @@ -37,16 +37,16 @@ import ch.eitchnet.xmlpers.api.XmlPersistenceException; * @author Robert von Burg */ public class XmlPersistencePathBuilder { + private static final String SLASH = "/"; //$NON-NLS-1$ + private static final Logger logger = LoggerFactory.getLogger(XmlPersistencePathBuilder.class); - public static final String FILE_EXT = ".xml"; + public static final String FILE_EXT = ".xml"; //$NON-NLS-1$ public static final int EXT_LENGTH = XmlPersistencePathBuilder.FILE_EXT.length(); private final boolean verbose; private final String basePath; - private File path; - public XmlPersistencePathBuilder(Properties properties) { // get properties @@ -59,10 +59,10 @@ public class XmlPersistencePathBuilder { // validate base path exists and is writable File basePathF = new File(basePath); if (!basePathF.exists()) - throw new XmlPersistenceException(MessageFormat.format("The database store path does not exist at {0}", + throw new XmlPersistenceException(MessageFormat.format("The database store path does not exist at {0}", //$NON-NLS-1$ basePathF.getAbsolutePath())); if (!basePathF.canWrite()) - throw new XmlPersistenceException(MessageFormat.format("The database store path is not writeable at {0}", + throw new XmlPersistenceException(MessageFormat.format("The database store path is not writeable at {0}", //$NON-NLS-1$ basePathF.getAbsolutePath())); // we want a clean base path @@ -71,14 +71,14 @@ public class XmlPersistencePathBuilder { canonicalBasePath = basePathF.getCanonicalPath(); } catch (IOException e) { throw new XmlPersistenceException( - MessageFormat.format("Failed to build canonical path from {0}", basePath), e); + MessageFormat.format("Failed to build canonical path from {0}", basePath), e); //$NON-NLS-1$ } // this.basePathF = basePathF; this.basePath = canonicalBasePath; this.verbose = verbose; - logger.info(MessageFormat.format("Using base path {0}", basePath)); + logger.info(MessageFormat.format("Using base path {0}", this.basePath)); //$NON-NLS-1$ } String getFilename(String id) { @@ -94,15 +94,15 @@ public class XmlPersistencePathBuilder { String getPathAsString(String type, String subType, String id) { StringBuilder sb = new StringBuilder(this.basePath); if (!StringHelper.isEmpty(type)) { - sb.append("/"); + sb.append(SLASH); sb.append(type); } if (!StringHelper.isEmpty(subType)) { - sb.append("/"); + sb.append(SLASH); sb.append(subType); } if (!StringHelper.isEmpty(id)) { - sb.append("/"); + sb.append(SLASH); sb.append(getFilename(id)); } @@ -116,11 +116,11 @@ public class XmlPersistencePathBuilder { File path = new File(getPathAsString(type, null, id)); // assert path exists - String msg = "Persistence unit already exists for {0} / {1} at {2}"; + String msg = "Persistence unit already exists for {0} / {1} at {2}"; //$NON-NLS-1$ assertPathNotExists(path, msg, type, id, path.getAbsolutePath()); // check if parent path exists - msg = "Could not create parent path for {0} / {1} at {2}"; + msg = "Could not create parent path for {0} / {1} at {2}"; //$NON-NLS-1$ createMissingParents(path, msg, type, id, path.getAbsolutePath()); return path; @@ -134,11 +134,11 @@ public class XmlPersistencePathBuilder { File path = new File(getPathAsString(type, subType, id)); // assert path exists - String msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; + String msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ assertPathNotExists(path, msg, type, subType, id, path.getAbsolutePath()); // check if parent path exists - msg = "Could not create parent path for {0} / {1} / {2} at {3}"; + msg = "Could not create parent path for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ createMissingParents(path, msg, type, subType, id, path.getAbsolutePath()); return path; @@ -149,7 +149,7 @@ public class XmlPersistencePathBuilder { assertId(id); File path = new File(getPathAsString(type, null, id)); if (this.verbose) { - String msg = "Query path for {0} / {1} is {2}..."; + String msg = "Query path for {0} / {1} is {2}..."; //$NON-NLS-1$ logger.info(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } return path; @@ -161,7 +161,7 @@ public class XmlPersistencePathBuilder { assertId(id); File path = new File(getPathAsString(type, subType, id)); if (this.verbose) { - String msg = "Query path for {0} / {1} / {2} is {3}..."; + String msg = "Query path for {0} / {1} / {2} is {3}..."; //$NON-NLS-1$ logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); } return path; @@ -174,7 +174,7 @@ public class XmlPersistencePathBuilder { File path = new File(getPathAsString(type, null, id)); if (!path.exists()) { - String msg = "Persistence unit does not exist for {0} / {1} at {2}"; + String msg = "Persistence unit does not exist for {0} / {1} at {2}"; //$NON-NLS-1$ throw new XmlPersistenceException(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } @@ -189,7 +189,7 @@ public class XmlPersistencePathBuilder { File path = new File(getPathAsString(type, subType, id)); if (!path.exists()) { - String msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; + String msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); } @@ -202,12 +202,12 @@ public class XmlPersistencePathBuilder { File path = new File(getPathAsString(type, null, id)); if (!path.exists()) { - String msg = "No Persistence units exist for {0} / {1} at {2}"; + String msg = "No Persistence units exist for {0} / {1} at {2}"; //$NON-NLS-1$ throw new XmlPersistenceException(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } if (this.verbose) { - String msg = "Remove path for {0} / {1} is {2}..."; + String msg = "Remove path for {0} / {1} is {2}..."; //$NON-NLS-1$ logger.info(MessageFormat.format(msg, type, id, path.getAbsolutePath())); } @@ -221,12 +221,12 @@ public class XmlPersistencePathBuilder { File path = new File(getPathAsString(type, subType, id)); if (!path.exists()) { - String msg = "Persistence unit for {0} / {1} / {2} does not exist at {3}"; + String msg = "Persistence unit for {0} / {1} / {2} does not exist at {3}"; //$NON-NLS-1$ throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); } if (this.verbose) { - String msg = "Remove path for {0} / {1} / {2} is {3}..."; + String msg = "Remove path for {0} / {1} / {2} is {3}..."; //$NON-NLS-1$ logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); } @@ -241,7 +241,7 @@ public class XmlPersistencePathBuilder { assertType(type); File path = new File(getPathAsString(type, null, null)); if (this.verbose) { - String msg = "Query path for {0} is {1}..."; + String msg = "Query path for {0} is {1}..."; //$NON-NLS-1$ logger.info(MessageFormat.format(msg, type, path.getAbsolutePath())); } return path; @@ -252,7 +252,7 @@ public class XmlPersistencePathBuilder { assertSubType(subType); File path = new File(getPathAsString(type, subType, null)); if (this.verbose) { - String msg = "Query path for {0} / {1} is {2}..."; + String msg = "Query path for {0} / {1} is {2}..."; //$NON-NLS-1$ logger.info(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); } return path; @@ -261,24 +261,26 @@ public class XmlPersistencePathBuilder { private void assertId(String id) { if (StringHelper.isEmpty(id)) throw new XmlPersistenceException( - "The id can not be empty! An object must always be handled with at least the type and id!"); + "The id can not be empty! An object must always be handled with at least the type and id!"); //$NON-NLS-1$ } private void assertType(String type) { if (StringHelper.isEmpty(type)) throw new XmlPersistenceException( - "The type can not be empty! An object must always be handled with at least the type and id!"); + "The type can not be empty! An object must always be handled with at least the type and id!"); //$NON-NLS-1$ } private void assertSubType(String subType) { if (StringHelper.isEmpty(subType)) - throw new XmlPersistenceException("The subType can not be empty!"); + throw new XmlPersistenceException("The subType can not be empty!"); //$NON-NLS-1$ } private void assertFilename(String filename) { - if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') - throw new XmlPersistenceException("The filename does not have a . at index " - + (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); + if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') { + String msg = "The filename does not have a . (dot) at index {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); + throw new XmlPersistenceException(msg); + } } private void assertPathNotExists(File path, String msg, Object... args) { @@ -298,10 +300,10 @@ public class XmlPersistencePathBuilder { if (this.verbose) { String msg; if (StringHelper.isEmpty(context.getSubType())) { - msg = "Path for operation {0} for {1} / {2} / is at {3}"; + msg = "Path for operation {0} for {1} / {2} / is at {3}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, operation, context.getType(), context.getId(), path.getAbsolutePath()); } else { - msg = "Path for operation {0} for {1} / {2} / {3} / is at {4}"; + msg = "Path for operation {0} for {1} / {2} / {3} / is at {4}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, operation, context.getType(), context.getSubType(), context.getId(), path.getAbsolutePath()); } @@ -313,14 +315,14 @@ public class XmlPersistencePathBuilder { if (!parentFile.exists() && !parentFile.mkdirs()) { String msg; if (StringHelper.isEmpty(context.getSubType())) { - msg = "Could not create parent path for {0} / {1} / at {2}"; + msg = "Could not create parent path for {0} / {1} / at {2}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); } else { - msg = "Could not create parent path for {0} / {1} / {2} at {3}"; + msg = "Could not create parent path for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), path.getAbsolutePath()); } - + throw new XmlPersistenceException(msg); } } @@ -329,14 +331,14 @@ public class XmlPersistencePathBuilder { if (!path.exists()) { String msg; if (StringHelper.isEmpty(context.getSubType())) { - msg = "Persistence unit does not exist for {0} / {1} at {2}"; + msg = "Persistence unit does not exist for {0} / {1} at {2}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); } else { - msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; + msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), path.getAbsolutePath()); } - + throw new XmlPersistenceException(msg); } } @@ -345,21 +347,21 @@ public class XmlPersistencePathBuilder { if (path.exists()) { String msg; if (StringHelper.isEmpty(context.getSubType())) { - msg = "Persistence unit already exists for {0} / {1} at {2}"; + msg = "Persistence unit already exists for {0} / {1} at {2}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); } else { - msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; + msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), path.getAbsolutePath()); } - + throw new XmlPersistenceException(msg); } } public File getCreatePath(PersistenceContext context) { File path = getPath(context); - logPath("CREATE", path, context); + logPath("CREATE", path, context); //$NON-NLS-1$ assertPathNotExists(path, context); createMissingParents(path, context); return path; @@ -367,21 +369,21 @@ public class XmlPersistencePathBuilder { public File getDeletePath(PersistenceContext context) { File path = getPath(context); - logPath("DELETE", path, context); + logPath("DELETE", path, context); //$NON-NLS-1$ assertPathExists(path, context); return path; } public File getUpdatePath(PersistenceContext context) { File path = getPath(context); - logPath("UPDATE", path, context); + logPath("UPDATE", path, context); //$NON-NLS-1$ assertPathExists(path, context); return path; } public File getReadPath(PersistenceContext context) { File path = getPath(context); - logPath("READ", path, context); + logPath("READ", path, context); //$NON-NLS-1$ if (!path.exists()) return null; return path; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java index 65a5fd113..ad151c351 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java @@ -85,6 +85,10 @@ public class BookSaxDao extends BookDao { private Book book; + public BookDefaultHandler() { + // default constructor + } + public Book getBook() { return this.book; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java index 657a54da0..5db3afe5b 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java @@ -98,6 +98,10 @@ public class ResourceSaxDao extends ResourceDao { private Resource resource; + public ResourceDefaultHandler() { + // default constructor + } + public Resource getResource() { return this.resource; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java index 27bdaf396..b156c7d05 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java @@ -30,6 +30,7 @@ import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.objectfilter.ObjectFilter; import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.XmlIoMode; /** * @author Robert von Burg @@ -45,8 +46,11 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { private final ObjectFilter objectFilter; private final boolean verbose; + private boolean committed; private boolean closed; + private XmlIoMode ioMode; + public DefaultPersistenceTransaction(FileDao fileDao, boolean verbose) { this.fileDao = fileDao; this.verbose = verbose; @@ -67,9 +71,13 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { @Override public void rollback() { - this.closed = true; - this.objectDao.rollback(); - this.objectFilter.clearCache(); + if (this.committed) + throw new IllegalStateException("Transaction has already been committed!"); //$NON-NLS-1$ + if (!this.closed) { + this.closed = true; + this.objectDao.rollback(); + this.objectFilter.clearCache(); + } } @Override @@ -95,7 +103,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$ for (Object object : removed) { - PersistenceContext context = persistenceContextFactory.createPersistenceContext(object); + PersistenceContext context = persistenceContextFactory.createCtx(this, object); this.fileDao.performDelete(context); } } @@ -110,7 +118,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { for (Object object : updated) { - PersistenceContext context = persistenceContextFactory.createPersistenceContext(object); + PersistenceContext context = persistenceContextFactory.createCtx(this, object); this.fileDao.performUpdate(context); } } @@ -125,7 +133,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { for (Object object : added) { - PersistenceContext context = persistenceContextFactory.createPersistenceContext(object); + PersistenceContext context = persistenceContextFactory.createCtx(this, object); this.fileDao.performCreate(context); } } @@ -137,12 +145,22 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { } finally { // clean up this.objectFilter.clearCache(); - this.closed = true; + this.committed = true; } } @Override - public boolean isClosed() { - return this.closed; + public boolean isOpen() { + return !this.closed && !this.committed; + } + + @Override + public void setIoMode(XmlIoMode ioMode) { + this.ioMode = ioMode; + } + + @Override + public XmlIoMode getIoMode() { + return this.ioMode; } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java index eb5963ff2..4cc86086c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java @@ -29,6 +29,7 @@ import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.PropertiesHelper; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.impl.XmlPersistenceHandlerImpl; +import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; /** * @author Robert von Burg @@ -41,6 +42,8 @@ public class DefaultXmlPersistenceManager implements XmlPersistenceManager { protected boolean initialized; protected boolean verbose; + private XmlPersistencePathBuilder pathBuilder; + public void initialize(Properties properties) { if (this.initialized) throw new IllegalStateException("Already initialized!"); //$NON-NLS-1$ @@ -51,12 +54,15 @@ public class DefaultXmlPersistenceManager implements XmlPersistenceManager { Boolean.FALSE).booleanValue(); this.verbose = verbose; + + this.pathBuilder = new XmlPersistencePathBuilder(properties); } @Override public PersistenceTransaction openTx() { - PersistenceTransaction tx = null; + FileDao fileDao = new FileDao(this.pathBuilder); + PersistenceTransaction tx = new DefaultPersistenceTransaction(fileDao, this.verbose); return tx; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java index 617057bda..eb98cd728 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java @@ -78,7 +78,7 @@ public class MetadataDao { } private void assertNotClosed() { - if (this.tx.isClosed()) + if (!this.tx.isOpen()) throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java index 6f554efcd..b16d44f46 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java @@ -178,7 +178,7 @@ public class ObjectDao { } private void assertNotClosed() { - if (this.closed || this.tx.isClosed()) + if (this.closed || !this.tx.isOpen()) throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); //$NON-NLS-1$ } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java index 07c21d77d..1357af29d 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java @@ -21,18 +21,26 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; +import static org.junit.Assert.assertNull; +import java.io.File; import java.util.Properties; import org.junit.After; -import org.junit.Before; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.XmlIoMode; +import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; +import ch.eitchnet.xmlpers.test.impl.TestConstants; import ch.eitchnet.xmlpers.test.model.Resource; /** @@ -41,41 +49,110 @@ import ch.eitchnet.xmlpers.test.model.Resource; */ public class ObjectDaoTest { - private static final Logger logger = LoggerFactory.getLogger(ObjectDaoTest.class); + private static final String BASEPATH = "target/dbTest/rewrite"; //$NON-NLS-1$ - private PersistenceContextFactory persistenceContextFactory; + private PersistenceContextFactory ctxFactory; private XmlPersistenceManager persistenceManager; private PersistenceTransaction tx; @BeforeClass public static void beforeClass() { - } - @Before - public void setUp() { + File basePath = new File(BASEPATH); + if (basePath.exists()) { + if (!FileHelper.deleteFile(basePath, true)) { + throw new RuntimeException("Faile to delete base path " + BASEPATH); //$NON-NLS-1$ + } + } - this.persistenceContextFactory = new TestPersistenceContextFactory(); + if (!basePath.mkdirs()) { + throw new RuntimeException("Failed to create base path " + BASEPATH); //$NON-NLS-1$ + } - Properties properties = new Properties(); - this.persistenceManager = XmlPersistenceManagerLoader.load(properties); + new File(BASEPATH + "/sax").mkdir(); //$NON-NLS-1$ + new File(BASEPATH + "/dom").mkdir(); //$NON-NLS-1$ } @After public void tearDown() { - if (this.tx != null) { + if (this.tx != null && this.tx.isOpen()) { this.tx.rollback(); } } @Test - @Ignore - public void testObjectDao() { + public void testSaxObjectDao() { + this.ctxFactory = new TestPersistenceContextFactory(); + Properties properties = new Properties(); + properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ + this.persistenceManager = XmlPersistenceManagerLoader.load(properties); + + testCrud(XmlIoMode.SAX); + } + + @Test + public void testDomObjectDao() { + this.ctxFactory = new TestPersistenceContextFactory(); + Properties properties = new Properties(); + properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/dom"); //$NON-NLS-1$ + this.persistenceManager = XmlPersistenceManagerLoader.load(properties); + + testCrud(XmlIoMode.DOM); + } + + private PersistenceTransaction freshTx(XmlIoMode ioMode) { + if (this.tx != null && this.tx.isOpen()) + this.tx.rollback(); this.tx = this.persistenceManager.openTx(); + this.tx.setIoMode(ioMode); + return this.tx; + } + + private void testCrud(XmlIoMode ioMode) { + + ObjectDao objectDao; + + // create new resource Resource resource = createResource(); + objectDao = freshTx(ioMode).getObjectDao(); + objectDao.add(resource); + this.tx.commit(this.ctxFactory); - this.tx.getObjectDao().add(resource); - this.tx.commit(this.persistenceContextFactory); + // read resource + PersistenceContext ctx = this.ctxFactory.createCtx(this.tx, TestConstants.TYPE_RES, RES_TYPE, RES_ID); + objectDao = freshTx(ioMode).getObjectDao(); + resource = objectDao.queryById(ctx); + assertResource(resource); + + // modify resource + updateResource(resource); + objectDao = freshTx(ioMode).getObjectDao(); + objectDao.update(resource); + this.tx.commit(this.ctxFactory); + + // read modified resource + objectDao = freshTx(ioMode).getObjectDao(); + resource = objectDao.queryById(ctx); + assertResourceUpdated(resource); + this.tx.commit(this.ctxFactory); + + // delete resource + objectDao = freshTx(ioMode).getObjectDao(); + objectDao.remove(resource); + this.tx.commit(this.ctxFactory); + + // fail to read + objectDao = freshTx(ioMode).getObjectDao(); + resource = objectDao.queryById(ctx); + assertNull(resource); + + // and create again + resource = createResource(); + assertResource(resource); + objectDao = freshTx(ioMode).getObjectDao(); + objectDao.add(resource); + this.tx.commit(this.ctxFactory); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java index 8c299be3b..5f1a20900 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java @@ -29,11 +29,11 @@ import ch.eitchnet.xmlpers.api.PersistenceContext; */ public interface PersistenceContextFactory { - public PersistenceContext createPersistenceContext(String type, String subType, String id); + public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType, String id); - public PersistenceContext createPersistenceContext(String type, String subType); + public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType); - public PersistenceContext createPersistenceContext(String type); + public PersistenceContext createCtx(PersistenceTransaction tx, String type); - public PersistenceContext createPersistenceContext(T t); + public PersistenceContext createCtx(PersistenceTransaction tx, T t); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java index 388b6a0f9..b123d3c04 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java @@ -21,6 +21,8 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; +import ch.eitchnet.xmlpers.api.XmlIoMode; + /** * @author Robert von Burg * @@ -31,9 +33,13 @@ public interface PersistenceTransaction { public void rollback(); - public boolean isClosed(); + public boolean isOpen(); public ObjectDao getObjectDao(); - + public MetadataDao getMetadataDao(); + + public XmlIoMode getIoMode(); + + public void setIoMode(XmlIoMode ioMode); } \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java index bf69b3e20..1bc512827 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java @@ -60,7 +60,7 @@ class ResourceSaxParser extends DefaultHandler implements SaxParser { writer.writeAttribute("type", this.resource.getType()); for (String paramId : this.resource.getParameterKeySet()) { Parameter param = this.resource.getParameterBy(paramId); - writer.writeElement("Parameter"); + writer.writeEmptyElement("Parameter"); writer.writeAttribute("id", param.getId()); writer.writeAttribute("name", param.getName()); writer.writeAttribute("type", param.getType()); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java index f83531824..bdb02f306 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java @@ -21,6 +21,8 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; +import java.text.MessageFormat; + import ch.eitchnet.xmlpers.api.ParserFactory; import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.test.impl.Book; @@ -34,41 +36,44 @@ import ch.eitchnet.xmlpers.test.model.Resource; public class TestPersistenceContextFactory implements PersistenceContextFactory { @Override - public PersistenceContext createPersistenceContext(String type, String subType, String id) { - return buildPersistenceContext(type, subType, id); + public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType, String id) { + return buildPersistenceContext(tx, type, subType, id); } @Override - public PersistenceContext createPersistenceContext(String type, String subType) { - return buildPersistenceContext(type, subType, null); + public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType) { + return buildPersistenceContext(tx, type, subType, null); } @Override - public PersistenceContext createPersistenceContext(String type) { - return buildPersistenceContext(type, null, null); + public PersistenceContext createCtx(PersistenceTransaction tx, String type) { + return buildPersistenceContext(tx, type, null, null); } @Override - public PersistenceContext createPersistenceContext(T t) { + public PersistenceContext createCtx(PersistenceTransaction tx, T t) { if (t == null) - throw new RuntimeException("T may not be null!"); + throw new RuntimeException("T may not be null!"); //$NON-NLS-1$ PersistenceContext context; if (t instanceof Resource) { Resource resource = (Resource) t; - context = buildPersistenceContext(TestConstants.TYPE_RES, resource.getType(), resource.getId()); + context = buildPersistenceContext(tx, TestConstants.TYPE_RES, resource.getType(), resource.getId()); } else if (t instanceof Book) { - context = buildPersistenceContext(TestConstants.TYPE_BOOK, null, ((Book) t).getId().toString()); + context = buildPersistenceContext(tx, TestConstants.TYPE_BOOK, null, ((Book) t).getId().toString()); } else { - throw new UnsupportedOperationException("Handling of " + t.getClass().getName() + " is not implemented!"); + String msg = "Handling of {0} is not implemented!"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, t.getClass().getName()); + throw new UnsupportedOperationException(msg); } context.setObject(t); return context; } - private PersistenceContext buildPersistenceContext(String type, String subType, String id) { + private PersistenceContext buildPersistenceContext(PersistenceTransaction tx, String type, String subType, + String id) { PersistenceContext context = new PersistenceContext<>(); @@ -76,6 +81,7 @@ public class TestPersistenceContextFactory implements PersistenceContextFactory context.setSubType(subType); context.setId(id); + context.setIoMode(tx.getIoMode()); context.setParserFactory(this. getParserFactoryInstance(type)); return context; @@ -93,8 +99,11 @@ public class TestPersistenceContextFactory implements PersistenceContextFactory parserFactory = (ParserFactory) new ResourceParserFactory(); else if (type.equals(TestConstants.TYPE_BOOK)) parserFactory = (ParserFactory) new BookParserFactory(); - else - throw new UnsupportedOperationException("No ParserFactory can be returned for type " + type); + else { + String msg = "No ParserFactory can be returned for type {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, type); + throw new UnsupportedOperationException(msg); + } return parserFactory; } From 3357787f32f2865359656afa6196ec22cc3ee26b Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Tue, 8 Oct 2013 18:49:46 +0200 Subject: [PATCH 30/87] [Major] rewrite is working with ObjectDao with including operations --- .../xmlpers/api/PersistenceContext.java | 10 +- .../xmlpers/impl/XmlPersistenceFileDao.java | 5 +- .../impl/XmlPersistencePathBuilder.java | 36 +-- .../test/impl/rewrite/AssertionUtil.java | 33 +++ .../DefaultPersistenceTransaction.java | 12 +- .../rewrite/DefaultXmlPersistenceManager.java | 2 +- .../xmlpers/test/impl/rewrite/FileDao.java | 79 +++++- .../test/impl/rewrite/FileDaoTest.java | 6 +- .../test/impl/rewrite/FilenameUtility.java | 23 ++ .../test/impl/rewrite/MetadataDao.java | 234 ++++++++++++++++-- .../xmlpers/test/impl/rewrite/ObjectDao.java | 80 +++--- .../test/impl/rewrite/ObjectDaoTest.java | 74 +++++- .../impl/rewrite/PersistenceTransaction.java | 2 +- .../xmlpers/test/model/ModelBuilder.java | 6 +- src/test/resources/log4j.xml | 4 +- 15 files changed, 498 insertions(+), 108 deletions(-) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index 7ce34f7c7..42d36b99c 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -32,7 +32,7 @@ public class PersistenceContext { private XmlIoMode ioMode; private ParserFactory parserFactory; - + public PersistenceContext() { this.ioMode = XmlIoMode.DEFAULT; } @@ -85,10 +85,18 @@ public class PersistenceContext { this.parserFactory = parserFactory; } + public boolean hasType() { + return !StringHelper.isEmpty(this.type); + } + public boolean hasSubType() { return !StringHelper.isEmpty(this.subType); } + public boolean hasId() { + return !StringHelper.isEmpty(this.id); + } + @Override public PersistenceContext clone() { PersistenceContext clone = new PersistenceContext<>(); diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java index 58ec57411..ae905546a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java @@ -32,6 +32,7 @@ import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.PropertiesHelper; import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.test.impl.rewrite.FilenameUtility; /** * @author Robert von Burg @@ -254,7 +255,7 @@ public class XmlPersistenceFileDao { for (File subTypeFile : subTypeFiles) { if (subTypeFile.isFile()) { String filename = subTypeFile.getName(); - String id = this.pathBuilder.getId(filename); + String id = FilenameUtility.getId(filename); keySet.add(id); } } @@ -283,7 +284,7 @@ public class XmlPersistenceFileDao { for (File subTypeFile : subTypeFiles) { if (subTypeFile.isFile()) { String filename = subTypeFile.getName(); - String id = this.pathBuilder.getId(filename); + String id = FilenameUtility.getId(filename); keySet.add(id); } } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java index 51d6f1791..a70d09444 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java @@ -85,12 +85,6 @@ public class XmlPersistencePathBuilder { return id.concat(XmlPersistencePathBuilder.FILE_EXT); } - String getId(String filename) { - assertFilename(filename); - - return filename.substring(0, filename.length() - XmlPersistencePathBuilder.EXT_LENGTH); - } - String getPathAsString(String type, String subType, String id) { StringBuilder sb = new StringBuilder(this.basePath); if (!StringHelper.isEmpty(type)) { @@ -275,14 +269,6 @@ public class XmlPersistencePathBuilder { throw new XmlPersistenceException("The subType can not be empty!"); //$NON-NLS-1$ } - private void assertFilename(String filename) { - if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') { - String msg = "The filename does not have a . (dot) at index {0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); - throw new XmlPersistenceException(msg); - } - } - private void assertPathNotExists(File path, String msg, Object... args) { if (path.exists()) { throw new XmlPersistenceException(MessageFormat.format(msg, args)); @@ -327,7 +313,7 @@ public class XmlPersistencePathBuilder { } } - private void assertPathExists(File path, PersistenceContext context) { + private void assertPathIsFileAndWritable(File path, PersistenceContext context) { if (!path.exists()) { String msg; if (StringHelper.isEmpty(context.getSubType())) { @@ -341,6 +327,20 @@ public class XmlPersistencePathBuilder { throw new XmlPersistenceException(msg); } + + if (!path.isFile() || !path.canWrite()) { + String msg; + if (StringHelper.isEmpty(context.getSubType())) { + msg = "Persistence unit is not a file or is not readable for {0} / {1} at {2}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); + } else { + msg = "Persistence unit is not a file or is not readable for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), + path.getAbsolutePath()); + } + + throw new XmlPersistenceException(msg); + } } private void assertPathNotExists(File path, PersistenceContext context) { @@ -370,14 +370,14 @@ public class XmlPersistencePathBuilder { public File getDeletePath(PersistenceContext context) { File path = getPath(context); logPath("DELETE", path, context); //$NON-NLS-1$ - assertPathExists(path, context); + assertPathIsFileAndWritable(path, context); return path; } public File getUpdatePath(PersistenceContext context) { File path = getPath(context); logPath("UPDATE", path, context); //$NON-NLS-1$ - assertPathExists(path, context); + assertPathIsFileAndWritable(path, context); return path; } @@ -389,7 +389,7 @@ public class XmlPersistencePathBuilder { return path; } - private File getPath(PersistenceContext context) { + public File getPath(PersistenceContext context) { File path = new File(getPathAsString(context.getType(), context.getSubType(), context.getId())); return path; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java new file mode 100644 index 000000000..d83f5edeb --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java @@ -0,0 +1,33 @@ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.text.MessageFormat; + +import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.xmlpers.api.PersistenceContext; + +public class AssertionUtil { + + public static void assertNotNull(Object object) { + if (object == null) + throw new RuntimeException("Object may not be null!"); //$NON-NLS-1$ + } + + public static void assertObjectRead(PersistenceContext context) { + if (context.getObject() == null) { + String msg = "Failed to read object with for {0} / {1} / {2}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId()); + throw new RuntimeException(msg); + } + } + + public static void assertHasType(PersistenceContext context) { + if (StringHelper.isEmpty(context.getType())) + throw new RuntimeException("Type is always needed on a persistence context!"); //$NON-NLS-1$ + } + + public static void assertHasId(PersistenceContext context) { + if (StringHelper.isEmpty(context.getId())) + throw new RuntimeException("Id is not set on persistence context!"); //$NON-NLS-1$ + } + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java index b156c7d05..598ab4dd1 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java @@ -56,7 +56,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { this.verbose = verbose; this.objectFilter = new ObjectFilter(); this.objectDao = new ObjectDao(this, this.fileDao, this.objectFilter); - this.metadataDao = new MetadataDao(this, this.fileDao); + this.metadataDao = new MetadataDao(this, this.fileDao, verbose); } @Override @@ -81,7 +81,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { } @Override - public void commit(PersistenceContextFactory persistenceContextFactory) { + public void commit(PersistenceContextFactory ctxFactory) { try { @@ -90,8 +90,6 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info("Committing TX..."); //$NON-NLS-1$ Set keySet = this.objectFilter.keySet(); - if (keySet.isEmpty()) - return; for (String key : keySet) { List removed = this.objectFilter.getRemoved(key); @@ -103,7 +101,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$ for (Object object : removed) { - PersistenceContext context = persistenceContextFactory.createCtx(this, object); + PersistenceContext context = ctxFactory.createCtx(this, object); this.fileDao.performDelete(context); } } @@ -118,7 +116,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { for (Object object : updated) { - PersistenceContext context = persistenceContextFactory.createCtx(this, object); + PersistenceContext context = ctxFactory.createCtx(this, object); this.fileDao.performUpdate(context); } } @@ -133,7 +131,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { for (Object object : added) { - PersistenceContext context = persistenceContextFactory.createCtx(this, object); + PersistenceContext context = ctxFactory.createCtx(this, object); this.fileDao.performCreate(context); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java index 4cc86086c..30ee6cac0 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java @@ -61,7 +61,7 @@ public class DefaultXmlPersistenceManager implements XmlPersistenceManager { @Override public PersistenceTransaction openTx() { - FileDao fileDao = new FileDao(this.pathBuilder); + FileDao fileDao = new FileDao(this.pathBuilder, this.verbose); PersistenceTransaction tx = new DefaultPersistenceTransaction(fileDao, this.verbose); return tx; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java index 8774d2549..1e8898bfa 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java @@ -22,15 +22,29 @@ package ch.eitchnet.xmlpers.test.impl.rewrite; import java.io.File; +import java.text.MessageFormat; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; public class FileDao { - private XmlPersistencePathBuilder pathBuilder; - public FileDao(XmlPersistencePathBuilder pathBuilder) { + private static final Logger logger = LoggerFactory.getLogger(FileDao.class); + + private final boolean verbose; + private final XmlPersistencePathBuilder pathBuilder; + + public FileDao(XmlPersistencePathBuilder pathBuilder, boolean verbose) { this.pathBuilder = pathBuilder; + this.verbose = verbose; + } + + File getPath(PersistenceContext context) { + return this.pathBuilder.getPath(context); } void performCreate(PersistenceContext context) { @@ -57,6 +71,65 @@ public class FileDao { void performDelete(PersistenceContext context) { File path = this.pathBuilder.getDeletePath(context); - path.delete(); + if (!path.delete()) { + String msg = "Failed to delete file {0}"; //$NON-NLS-1$ + throw new RuntimeException(MessageFormat.format(msg, path.getAbsolutePath())); + } + + deleteEmptyDirectory(path.getParentFile(), context); + } + + private void deleteEmptyDirectory(File directoryPath, PersistenceContext ctx) { + if (!directoryPath.isDirectory()) { + String msg = "The given path for deletion when empty is not a directory:{0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, directoryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + if (directoryPath.list().length == 0) { + if (!ctx.hasSubType()) { + if (!directoryPath.delete()) { + throw failedToDelete(directoryPath, ctx); + } + if (this.verbose) { + String msg = "Deleted empty directory for type {0} at {1}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, ctx.getType(), directoryPath)); + } + } else { + + if (!directoryPath.delete()) { + throw failedToDelete(directoryPath, ctx); + } + if (this.verbose) { + String msg = "Deleted empty directory for subType {0} of type {1} at {2}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, ctx.getSubType(), ctx.getType(), directoryPath)); + } + + File typePath = directoryPath.getParentFile(); + if (typePath.list().length == 0) { + + if (!typePath.delete()) { + throw failedToDelete(typePath, ctx); + } + if (this.verbose) { + String msg = "Deleted empty directory for type {0} at {1}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, ctx.getType(), typePath)); + } + } + } + } + } + + private XmlPersistenceException failedToDelete(File directoryPath, PersistenceContext ctx) { + String msg; + if (ctx.hasSubType()) { + msg = "Deletion of empty directory for {0} / {1} / {2} at {3} failed! Check file permissions!"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, ctx.getType(), ctx.getSubType(), ctx.getId(), + directoryPath.getAbsolutePath()); + } else { + + msg = "Deletion of empty directory for {0} / {1} / at {2} failed! Check file permissions!"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, ctx.getType(), ctx.getId(), directoryPath.getAbsolutePath()); + } + return new XmlPersistenceException(msg); } } \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java index 11ac0036d..b5d980543 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java @@ -46,9 +46,11 @@ import ch.eitchnet.xmlpers.test.model.Resource; * @author Robert von Burg * */ +@SuppressWarnings("nls") public class FileDaoTest { private static final String TEST_PATH = "target/dbTest"; + private static final boolean VERBOSE = true; private FileDao fileDao; private Properties properties; @@ -82,7 +84,7 @@ public class FileDaoTest { public void testCrudSax() { this.properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, TEST_PATH + "/sax/"); XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(this.properties); - this.fileDao = new FileDao(pathBuilder); + this.fileDao = new FileDao(pathBuilder, VERBOSE); Resource resource = createResource(); assertResource(resource); @@ -95,7 +97,7 @@ public class FileDaoTest { public void testCrudDom() { this.properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, TEST_PATH + "/dom/"); XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(this.properties); - this.fileDao = new FileDao(pathBuilder); + this.fileDao = new FileDao(pathBuilder, VERBOSE); Resource resource = createResource(); assertResource(resource); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java new file mode 100644 index 000000000..30cd558fc --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java @@ -0,0 +1,23 @@ +package ch.eitchnet.xmlpers.test.impl.rewrite; + +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; + +public class FilenameUtility { + + public static String getId(String filename) { + assertFilename(filename); + return filename.substring(0, filename.length() - XmlPersistencePathBuilder.EXT_LENGTH); + } + + public static void assertFilename(String filename) { + if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') { + String msg = "The filename does not have a . (dot) at index {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); + throw new XmlPersistenceException(msg); + } + } + +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java index eb98cd728..4cf2d287b 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java @@ -21,64 +21,252 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; +import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertHasType; + +import java.io.File; +import java.text.MessageFormat; +import java.util.Collections; +import java.util.HashSet; import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.xmlpers.api.PersistenceContext; + /** * @author Robert von Burg * */ public class MetadataDao { + private static final Logger logger = LoggerFactory.getLogger(MetadataDao.class); + private final DefaultPersistenceTransaction tx; private final FileDao fileDao; + private final boolean verbose; - public MetadataDao(DefaultPersistenceTransaction tx, FileDao fileDao) { + public MetadataDao(DefaultPersistenceTransaction tx, FileDao fileDao, boolean verbose) { this.tx = tx; this.fileDao = fileDao; + this.verbose = verbose; } - public Set queryTypeSet() { + public Set queryTypeSet(PersistenceContext ctx) { assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + assertHasNoSubType(ctx); + + File queryPath = this.fileDao.getPath(ctx); + Set keySet = queryTypeSet(queryPath); + + if (this.verbose) { + String msg; + if (!ctx.hasType()) { + msg = "Found {0} types"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size()); + } else { + msg = "Found {0} subTypes of type {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), ctx.getType()); + } + + logger.info(msg); + } + + return keySet; } - public Set queryTypeSet(String type) { - assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + private void assertHasNoSubType(PersistenceContext ctx) { + if (ctx.hasSubType()) { + throw new RuntimeException("Illegal query: sub type may not be set!"); //$NON-NLS-1$ + } } - public Set queryKeySet(String type) { + public Set queryKeySet(PersistenceContext ctx) { assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + assertHasType(ctx); + + File queryPath = this.fileDao.getPath(ctx); + Set keySet = queryKeySet(queryPath); + + if (this.verbose) { + String msg; + if (!ctx.hasSubType()) { + msg = "Found {0} objects of type {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), ctx.getType()); + } else { + msg = "Found {0} objects of type {1} and subtType {2}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), ctx.getType(), ctx.getSubType()); + } + + logger.info(msg); + } + + return keySet; } - public Set queryKeySet(String type, String subType) { + public long queryTypeSize(PersistenceContext ctx) { assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + assertHasNoSubType(ctx); + + File queryPath = this.fileDao.getPath(ctx); + long numberOfFiles = queryTypeSize(queryPath); + + if (this.verbose) { + String msg; + if (!ctx.hasType()) { + msg = "Found {0} types"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles); + } else { + msg = "Found {0} subTypes of type {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, ctx.getType()); + } + + logger.info(msg); + } + + return numberOfFiles; } - public long queryTypeSize() { + public long querySize(PersistenceContext ctx) { assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + assertHasType(ctx); + + File queryPath = this.fileDao.getPath(ctx); + long numberOfFiles = querySize(queryPath); + + if (this.verbose) { + String msg; + if (!ctx.hasSubType()) { + msg = "Found {0} objects of type {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, ctx.getType()); + } else { + msg = "Found {0} objects of type {1} and subtType {2}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, ctx.getType(), ctx.getSubType()); + } + + logger.info(msg); + } + + return numberOfFiles; } - public long querySubTypeSize(String type) { - assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + /** + * Returns the types, i.e. directories in the given query path + * + * @param queryPath + * the path for which the types should be gathered + * + * @return a set of types in the given query path + */ + private Set queryTypeSet(File queryPath) { + Set keySet = new HashSet(); + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + if (subTypeFile.isFile()) { + String filename = subTypeFile.getName(); + String id = FilenameUtility.getId(filename); + keySet.add(id); + } + } + + return keySet; } - public long querySize(String type) { - assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + /** + * Returns the ids of all objects in the given query path, i.e. the id part of all the files in the given query path + * + * @param queryPath + * the path for which the ids should be gathered + * + * @return a set of ids for the objects in the given query path + */ + private Set queryKeySet(File queryPath) { + if (!queryPath.exists()) + return Collections.emptySet(); + + if (!queryPath.isDirectory()) { + String msg = "The path is not a directory, thus can not query key set for it: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, queryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + + Set keySet = new HashSet(); + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + if (subTypeFile.isFile()) { + String filename = subTypeFile.getName(); + String id = FilenameUtility.getId(filename); + keySet.add(id); + } + } + + return keySet; } - public long querySize(String type, String subType) { - assertNotClosed(); - throw new UnsupportedOperationException("Not yet implemented!"); + /** + * Returns the number of all types, i.e. directories in the given query path + * + * @param queryPath + * the path in which to count the types + * + * @return the number of types in the given query path + */ + private long queryTypeSize(File queryPath) { + if (!queryPath.exists()) + return 0L; + + if (!queryPath.isDirectory()) { + String msg = "The path is not a directory, thus can not query type size for it: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, queryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + + long numberOfFiles = 0l; + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isDirectory()) + numberOfFiles++; + } + return numberOfFiles; + } + + /** + * Returns the number of all objects in the given query path + * + * @param queryPath + * the path in which to count the objects + * + * @return the number of objects in the given query path + */ + private long querySize(File queryPath) { + if (!queryPath.exists()) + return 0L; + + if (!queryPath.isDirectory()) { + String msg = "The path is not a directory, thus can not query key size for it: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, queryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + + long numberOfFiles = 0l; + + File[] subTypeFiles = queryPath.listFiles(); + for (File subTypeFile : subTypeFiles) { + + if (subTypeFile.isFile()) + numberOfFiles++; + } + return numberOfFiles; } private void assertNotClosed() { - if (!this.tx.isOpen()) - throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); + if (!this.tx.isOpen()) { + String msg = "Transaction has been closed and thus no operation can be performed!"; //$NON-NLS-1$ + throw new IllegalStateException(msg); + } } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java index b16d44f46..44957ff8a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java @@ -21,12 +21,15 @@ */ package ch.eitchnet.xmlpers.test.impl.rewrite; -import java.text.MessageFormat; +import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertHasId; +import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertHasType; +import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertNotNull; +import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertObjectRead; + import java.util.ArrayList; import java.util.List; import java.util.Set; -import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.objectfilter.ObjectFilter; import ch.eitchnet.xmlpers.api.PersistenceContext; @@ -47,24 +50,48 @@ public class ObjectDao { this.objectFilter = objectFilter; } - public void add(Object object) { + public void add(T object) { assertNotClosed(); assertNotNull(object); this.objectFilter.add(object); } - public void update(Object object) { + @SuppressWarnings("unchecked") + public void addAll(List objects) { + assertNotClosed(); + assertNotNull(objects); + if (!objects.isEmpty()) + this.objectFilter.addAll((List) objects); + } + + public void update(T object) { assertNotClosed(); assertNotNull(object); this.objectFilter.update(object); } - public void remove(Object object) { + @SuppressWarnings("unchecked") + public void updateAll(List objects) { + assertNotClosed(); + assertNotNull(objects); + if (!objects.isEmpty()) + this.objectFilter.updateAll((List) objects); + } + + public void remove(T object) { assertNotClosed(); assertNotNull(object); this.objectFilter.remove(object); } + @SuppressWarnings("unchecked") + public void removeAll(List objects) { + assertNotClosed(); + assertNotNull(objects); + if (!objects.isEmpty()) + this.objectFilter.removeAll((List) objects); + } + public void removeById(PersistenceContext context) { assertNotClosed(); assertHasType(context); @@ -97,11 +124,7 @@ public class ObjectDao { assertHasType(context); MetadataDao metadataDao = this.tx.getMetadataDao(); - Set keySet; - if (context.hasSubType()) - keySet = metadataDao.queryKeySet(context.getType(), context.getSubType()); - else - keySet = metadataDao.queryKeySet(context.getType()); + Set keySet = metadataDao.queryKeySet(context); List result = new ArrayList<>(); PersistenceContext readContext = context.clone(); @@ -123,12 +146,7 @@ public class ObjectDao { assertHasType(context); MetadataDao metadataDao = this.tx.getMetadataDao(); - Set keySet; - if (context.hasSubType()) - keySet = metadataDao.queryKeySet(context.getType(), context.getSubType()); - else - keySet = metadataDao.queryKeySet(context.getType()); - + Set keySet = metadataDao.queryKeySet(context); return keySet; } @@ -140,12 +158,7 @@ public class ObjectDao { assertHasType(context); MetadataDao metadataDao = this.tx.getMetadataDao(); - long size; - if (context.hasSubType()) - size = metadataDao.querySize(context.getType(), context.getSubType()); - else - size = metadataDao.querySize(context.getType()); - + long size = metadataDao.querySize(context); return size; } @@ -154,29 +167,6 @@ public class ObjectDao { this.closed = true; } - private void assertNotNull(Object object) { - if (object == null) - throw new RuntimeException("Object may not be null!"); //$NON-NLS-1$ - } - - private void assertObjectRead(PersistenceContext context) { - if (context.getObject() == null) { - String msg = "Failed to read object with for {0} / {1} / {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId()); - throw new RuntimeException(msg); - } - } - - private void assertHasType(PersistenceContext context) { - if (StringHelper.isEmpty(context.getType())) - throw new RuntimeException("Type is always needed on a persistence context!"); //$NON-NLS-1$ - } - - private void assertHasId(PersistenceContext context) { - if (StringHelper.isEmpty(context.getId())) - throw new RuntimeException("Id is not set on persistence context!"); //$NON-NLS-1$ - } - private void assertNotClosed() { if (this.closed || !this.tx.isOpen()) throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); //$NON-NLS-1$ diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java index 1357af29d..d5e6e9c59 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java @@ -27,9 +27,12 @@ import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.io.File; +import java.util.ArrayList; +import java.util.List; import java.util.Properties; import org.junit.After; @@ -81,7 +84,7 @@ public class ObjectDaoTest { } @Test - public void testSaxObjectDao() { + public void testCrudSax() { this.ctxFactory = new TestPersistenceContextFactory(); Properties properties = new Properties(); properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ @@ -91,7 +94,7 @@ public class ObjectDaoTest { } @Test - public void testDomObjectDao() { + public void testCrudDom() { this.ctxFactory = new TestPersistenceContextFactory(); Properties properties = new Properties(); properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/dom"); //$NON-NLS-1$ @@ -155,4 +158,71 @@ public class ObjectDaoTest { objectDao.add(resource); this.tx.commit(this.ctxFactory); } + + @Test + public void testBulkSax() { + + this.ctxFactory = new TestPersistenceContextFactory(); + Properties properties = new Properties(); + properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ + properties.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + this.persistenceManager = XmlPersistenceManagerLoader.load(properties); + + XmlIoMode ioMode = XmlIoMode.SAX; + testBulk(ioMode); + } + + @Test + public void testBulkDom() { + + this.ctxFactory = new TestPersistenceContextFactory(); + Properties properties = new Properties(); + properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ + properties.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + this.persistenceManager = XmlPersistenceManagerLoader.load(properties); + + XmlIoMode ioMode = XmlIoMode.DOM; + testBulk(ioMode); + } + + private void testBulk(XmlIoMode ioMode) { + + // context + String type = "testBulk" + ioMode.name(); //$NON-NLS-1$ + + // create a list of resources + List resources = new ArrayList<>(10); + for (int i = 0; i < 10; i++) { + String id = RES_ID + "_" + i; //$NON-NLS-1$ + String name = "Bulk Test Object. " + i; //$NON-NLS-1$ + + Resource resource = createResource(id, name, type); + resources.add(resource); + } + + ObjectDao objectDao; + + // save all + objectDao = freshTx(ioMode).getObjectDao(); + objectDao.addAll(resources); + resources.clear(); + this.tx.commit(this.ctxFactory); + + // query all + objectDao = freshTx(ioMode).getObjectDao(); + PersistenceContext ctx = this.ctxFactory.createCtx(this.tx, TestConstants.TYPE_RES, type); + resources = objectDao.queryAll(ctx); + assertEquals("Expected to find 10 entries!", 10, resources.size()); //$NON-NLS-1$ + + // delete them all + objectDao.removeAll(resources); + this.tx.commit(this.ctxFactory); + + // now query them again + objectDao = freshTx(ioMode).getObjectDao(); + ctx = this.ctxFactory.createCtx(this.tx, TestConstants.TYPE_RES, type); + resources = objectDao.queryAll(ctx); + assertEquals("Expected to find 0 entries!", 0, resources.size()); //$NON-NLS-1$ + this.tx.commit(this.ctxFactory); + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java index b123d3c04..1109d65d1 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java @@ -29,7 +29,7 @@ import ch.eitchnet.xmlpers.api.XmlIoMode; */ public interface PersistenceTransaction { - public void commit(PersistenceContextFactory persistenceContextFactory); + public void commit(PersistenceContextFactory ctxFactory); public void rollback(); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index bc7fd5a4a..f44cc6590 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -51,7 +51,11 @@ public class ModelBuilder { public static final double BOOK_PRICE = 45.55D; public static Resource createResource() { - Resource resource = new Resource(RES_ID, RES_NAME, RES_TYPE); + return createResource(RES_ID, RES_NAME, RES_TYPE); + } + + public static Resource createResource(String id, String name, String type) { + Resource resource = new Resource(id, name, type); Parameter param = new Parameter(PARAM_ID, PARAM_NAME, PARAM_TYPE, PARAM_VALUE_1); resource.addParameter(param); return resource; diff --git a/src/test/resources/log4j.xml b/src/test/resources/log4j.xml index a35a3c351..2f49b0dca 100644 --- a/src/test/resources/log4j.xml +++ b/src/test/resources/log4j.xml @@ -17,11 +17,11 @@ - + - + From d3e77afef27ed678d1efb073469a63bcbb6b1d76 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Tue, 8 Oct 2013 19:00:27 +0200 Subject: [PATCH 31/87] [Minor] cleaned up compiler warnings --- .../xmlpers/test/impl/rewrite/FileIo.java | 91 +++++++++++-------- 1 file changed, 51 insertions(+), 40 deletions(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java index f23a3361d..7e64e45c0 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java @@ -52,6 +52,7 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; +import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.helper.XmlHelper; import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.DomUtil; @@ -62,6 +63,9 @@ import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; public class FileIo { + public static final String DEFAULT_XML_VERSION = "1.0"; //$NON-NLS-1$ + public static final String DEFAULT_ENCODING = "utf-8"; //$NON-NLS-1$ + private static final Logger logger = LoggerFactory.getLogger(FileIo.class); private final File path; @@ -79,11 +83,11 @@ public class FileIo { writeSax(context); break; case DEFAULT: - logger.info("Using default XML IO Handler SAX"); + logger.info("Using default XML IO Handler SAX"); //$NON-NLS-1$ writeSax(context); break; default: - String msg = "The Xml IO Mode {0} is not supported!"; + String msg = "The Xml IO Mode {0} is not supported!"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getIoMode()); throw new UnsupportedOperationException(msg); } @@ -98,11 +102,11 @@ public class FileIo { readSax(context); break; case DEFAULT: - logger.info("Using default XML IO Handler SAX"); + logger.info("Using default XML IO Handler SAX"); //$NON-NLS-1$ readSax(context); break; default: - String msg = "The Xml IO Mode {0} is not supported!"; + String msg = "The Xml IO Mode {0} is not supported!"; //$NON-NLS-1$ msg = MessageFormat.format(msg, context.getIoMode()); throw new UnsupportedOperationException(msg); } @@ -112,38 +116,36 @@ public class FileIo { XMLStreamWriter writer = null; try { - XMLOutputFactory factory = XMLOutputFactory.newInstance(); - writer = factory.createXMLStreamWriter(new FileWriter(this.path)); - writer = new IndentingXMLStreamWriter(writer); + try (FileWriter fileWriter = new FileWriter(this.path);) { - // start document - writer.writeStartDocument("utf-8", "1.0"); + XMLOutputFactory factory = XMLOutputFactory.newInstance(); + writer = factory.createXMLStreamWriter(fileWriter); + writer = new IndentingXMLStreamWriter(writer); - // then delegate object writing to caller - XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); - SaxParser saxParser = context.getParserFactor().getSaxParser(); - saxParser.setObject(context.getObject()); - saxParser.write(xmlWriter); + // start document + writer.writeStartDocument(DEFAULT_ENCODING, DEFAULT_XML_VERSION); - // and now end - writer.writeEndDocument(); - writer.flush(); + // then delegate object writing to caller + XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); + SaxParser saxParser = context.getParserFactor().getSaxParser(); + saxParser.setObject(context.getObject()); + saxParser.write(xmlWriter); + + // and now end + writer.writeEndDocument(); + writer.flush(); + } } catch (FactoryConfigurationError | XMLStreamException | IOException e) { if (this.path.exists()) this.path.delete(); - throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception e) { - logger.error("Failed to close stream: " + e.getMessage()); - } - } + String msg = "Writing to file failed due to internal error: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, e.getMessage()); + throw new XmlException(msg, e); } - logger.info("Wrote SAX to " + this.path.getAbsolutePath()); + String msg = "Wrote SAX to {0}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); } private void readSax(PersistenceContext context) { @@ -160,10 +162,12 @@ public class FileIo { } catch (ParserConfigurationException | SAXException | IOException e) { - throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); + String msg = "Parsing failed due to internal error: {0}"; //$NON-NLS-1$ + throw new XmlPersistenceException(MessageFormat.format(msg, e.getMessage()), e); } - logger.info("SAX parsed file " + this.path.getAbsolutePath()); + String msg = "SAX parsed file {0}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); } private void writeDom(PersistenceContext context) { @@ -178,19 +182,19 @@ public class FileIo { encoding = XmlHelper.DEFAULT_ENCODING; } - if (!lineSep.equals("\n")) { - logger.info("Overriding line separator to \\n"); - System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, "\n"); + if (!lineSep.equals(StringHelper.NEW_LINE)) { + logger.info("Overriding line separator to \\n"); //$NON-NLS-1$ + System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, StringHelper.NEW_LINE); } // Set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer transformer = transfac.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); //$NON-NLS-1$ + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ + transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.ENCODING, encoding); - transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); + transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$ // transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\t"); // Transform to file @@ -198,12 +202,15 @@ public class FileIo { Source xmlSource = new DOMSource(document); transformer.transform(xmlSource, result); - logger.info("Wrote DOM to " + this.path.getAbsolutePath()); + String msg = MessageFormat.format("Wrote DOM to {0}", this.path.getAbsolutePath()); //$NON-NLS-1$ + logger.info(msg); } catch (TransformerFactoryConfigurationError | TransformerException e) { if (this.path.exists()) this.path.delete(); - throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); + String msg = "Writing to file failed due to internal error: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, e.getMessage()); + throw new XmlException(msg, e); } finally { System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep); } @@ -217,9 +224,13 @@ public class FileIo { domParser.fromDom(document); context.setObject(domParser.getObject()); } catch (SAXException | IOException e) { - throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); + String msg = "Parsing failed due to internal error: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, e.getMessage()); + throw new XmlPersistenceException(msg, e); } - logger.info("DOM parsed file " + this.path.getAbsolutePath()); + String msg = "DOM parsed file {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, this.path.getAbsolutePath()); + logger.info(msg); } } \ No newline at end of file From 4c7f0fc46085ad340f5d5ad210431ec8e94ab7a3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Tue, 15 Oct 2013 22:26:58 +0200 Subject: [PATCH 32/87] [Major] implemented new ObjectRef referencing of objects with locking Locking is not yet implemented, but is now prepared. This is once again a major rewrite but this has lead to easier use and less if/else constructs but far more object oriented delegation and double dispatching where possible --- pom.xml | 2 +- .../xmlpers/api/AbstractDaoFactory.java | 90 ---- .../eitchnet/xmlpers/api/AbstractXmlDao.java | 219 ---------- .../ch/eitchnet/xmlpers/api/DaoContext.java | 42 -- .../java/ch/eitchnet/xmlpers/api/FileDao.java | 183 ++++++++ .../java/ch/eitchnet/xmlpers/api}/FileIo.java | 96 ++--- .../ch/eitchnet/xmlpers/api/IoContext.java | 31 -- ...istenceDomContextData.java => IoMode.java} | 43 +- .../ch/eitchnet/xmlpers/api/IoOperation.java | 6 + .../ch/eitchnet/xmlpers/api}/MetadataDao.java | 129 +++--- .../ch/eitchnet/xmlpers/api}/ObjectDao.java | 91 ++-- ...nstants.java => PersistenceConstants.java} | 3 +- .../xmlpers/api/PersistenceContext.java | 68 +-- .../api/PersistenceContextFactory.java | 12 + .../PersistenceContextFactoryDelegator.java | 73 ++++ .../xmlpers/api/PersistenceManager.java} | 10 +- .../api/PersistenceManagerLoader.java} | 8 +- .../xmlpers/api/PersistenceRealm.java | 24 ++ .../xmlpers/api}/PersistenceTransaction.java | 23 +- .../ch/eitchnet/xmlpers/api/SaxParser.java | 2 - .../xmlpers/api/TransactionCloseStrategy.java | 21 + .../ch/eitchnet/xmlpers/api/XmlIoMode.java | 31 -- .../api/XmlPersistenceContextData.java | 48 --- .../xmlpers/api/XmlPersistenceDao.java | 47 --- .../xmlpers/api/XmlPersistenceDaoFactory.java | 40 -- .../api/XmlPersistenceFileHandler.java | 34 -- .../xmlpers/api/XmlPersistenceHandler.java | 31 -- .../api/XmlPersistenceMetadataDao.java | 44 -- .../api/XmlPersistenceSaxContextData.java | 65 --- .../xmlpers/api/XmlPersistenceSaxWriter.java | 35 -- .../XmlPersistenceStreamWriter.java | 2 +- .../api/XmlPersistenceTransaction.java | 76 ---- .../xmlpers/impl/DefaultPersistenceRealm.java | 59 +++ .../impl}/DefaultPersistenceTransaction.java | 108 +++-- .../impl/DefaultXmlPersistenceManager.java | 114 +++++ .../eitchnet/xmlpers/impl/MetadataXmlDao.java | 90 ---- .../ch/eitchnet/xmlpers/impl/PathBuilder.java | 127 ++++++ .../impl/TransactionDaoFactoryFacade.java | 107 ----- .../impl/XmlPersistenceDomHandler.java | 127 ------ .../xmlpers/impl/XmlPersistenceFileDao.java | 372 ---------------- .../impl/XmlPersistenceFileIoHandler.java | 37 -- .../impl/XmlPersistenceHandlerImpl.java | 90 ---- .../impl/XmlPersistencePathBuilder.java | 396 ------------------ .../impl/XmlPersistenceSaxHandler.java | 129 ------ .../impl/XmlPersistenceTransactionImpl.java | 227 ---------- .../xmlpers/objref/IdOfSubTypeRef.java | 79 ++++ .../eitchnet/xmlpers/objref/IdOfTypeRef.java | 73 ++++ .../xmlpers/objref/LockableObject.java | 29 ++ .../ch/eitchnet/xmlpers/objref/ObjectRef.java | 40 ++ .../xmlpers/objref/ObjectReferenceCache.java | 80 ++++ .../xmlpers/objref/RefNameCreator.java | 65 +++ .../ch/eitchnet/xmlpers/objref/RootRef.java | 53 +++ .../eitchnet/xmlpers/objref/SubTypeRef.java | 65 +++ .../ch/eitchnet/xmlpers/objref/TypeRef.java | 58 +++ .../eitchnet/xmlpers/util/AssertionUtil.java | 47 +++ .../xmlpers/{api => util}/DomUtil.java | 10 +- .../xmlpers/util}/FilenameUtility.java | 10 +- .../test/AbstractXmlPersistenceTest.java | 372 ---------------- .../ch/eitchnet/xmlpers/test/FileDaoTest.java | 154 +++++++ .../eitchnet/xmlpers/test/ObjectDaoTest.java | 221 ++++++++++ .../xmlpers/test/XmlPersistenceDomTest.java | 49 --- .../xmlpers/test/XmlPersistenceSaxTest.java | 49 --- .../ch/eitchnet/xmlpers/test/XmlTestMain.java | 73 ++-- .../ch/eitchnet/xmlpers/test/impl/Book.java | 2 +- .../eitchnet/xmlpers/test/impl/BookDao.java | 41 -- .../xmlpers/test/impl/BookDomDao.java | 33 +- .../impl/{rewrite => }/BookDomParser.java | 3 +- .../impl/{rewrite => }/BookParserFactory.java | 3 +- .../xmlpers/test/impl/BookSaxDao.java | 56 +-- .../impl/{rewrite => }/BookSaxParser.java | 5 +- .../test/impl/ResourceContextFactory.java | 25 ++ .../xmlpers/test/impl/ResourceDao.java | 53 --- .../xmlpers/test/impl/ResourceDomDao.java | 39 +- .../impl/{rewrite => }/ResourceDomParser.java | 6 +- .../{rewrite => }/ResourceParserFactory.java | 2 +- .../xmlpers/test/impl/ResourceSaxDao.java | 73 +--- .../impl/{rewrite => }/ResourceSaxParser.java | 6 +- .../test/impl/TestModelDaoFactory.java | 97 ----- .../test/impl/rewrite/AssertionUtil.java | 33 -- .../rewrite/DefaultXmlPersistenceManager.java | 69 --- .../xmlpers/test/impl/rewrite/FileDao.java | 135 ------ .../test/impl/rewrite/FileDaoTest.java | 145 ------- .../test/impl/rewrite/ObjectDaoTest.java | 228 ---------- .../rewrite/PersistenceContextFactory.java | 39 -- .../TestPersistenceContextFactory.java | 110 ----- .../xmlpers/test/model/ModelBuilder.java | 1 + .../xmlpers/test/model/Parameter.java | 1 + .../eitchnet/xmlpers/test/model/Resource.java | 1 + 88 files changed, 1988 insertions(+), 4357 deletions(-) delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/FileDao.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/FileIo.java (72%) delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/IoContext.java rename src/main/java/ch/eitchnet/xmlpers/api/{XmlPersistenceDomContextData.java => IoMode.java} (53%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/MetadataDao.java (66%) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/ObjectDao.java (60%) rename src/main/java/ch/eitchnet/xmlpers/api/{XmlPersistenceConstants.java => PersistenceConstants.java} (95%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java => main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java} (76%) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java => main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java} (83%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/api}/PersistenceTransaction.java (63%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java rename src/main/java/ch/eitchnet/xmlpers/{impl => api}/XmlPersistenceStreamWriter.java (98%) delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/impl}/DefaultPersistenceTransaction.java (53%) create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java delete mode 100644 src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java rename src/main/java/ch/eitchnet/xmlpers/{api => util}/DomUtil.java (81%) rename src/{test/java/ch/eitchnet/xmlpers/test/impl/rewrite => main/java/ch/eitchnet/xmlpers/util}/FilenameUtility.java (50%) delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java rename src/test/java/ch/eitchnet/xmlpers/test/impl/{rewrite => }/BookDomParser.java (93%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{rewrite => }/BookParserFactory.java (92%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{rewrite => }/BookSaxParser.java (90%) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java rename src/test/java/ch/eitchnet/xmlpers/test/impl/{rewrite => }/ResourceDomParser.java (95%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{rewrite => }/ResourceParserFactory.java (96%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{rewrite => }/ResourceSaxParser.java (94%) delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java diff --git a/pom.xml b/pom.xml index 85a3a0442..bd8741828 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ ch.eitchnet ch.eitchnet.xmlpers jar - 0.2.0-SNAPSHOT + 0.3.0-SNAPSHOT ch.eitchnet.xmlpers https://github.com/eitch/ch.eitchnet.xmlpers diff --git a/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java deleted file mode 100644 index 33ad1db95..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/AbstractDaoFactory.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.PropertiesHelper; -import ch.eitchnet.xmlpers.impl.MetadataXmlDao; -import ch.eitchnet.xmlpers.impl.XmlPersistenceDomHandler; -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; -import ch.eitchnet.xmlpers.impl.XmlPersistenceSaxHandler; - -/** - * @author Robert von Burg - */ -public abstract class AbstractDaoFactory implements XmlPersistenceDaoFactory { - - private static final Logger logger = LoggerFactory.getLogger(AbstractDaoFactory.class); - - private XmlIoMode xmlIoMode; - private XmlPersistenceFileDao fileDao; - - @Override - public void initialize(XmlPersistenceFileDao fileDao, Properties properties) { - this.fileDao = fileDao; - // TODO catch and throw proper exception - String xmlIoModeS = PropertiesHelper.getProperty(properties, AbstractDaoFactory.class.getName(), - XmlPersistenceConstants.PROP_XML_IO_MOD, XmlIoMode.SAX.name()); - this.xmlIoMode = XmlIoMode.valueOf(xmlIoModeS.toUpperCase()); - logger.info("Defaut Xml IO Mode is " + this.xmlIoMode.name()); - } - - /** - * @return - * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getMetadataDao() - */ - @Override - public XmlPersistenceMetadataDao getMetadataDao() { - MetadataXmlDao metadataDao = new MetadataXmlDao(); - metadataDao.initialize(this.fileDao); - return metadataDao; - } - - protected XmlIoMode getXmlIoMode() { - return this.xmlIoMode; - } - - protected XmlPersistenceDao initializeDao(XmlPersistenceDao dao) { - if (!(dao instanceof AbstractXmlDao)) { - throw new IllegalArgumentException("Your dao implementation does not extend from " - + AbstractXmlDao.class.getName() + "!"); - } - AbstractXmlDao abstractXmlDao = (AbstractXmlDao) dao; - abstractXmlDao.initialize(this.fileDao, getXmlFileHandler(this.xmlIoMode)); - return dao; - } - - protected XmlPersistenceFileHandler getXmlFileHandler(XmlIoMode ioMode) { - switch (ioMode) { - case DOM: - return new XmlPersistenceDomHandler(); - case SAX: - return new XmlPersistenceSaxHandler(); - default: - throw new IllegalArgumentException("The XmlIoMode " + ioMode + " is not yet supported!"); - } - } -} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java b/src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java deleted file mode 100644 index 321958b0c..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/AbstractXmlDao.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -import java.io.File; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import ch.eitchnet.utils.exceptions.XmlException; -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; - -/** - * @author Robert von Burg - * - */ -public abstract class AbstractXmlDao implements XmlPersistenceDao { - - private XmlPersistenceFileDao fileDao; - private XmlPersistenceFileHandler fileHandler; - - // TODO think about setting some methods to final - // TODO if no sub type is given, then don't search recursively - it means subType does not exist - - void initialize(XmlPersistenceFileDao fileDao, XmlPersistenceFileHandler fileHandler) { - if (fileDao == null || fileHandler == null) - throw new IllegalArgumentException("Neither fileDao nor fileHandler may be null!"); - if (this.fileDao != null) - throw new IllegalStateException("DAO is already initialized!"); - this.fileDao = fileDao; - this.fileHandler = fileHandler; - } - - protected XmlPersistenceFileDao getXmlPersistenceFileDao() { - return this.fileDao; - } - - protected XmlPersistenceFileHandler getXmlPersistenceFileHandler() { - return this.fileHandler; - } - - /** - * @return the fileHandler - */ - protected XmlPersistenceFileHandler getFileHandler() { - return this.fileHandler; - } - - /** - * @return the fileDao - */ - protected XmlPersistenceFileDao getFileDao() { - return this.fileDao; - } - - @Override - public void remove(T object) { - if (getSubType() == null) - this.fileDao.remove(getType(), getId(object)); - else - this.fileDao.remove(getType(), getSubType(), getId(object)); - } - - @Override - public void removeById(String id) { - if (getSubType() == null) - this.fileDao.remove(getType(), id); - else - this.fileDao.remove(getType(), getSubType(), id); - } - - @Override - public void removeAll() { - if (getSubType() == null) - this.fileDao.removeAll(getType()); - else - this.fileDao.removeAll(getType(), getSubType()); - } - - @Override - public Set queryKeySet() { - if (getSubType() == null) - return this.fileDao.queryKeySet(getType()); - return this.fileDao.queryKeySet(getType(), getSubType()); - } - - @Override - public long querySize() { - if (getSubType() == null) - return this.fileDao.querySize(getType()); - return this.fileDao.querySize(getType(), getSubType()); - } - - @Override - public List queryAll() { - - if (getSubType() == null) { - - Set idsByType = this.fileDao.queryKeySet(getType()); - List result = new ArrayList<>(idsByType.size()); - - for (String id : idsByType) { - File objectPath = this.fileDao.getReadPath(getType(), id); - String msg = "Can not read persistence units for {0} / {1} at {2}"; - assertReadable(objectPath, msg, getType(), id, objectPath); - T object = read(objectPath); - result.add(object); - } - - return result; - } - - Set idsByType = this.fileDao.queryKeySet(getType(), getSubType()); - List result = new ArrayList<>(idsByType.size()); - - for (String id : idsByType) { - File objectPath = this.fileDao.getReadPath(getType(), getSubType(), id); - String msg = "Can not read persistence units for {0} / {1} / {2} at {3}"; - assertReadable(objectPath, msg, getType(), getSubType(), id, objectPath); - T object = read(objectPath); - result.add(object); - } - - return result; - } - - private void assertReadable(File persistenceUnit, String errorMsg, Object... msgArgs) { - if (!persistenceUnit.canRead()) { - String msg = MessageFormat.format(errorMsg, msgArgs); - throw new XmlException(msg); - } - } - - @Override - public T queryById(String id) { - if (getSubType() == null) { - File persistenceUnit = this.fileDao.getReadPath(getType(), id); - if (!persistenceUnit.exists()) - return null; - String msg = "Can not read persistence unit for {0} / {1} at {2}"; - assertReadable(persistenceUnit, msg, getType(), id, persistenceUnit); - T object = read(persistenceUnit); - return object; - } - - File persistenceUnit = this.fileDao.getReadPath(getType(), getSubType(), id); - if (!persistenceUnit.exists()) - return null; - String msg = "Can not read persistence unit for {0} / {1} / {2} at {3}"; - assertReadable(persistenceUnit, msg, getType(), getSubType(), id, persistenceUnit); - T object = read(persistenceUnit); - return object; - } - - @Override - public void add(T object) { - - File addPath; - if (getSubType() == null) - addPath = this.fileDao.getAddPath(getType(), getId(object)); - else - addPath = this.fileDao.getAddPath(getType(), getSubType(), getId(object)); - write(object, addPath); - } - - @Override - public void update(T object) { - File addPath; - if (getSubType() == null) - addPath = this.fileDao.getUpdatePath(getType(), getId(object)); - else - addPath = this.fileDao.getUpdatePath(getType(), getSubType(), getId(object)); - write(object, addPath); - } - - /** - * Returns the type of domain object being handled by this {@link XmlPersistenceDao}. This would in most cases be - * the simple name of the class being persisted - * - * @return the type of object being persisted - */ - protected abstract String getType(); - - /** - * Returns the sub type, enabling categorizing types by a sub type. Default implementation returns null, thus no - * categorization is performed for this {@link XmlPersistenceDao} implementation - * - * @return the sub type to further categorize the type of object being persisted - */ - protected String getSubType() { - return null; - } - - protected abstract String getId(T object); - - protected abstract T read(File filePath); - - protected abstract void write(T object, File filePath); -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java b/src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java deleted file mode 100644 index 0128f7bed..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/DaoContext.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -/** - * @author Robert von Burg - * - * @param - */ -public interface DaoContext { - - public String getType(); - - public String getSubType(); - - public String getId(); - - public boolean hasSubType(); - - public T getObject(); - - public U getIoContext(); -} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java new file mode 100644 index 000000000..2c0c3e0ca --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import java.io.File; +import java.text.MessageFormat; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.xmlpers.impl.PathBuilder; +import ch.eitchnet.xmlpers.objref.ObjectRef; + +public class FileDao { + + private static final Logger logger = LoggerFactory.getLogger(FileDao.class); + + private final PersistenceTransaction tx; + private final boolean verbose; + private final PathBuilder pathBuilder; + + public FileDao(PersistenceTransaction tx, PathBuilder pathBuilder, boolean verbose) { + this.tx = tx; + this.pathBuilder = pathBuilder; + this.verbose = verbose; + } + + private void assertIsIdRef(IoOperation ioOperation, ObjectRef objectRef) { + if (!objectRef.isLeaf()) { + String msg = "A {0} operation can only be performed with IdRefs!"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, ioOperation); + throw new XmlPersistenceException(msg); + } + } + + public void performCreate(PersistenceContext ctx) { + ObjectRef objectRef = ctx.getObjectRef(); + assertIsIdRef(IoOperation.CREATE, objectRef); + File path = objectRef.getPath(this.pathBuilder); + logPath(IoOperation.CREATE, path, objectRef); + assertPathNotExists(path, objectRef); + createMissingParents(path, objectRef); + FileIo fileIo = new FileIo(path); + this.tx.getIoMode().write(ctx, fileIo); + } + + public void performRead(PersistenceContext ctx) { + ObjectRef objectRef = ctx.getObjectRef(); + assertIsIdRef(IoOperation.READ, objectRef); + File path = objectRef.getPath(this.pathBuilder); + if (!path.exists()) { + ctx.setObject(null); + return; + } + + logPath(IoOperation.READ, path, objectRef); + FileIo fileIo = new FileIo(path); + this.tx.getIoMode().read(ctx, fileIo); + } + + public void performUpdate(PersistenceContext ctx) { + ObjectRef objectRef = ctx.getObjectRef(); + assertIsIdRef(IoOperation.UPDATE, objectRef); + File path = objectRef.getPath(this.pathBuilder); + logPath(IoOperation.UPDATE, path, objectRef); + assertPathIsFileAndWritable(path, objectRef); + FileIo fileIo = new FileIo(path); + this.tx.getIoMode().write(ctx, fileIo); + } + + public void performDelete(PersistenceContext ctx) { + ObjectRef objectRef = ctx.getObjectRef(); + assertIsIdRef(IoOperation.DELETE, objectRef); + File path = objectRef.getPath(this.pathBuilder); + logPath(IoOperation.DELETE, path, objectRef); + assertPathIsFileAndWritable(path, objectRef); + if (!path.delete()) { + String msg = "Failed to delete file {0}"; //$NON-NLS-1$ + throw new RuntimeException(MessageFormat.format(msg, path.getAbsolutePath())); + } + + ObjectRef parentRef = objectRef.getParent(this.tx); + deleteEmptyDirectories(parentRef); + } + + private void deleteEmptyDirectories(ObjectRef objectRef) { + + // root can't be deleted + if (objectRef.isRoot()) + return; + + if (objectRef.isLeaf()) { + throw new IllegalArgumentException("IdRefs don't reference directories!"); //$NON-NLS-1$ + } + + File directoryPath = objectRef.getPath(this.pathBuilder); + if (!directoryPath.isDirectory()) { + String msg = "The path for {0} is not a directory: {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), directoryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + + // stop if empty + if (directoryPath.list().length != 0) + return; + + // delete + if (!directoryPath.delete()) { + String msg = "Deletion of empty directory for {0} at {1} failed! Check file permissions!"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), directoryPath.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + + // log + if (this.verbose) { + String msg = "Deleted empty directory for {0} at {1}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, objectRef.getName(), directoryPath)); + } + + // recursively delete + ObjectRef parent = objectRef.getParent(this.tx); + deleteEmptyDirectories(parent); + } + + private void logPath(IoOperation operation, File path, ObjectRef objectRef) { + if (this.verbose) { + String msg = "Path for operation {0} for {1} is at {2}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, operation, objectRef.getName(), path.getAbsolutePath()); + } + } + + private void createMissingParents(File path, ObjectRef objectRef) { + File parentFile = path.getParentFile(); + if (!parentFile.exists() && !parentFile.mkdirs()) { + String msg = "Could not create parent path for {0} at {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), path.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + } + + private void assertPathIsFileAndWritable(File path, ObjectRef objectRef) { + if (!path.exists()) { + String msg = "Persistence unit does not exist for {0} at {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), path.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + + if (!path.isFile() || !path.canWrite()) { + String msg; + msg = "Persistence unit is not a file or is not readable for {0} at {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), path.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + } + + private void assertPathNotExists(File path, ObjectRef objectRef) { + if (path.exists()) { + String msg = "Persistence unit already exists for {0} at {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), path.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + } + +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java similarity index 72% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java rename to src/main/java/ch/eitchnet/xmlpers/api/FileIo.java index 7e64e45c0..0623b1ef5 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileIo.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; import java.io.File; import java.io.FileWriter; @@ -54,12 +54,7 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.helper.XmlHelper; -import ch.eitchnet.xmlpers.api.DomParser; -import ch.eitchnet.xmlpers.api.DomUtil; -import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.util.DomUtil; public class FileIo { @@ -74,45 +69,7 @@ public class FileIo { this.path = path; } - public void write(PersistenceContext context) { - switch (context.getIoMode()) { - case DOM: - writeDom(context); - break; - case SAX: - writeSax(context); - break; - case DEFAULT: - logger.info("Using default XML IO Handler SAX"); //$NON-NLS-1$ - writeSax(context); - break; - default: - String msg = "The Xml IO Mode {0} is not supported!"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getIoMode()); - throw new UnsupportedOperationException(msg); - } - } - - public void read(PersistenceContext context) { - switch (context.getIoMode()) { - case DOM: - readDom(context); - break; - case SAX: - readSax(context); - break; - case DEFAULT: - logger.info("Using default XML IO Handler SAX"); //$NON-NLS-1$ - readSax(context); - break; - default: - String msg = "The Xml IO Mode {0} is not supported!"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getIoMode()); - throw new UnsupportedOperationException(msg); - } - } - - private void writeSax(PersistenceContext context) { + public void writeSax(PersistenceContext ctx) { XMLStreamWriter writer = null; try { @@ -127,8 +84,8 @@ public class FileIo { // then delegate object writing to caller XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); - SaxParser saxParser = context.getParserFactor().getSaxParser(); - saxParser.setObject(context.getObject()); + SaxParser saxParser = ctx.getParserFactor().getSaxParser(); + saxParser.setObject(ctx.getObject()); saxParser.write(xmlWriter); // and now end @@ -148,33 +105,37 @@ public class FileIo { logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); } - private void readSax(PersistenceContext context) { + public void readSax(PersistenceContext ctx) { try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); - SaxParser saxParser = context.getParserFactor().getSaxParser(); + SaxParser saxParser = ctx.getParserFactor().getSaxParser(); DefaultHandler defaultHandler = saxParser.getDefaultHandler(); sp.parse(this.path, defaultHandler); - context.setObject(saxParser.getObject()); + + String msg = "SAX parsed file {0}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); + + ctx.setObject(saxParser.getObject()); } catch (ParserConfigurationException | SAXException | IOException e) { String msg = "Parsing failed due to internal error: {0}"; //$NON-NLS-1$ throw new XmlPersistenceException(MessageFormat.format(msg, e.getMessage()), e); } - - String msg = "SAX parsed file {0}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); } - private void writeDom(PersistenceContext context) { + public void writeDom(PersistenceContext ctx) { + String lineSep = System.getProperty(XmlHelper.PROP_LINE_SEPARATOR); + try { - DomParser domParser = context.getParserFactor().getDomParser(); - domParser.setObject(context.getObject()); + + DomParser domParser = ctx.getParserFactor().getDomParser(); + domParser.setObject(ctx.getObject()); Document document = domParser.toDom(); String encoding = document.getInputEncoding(); if (encoding == null || encoding.isEmpty()) { @@ -206,31 +167,38 @@ public class FileIo { logger.info(msg); } catch (TransformerFactoryConfigurationError | TransformerException e) { + if (this.path.exists()) this.path.delete(); + String msg = "Writing to file failed due to internal error: {0}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, e.getMessage()); throw new XmlException(msg, e); + } finally { System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep); } } - private void readDom(PersistenceContext context) { + public void readDom(PersistenceContext ctx) { + try { + DocumentBuilder docBuilder = DomUtil.createDocumentBuilder(); Document document = docBuilder.parse(this.path); - DomParser domParser = context.getParserFactor().getDomParser(); + DomParser domParser = ctx.getParserFactor().getDomParser(); domParser.fromDom(document); - context.setObject(domParser.getObject()); + + String msg = "DOM parsed file {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, this.path.getAbsolutePath()); + logger.info(msg); + + ctx.setObject(domParser.getObject()); + } catch (SAXException | IOException e) { String msg = "Parsing failed due to internal error: {0}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, e.getMessage()); throw new XmlPersistenceException(msg, e); } - - String msg = "DOM parsed file {0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, this.path.getAbsolutePath()); - logger.info(msg); } } \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoContext.java b/src/main/java/ch/eitchnet/xmlpers/api/IoContext.java deleted file mode 100644 index 641eb3914..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/IoContext.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -/** - * @author Robert von Burg - * - */ -public interface IoContext { - - // marker interface -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java b/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java similarity index 53% rename from src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java rename to src/main/java/ch/eitchnet/xmlpers/api/IoMode.java index 081660b04..7464bff31 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDomContextData.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java @@ -21,29 +21,40 @@ */ package ch.eitchnet.xmlpers.api; -import org.w3c.dom.Document; - - /** * @author Robert von Burg * */ -public class XmlPersistenceDomContextData extends XmlPersistenceContextData { +public enum IoMode { - private Document document; + DOM { + @Override + public void write(PersistenceContext ctx, FileIo fileIo) { + fileIo.writeDom(ctx); + } - /** - * @return the document - */ - public Document getDocument() { - return this.document; + @Override + public void read(PersistenceContext ctx, FileIo fileIo) { + fileIo.readDom(ctx); + } + }, + SAX { + @Override + public void write(PersistenceContext ctx, FileIo fileIo) { + fileIo.writeSax(ctx); + } + + @Override + public void read(PersistenceContext ctx, FileIo fileIo) { + fileIo.readSax(ctx); + } + }; + + public void write(PersistenceContext ctx, FileIo fileIo) { + throw new UnsupportedOperationException("Override me!"); //$NON-NLS-1$ } - /** - * @param document - * the document to set - */ - public void setDocument(Document document) { - this.document = document; + public void read(PersistenceContext ctx, FileIo fileIo) { + throw new UnsupportedOperationException("Override me!"); //$NON-NLS-1$ } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java b/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java new file mode 100644 index 000000000..f60211abe --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java @@ -0,0 +1,6 @@ +package ch.eitchnet.xmlpers.api; + +public enum IoOperation { + + CREATE, READ, UPDATE, DELETE; +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java similarity index 66% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java rename to src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java index 4cf2d287b..b2e57e7e6 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/MetadataDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java @@ -19,9 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertHasType; +package ch.eitchnet.xmlpers.api; import java.io.File; import java.text.MessageFormat; @@ -32,7 +30,9 @@ import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.impl.PathBuilder; +import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.util.FilenameUtility; /** * @author Robert von Burg @@ -42,108 +42,75 @@ public class MetadataDao { private static final Logger logger = LoggerFactory.getLogger(MetadataDao.class); - private final DefaultPersistenceTransaction tx; - private final FileDao fileDao; + private final PersistenceTransaction tx; + private final PathBuilder pathBuilder; private final boolean verbose; - public MetadataDao(DefaultPersistenceTransaction tx, FileDao fileDao, boolean verbose) { + public MetadataDao(PathBuilder pathBuilder, PersistenceTransaction tx, boolean verbose) { this.tx = tx; - this.fileDao = fileDao; + this.pathBuilder = pathBuilder; this.verbose = verbose; } - public Set queryTypeSet(PersistenceContext ctx) { - assertNotClosed(); - assertHasNoSubType(ctx); + public Set queryTypeSet(ObjectRef parentRef) { + assertNotClosed(this.tx); + assertNotIdRef(parentRef); - File queryPath = this.fileDao.getPath(ctx); + File queryPath = parentRef.getPath(this.pathBuilder); Set keySet = queryTypeSet(queryPath); if (this.verbose) { - String msg; - if (!ctx.hasType()) { - msg = "Found {0} types"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, keySet.size()); - } else { - msg = "Found {0} subTypes of type {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, keySet.size(), ctx.getType()); - } - + String msg = "Found {0} types for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), parentRef.getName()); logger.info(msg); } return keySet; } - private void assertHasNoSubType(PersistenceContext ctx) { - if (ctx.hasSubType()) { - throw new RuntimeException("Illegal query: sub type may not be set!"); //$NON-NLS-1$ - } - } + public Set queryKeySet(ObjectRef parentRef) { + assertNotClosed(this.tx); + assertNotRootRef(parentRef); + assertNotIdRef(parentRef); - public Set queryKeySet(PersistenceContext ctx) { - assertNotClosed(); - assertHasType(ctx); - - File queryPath = this.fileDao.getPath(ctx); + File queryPath = parentRef.getPath(this.pathBuilder); Set keySet = queryKeySet(queryPath); if (this.verbose) { - String msg; - if (!ctx.hasSubType()) { - msg = "Found {0} objects of type {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, keySet.size(), ctx.getType()); - } else { - msg = "Found {0} objects of type {1} and subtType {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, keySet.size(), ctx.getType(), ctx.getSubType()); - } - + String msg = "Found {0} objects for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), parentRef.getName()); logger.info(msg); } return keySet; } - public long queryTypeSize(PersistenceContext ctx) { - assertNotClosed(); - assertHasNoSubType(ctx); + public long queryTypeSize(ObjectRef parentRef) { + assertNotClosed(this.tx); + assertNotRootRef(parentRef); + assertNotIdRef(parentRef); - File queryPath = this.fileDao.getPath(ctx); + File queryPath = parentRef.getPath(this.pathBuilder); long numberOfFiles = queryTypeSize(queryPath); if (this.verbose) { - String msg; - if (!ctx.hasType()) { - msg = "Found {0} types"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, numberOfFiles); - } else { - msg = "Found {0} subTypes of type {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, numberOfFiles, ctx.getType()); - } - + String msg = "Found {0} types for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, parentRef.getName()); logger.info(msg); } return numberOfFiles; } - public long querySize(PersistenceContext ctx) { - assertNotClosed(); - assertHasType(ctx); + public long querySize(ObjectRef parentRef) { + assertNotClosed(this.tx); - File queryPath = this.fileDao.getPath(ctx); + File queryPath = parentRef.getPath(this.pathBuilder); long numberOfFiles = querySize(queryPath); if (this.verbose) { - String msg; - if (!ctx.hasSubType()) { - msg = "Found {0} objects of type {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, numberOfFiles, ctx.getType()); - } else { - msg = "Found {0} objects of type {1} and subtType {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, numberOfFiles, ctx.getType(), ctx.getSubType()); - } - + String msg = "Found {0} objects for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, parentRef.getName()); logger.info(msg); } @@ -159,8 +126,16 @@ public class MetadataDao { * @return a set of types in the given query path */ private Set queryTypeSet(File queryPath) { - Set keySet = new HashSet(); + if (!queryPath.exists()) + return Collections.emptySet(); + if (!queryPath.isDirectory()) { + String msg = "The path is not a directory, thus can not query type set for it: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, queryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + + Set keySet = new HashSet(); File[] subTypeFiles = queryPath.listFiles(); for (File subTypeFile : subTypeFiles) { if (subTypeFile.isFile()) { @@ -263,10 +238,26 @@ public class MetadataDao { return numberOfFiles; } - private void assertNotClosed() { - if (!this.tx.isOpen()) { + private void assertNotClosed(PersistenceTransaction tx) { + if (!tx.isOpen()) { String msg = "Transaction has been closed and thus no operation can be performed!"; //$NON-NLS-1$ throw new IllegalStateException(msg); } } + + private void assertNotIdRef(ObjectRef objectRef) { + if (objectRef.isLeaf()) { + String msg = "IdRef not allowed: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName()); + throw new IllegalArgumentException(msg); + } + } + + private void assertNotRootRef(ObjectRef objectRef) { + if (objectRef.isRoot()) { + String msg = "RootRef not allowed: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName()); + throw new IllegalArgumentException(msg); + } + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java similarity index 60% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java rename to src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index 44957ff8a..ef5ead550 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -19,19 +19,20 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; -import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertHasId; -import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertHasType; -import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertNotNull; -import static ch.eitchnet.xmlpers.test.impl.rewrite.AssertionUtil.assertObjectRead; +import static ch.eitchnet.xmlpers.util.AssertionUtil.assertIsIdRef; +import static ch.eitchnet.xmlpers.util.AssertionUtil.assertIsNotIdRef; +import static ch.eitchnet.xmlpers.util.AssertionUtil.assertIsNotRootRef; +import static ch.eitchnet.xmlpers.util.AssertionUtil.assertNotNull; +import static ch.eitchnet.xmlpers.util.AssertionUtil.assertObjectRead; import java.util.ArrayList; import java.util.List; import java.util.Set; import ch.eitchnet.utils.objectfilter.ObjectFilter; -import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.objref.ObjectRef; /** * @author Robert von Burg @@ -39,10 +40,9 @@ import ch.eitchnet.xmlpers.api.PersistenceContext; */ public class ObjectDao { - private final PersistenceTransaction tx; private final ObjectFilter objectFilter; private final FileDao fileDao; - private boolean closed; + private final PersistenceTransaction tx; public ObjectDao(PersistenceTransaction tx, FileDao fileDao, ObjectFilter objectFilter) { this.tx = tx; @@ -92,83 +92,76 @@ public class ObjectDao { this.objectFilter.removeAll((List) objects); } - public void removeById(PersistenceContext context) { + public void removeById(ObjectRef objectRef) { assertNotClosed(); - assertHasType(context); - assertHasId(context); - this.objectFilter.remove(context.clone()); + assertIsIdRef(objectRef); + this.objectFilter.remove(objectRef); } - public void removeAll(PersistenceContext context) { + public void removeAll(ObjectRef parentRef) { assertNotClosed(); - assertHasType(context); + assertIsNotIdRef(parentRef); + assertIsNotRootRef(parentRef); - Set keySet = queryKeySet(context); + Set keySet = queryKeySet(parentRef); for (String id : keySet) { - PersistenceContext clone = context.clone(); - clone.setId(id); - this.objectFilter.remove(clone); + + ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); + PersistenceContext childCtx = childRef. createPersistenceContext(this.tx); + + this.objectFilter.remove(childCtx); } } - public T queryById(PersistenceContext context) { + public T queryById(ObjectRef objectRef) { assertNotClosed(); - assertHasType(context); - assertHasId(context); - this.fileDao.performRead(context); - return context.getObject(); + assertIsIdRef(objectRef); + PersistenceContext ctx = objectRef. createPersistenceContext(this.tx); + this.fileDao.performRead(ctx); + return ctx.getObject(); } - public List queryAll(PersistenceContext context) { + public List queryAll(ObjectRef parentRef) { assertNotClosed(); - assertHasType(context); + assertIsNotIdRef(parentRef); MetadataDao metadataDao = this.tx.getMetadataDao(); - Set keySet = metadataDao.queryKeySet(context); + Set keySet = metadataDao.queryKeySet(parentRef); List result = new ArrayList<>(); - PersistenceContext readContext = context.clone(); for (String id : keySet) { - readContext.setId(id); - this.fileDao.performRead(readContext); - assertObjectRead(readContext); - result.add(readContext.getObject()); + + ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); + PersistenceContext childCtx = childRef.createPersistenceContext(this.tx); + + this.fileDao.performRead(childCtx); + assertObjectRead(childCtx); + result.add(childCtx.getObject()); } return result; } - public Set queryKeySet(PersistenceContext context) { + public Set queryKeySet(ObjectRef parentRef) { assertNotClosed(); - assertHasType(context); - - assertNotClosed(); - assertHasType(context); + assertIsNotIdRef(parentRef); MetadataDao metadataDao = this.tx.getMetadataDao(); - Set keySet = metadataDao.queryKeySet(context); + Set keySet = metadataDao.queryKeySet(parentRef); return keySet; } - public long querySize(PersistenceContext context) { + public long querySize(ObjectRef parentRef) { assertNotClosed(); - assertHasType(context); - - assertNotClosed(); - assertHasType(context); + assertIsNotIdRef(parentRef); MetadataDao metadataDao = this.tx.getMetadataDao(); - long size = metadataDao.querySize(context); + long size = metadataDao.querySize(parentRef); return size; } - public void rollback() { - this.objectFilter.clearCache(); - this.closed = true; - } - private void assertNotClosed() { - if (this.closed || !this.tx.isOpen()) + if (!this.tx.isOpen()) throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); //$NON-NLS-1$ } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java similarity index 95% rename from src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java rename to src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java index f1968952e..c06b54717 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceConstants.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java @@ -25,7 +25,8 @@ package ch.eitchnet.xmlpers.api; * @author Robert von Burg * */ -public class XmlPersistenceConstants { +@SuppressWarnings("nls") +public class PersistenceConstants { private static final String PROP_PREFIX = "ch.eitchnet.xmlpers."; public static final String PROP_VERBOSE = PROP_PREFIX + "verbose"; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index 42d36b99c..5a074832f 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -21,44 +21,20 @@ */ package ch.eitchnet.xmlpers.api; -import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.xmlpers.objref.ObjectRef; public class PersistenceContext { + private final ObjectRef objectRef; private T object; - private String type; - private String subType; - private String id; - - private XmlIoMode ioMode; private ParserFactory parserFactory; - public PersistenceContext() { - this.ioMode = XmlIoMode.DEFAULT; + public PersistenceContext(ObjectRef objectRef) { + this.objectRef = objectRef; } - public String getType() { - return this.type; - } - - public void setType(String type) { - this.type = type; - } - - public String getSubType() { - return this.subType; - } - - public void setSubType(String subType) { - this.subType = subType; - } - - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id = id; + public ObjectRef getObjectRef() { + return this.objectRef; } public T getObject() { @@ -69,14 +45,6 @@ public class PersistenceContext { this.object = object; } - public XmlIoMode getIoMode() { - return this.ioMode; - } - - public void setIoMode(XmlIoMode ioMode) { - this.ioMode = ioMode; - } - public ParserFactory getParserFactor() { return this.parserFactory; } @@ -84,28 +52,4 @@ public class PersistenceContext { public void setParserFactory(ParserFactory parserFactory) { this.parserFactory = parserFactory; } - - public boolean hasType() { - return !StringHelper.isEmpty(this.type); - } - - public boolean hasSubType() { - return !StringHelper.isEmpty(this.subType); - } - - public boolean hasId() { - return !StringHelper.isEmpty(this.id); - } - - @Override - public PersistenceContext clone() { - PersistenceContext clone = new PersistenceContext<>(); - clone.type = this.type; - clone.subType = this.subType; - clone.id = this.id; - clone.ioMode = this.ioMode; - clone.parserFactory = this.parserFactory; - clone.object = this.object; - return clone; - } } \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java new file mode 100644 index 000000000..2735d4aeb --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java @@ -0,0 +1,12 @@ +package ch.eitchnet.xmlpers.api; + +import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; + +public interface PersistenceContextFactory { + + public PersistenceContext createCtx(ObjectRef objectRef); + + public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, T t); + +} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java new file mode 100644 index 000000000..92bff9299 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.api; + +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; + +/** + * @author Robert von Burg + * + */ +public class PersistenceContextFactoryDelegator { + + private Map> contextFactoryCacheByType; + private Map, PersistenceContextFactory> contextFactoryCacheByClass; + + public PersistenceContextFactoryDelegator() { + this.contextFactoryCacheByType = new HashMap<>(); + this.contextFactoryCacheByClass = new HashMap<>(); + } + + public void registerPersistenceContextFactory(Class classType, String type, + PersistenceContextFactory ctxFactory) { + this.contextFactoryCacheByClass.put(classType, ctxFactory); + this.contextFactoryCacheByType.put(type, ctxFactory); + } + + public PersistenceContextFactory getCtxFactory(Class classType) { + + @SuppressWarnings("unchecked") + PersistenceContextFactory ctxFactory = (PersistenceContextFactory) this.contextFactoryCacheByClass + .get(classType); + if (ctxFactory != null) + return ctxFactory; + + String msg = "No context factory is registered for {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, classType); + throw new IllegalArgumentException(msg); + } + + public PersistenceContextFactory getCtxFactory(String type) { + + @SuppressWarnings("unchecked") + PersistenceContextFactory ctxFactory = (PersistenceContextFactory) this.contextFactoryCacheByType + .get(type); + if (ctxFactory != null) + return ctxFactory; + + String msg = "No context factory is registered for type {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, type); + throw new IllegalArgumentException(msg); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java similarity index 76% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java rename to src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java index e57d02ca8..1d4d93fab 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java @@ -19,14 +19,20 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; /** * @author Robert von Burg * */ -public interface XmlPersistenceManager { +public interface PersistenceManager { + public static final String DEFAULT_REALM = "defaultRealm"; //$NON-NLS-1$ + + public PersistenceContextFactoryDelegator getCtxFactory(); + public PersistenceTransaction openTx(); + + public PersistenceTransaction openTx(String realm); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java similarity index 83% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java rename to src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java index 4fbc34527..64e6aef82 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/XmlPersistenceManagerLoader.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java @@ -19,17 +19,19 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; import java.util.Properties; +import ch.eitchnet.xmlpers.impl.DefaultXmlPersistenceManager; + /** * @author Robert von Burg * */ -public class XmlPersistenceManagerLoader { +public class PersistenceManagerLoader { - public static XmlPersistenceManager load(Properties properties) { + public static PersistenceManager load(Properties properties) { DefaultXmlPersistenceManager persistenceManager = new DefaultXmlPersistenceManager(); persistenceManager.initialize(properties); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java new file mode 100644 index 000000000..a83eeb014 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java @@ -0,0 +1,24 @@ +package ch.eitchnet.xmlpers.api; + +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; + +public interface PersistenceRealm { + + /** + * @return the realm + */ + public abstract String getRealmName(); + + public abstract PersistenceContextFactoryDelegator getCtxFactoryDelegator(); + + /** + * @return the objectRefCache + */ + public abstract ObjectReferenceCache getObjectRefCache(); + + /** + * @return the persistenceManager + */ + public abstract PersistenceManager getPersistenceManager(); + +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java similarity index 63% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java rename to src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java index 1109d65d1..0600aa2cf 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java @@ -19,19 +19,24 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.api; -import ch.eitchnet.xmlpers.api.XmlIoMode; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; /** * @author Robert von Burg * */ -public interface PersistenceTransaction { +public interface PersistenceTransaction extends AutoCloseable { - public void commit(PersistenceContextFactory ctxFactory); + public void setCloseStrategy(TransactionCloseStrategy closeStrategy); - public void rollback(); + public void autoCloseableCommit(); + + public void autoCloseableRollback(); + + @Override + public void close() throws XmlPersistenceException; public boolean isOpen(); @@ -39,7 +44,11 @@ public interface PersistenceTransaction { public MetadataDao getMetadataDao(); - public XmlIoMode getIoMode(); + public ObjectReferenceCache getObjectRefCache(); - public void setIoMode(XmlIoMode ioMode); + public PersistenceRealm getRealm(); + + public IoMode getIoMode(); + + public void setIoMode(IoMode ioMode); } \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java index 9fc8d1dd9..f6e660175 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java @@ -25,8 +25,6 @@ import javax.xml.stream.XMLStreamException; import org.xml.sax.helpers.DefaultHandler; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; - public interface SaxParser { public T getObject(); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java new file mode 100644 index 000000000..a535fe5c6 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java @@ -0,0 +1,21 @@ +package ch.eitchnet.xmlpers.api; + +public enum TransactionCloseStrategy { + COMMIT() { + @Override + public void close(PersistenceTransaction tx) { + tx.autoCloseableCommit(); + } + }, + + ROLLBACK() { + @Override + public void close(PersistenceTransaction tx) { + tx.autoCloseableRollback(); + } + }; + + public void close(PersistenceTransaction tx) { + throw new UnsupportedOperationException("Override in enum!"); //$NON-NLS-1$ + } +} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java deleted file mode 100644 index 99592ff6c..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlIoMode.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -/** - * @author Robert von Burg - * - */ -public enum XmlIoMode { - - DEFAULT, DOM, SAX; -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java deleted file mode 100644 index 821f26ea9..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceContextData.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -import java.io.File; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceContextData { - - private File file; - - /** - * @return the file - */ - public File getFile() { - return this.file; - } - - /** - * @param file - * the file to set - */ - public void setFile(File file) { - this.file = file; - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java deleted file mode 100644 index 8923211fc..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDao.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.api; - -import java.util.List; -import java.util.Set; - -/** - * @author Robert von Burg - */ -public interface XmlPersistenceDao { - - public void add(T object); - - public void update(T object); - - public void remove(T object); - - public void removeById(String id); - - public void removeAll(); - - public T queryById(String id); - - public List queryAll(); - - public Set queryKeySet(); - - public long querySize(); -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java deleted file mode 100644 index 4b5ac1782..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceDaoFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.api; - -import java.util.Properties; - -import ch.eitchnet.xmlpers.impl.XmlPersistenceFileDao; - -/** - * @author Robert von Burg - */ -public interface XmlPersistenceDaoFactory { - - public void initialize(XmlPersistenceFileDao fileDao, Properties properties); - - public XmlPersistenceMetadataDao getMetadataDao(); - - public XmlPersistenceDao getDao(T object); - - public XmlPersistenceDao getDaoBy(String type); - - public XmlPersistenceDao getDaoBy(String type, String subType); -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java deleted file mode 100644 index a3d71c00b..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceFileHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - - -/** - * @author Robert von Burg - * - */ -public interface XmlPersistenceFileHandler { - - public void read(XmlPersistenceContextData contextData); - - public void write(XmlPersistenceContextData contextData); -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java deleted file mode 100644 index 9f814a05a..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceHandler.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -/** - * @author Robert von Burg - * - */ -public interface XmlPersistenceHandler { - - public abstract XmlPersistenceTransaction openTx(); -} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java deleted file mode 100644 index 4f8e74b40..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceMetadataDao.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.api; - -import java.util.Set; - -/** - * @author Robert von Burg - */ -public interface XmlPersistenceMetadataDao { - - public Set queryTypeSet(); - - public Set queryTypeSet(String type); - - public Set queryKeySet(String type); - - public Set queryKeySet(String type, String subType); - - public long queryTypeSize(); - - public long querySubTypeSize(String type); - - public long querySize(String type); - - public long querySize(String type, String subType); -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java deleted file mode 100644 index 8ab786c9a..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxContextData.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -import org.xml.sax.helpers.DefaultHandler; - - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceSaxContextData extends XmlPersistenceContextData { - - private DefaultHandler defaultHandler; - private XmlPersistenceSaxWriter xmlWriter; - - /** - * @return the defaultHandler - */ - public DefaultHandler getDefaultHandler() { - return this.defaultHandler; - } - - /** - * @param defaultHandler - * the defaultHandler to set - */ - public void setDefaultHandler(DefaultHandler defaultHandler) { - this.defaultHandler = defaultHandler; - } - - /** - * @return the xmlWriter - */ - public XmlPersistenceSaxWriter getXmlWriter() { - return this.xmlWriter; - } - - /** - * @param xmlWriter - * the xmlWriter to set - */ - public void setXmlWriter(XmlPersistenceSaxWriter xmlWriter) { - this.xmlWriter = xmlWriter; - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java deleted file mode 100644 index df950f904..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceSaxWriter.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -import javax.xml.stream.XMLStreamException; - -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; - -/** - * @author Robert von Burg - * - */ -public interface XmlPersistenceSaxWriter { - - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException; -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java similarity index 98% rename from src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java rename to src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java index 7294e331d..7a758c901 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceStreamWriter.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.impl; +package ch.eitchnet.xmlpers.api; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java deleted file mode 100644 index ae6545d15..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceTransaction.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.api; - -import java.util.List; - -/** - * @author Robert von Burg - * - */ -public interface XmlPersistenceTransaction { - - /** - * @param object - */ - public abstract void add(T object); - - /** - * @param objects - */ - public abstract void addAll(List objects); - - /** - * @param object - */ - public abstract void update(T object); - - /** - * @param objects - */ - public abstract void updateAll(List objects); - - /** - * @param object - */ - public abstract void remove(T object); - - /** - * @param objects - */ - public abstract void removeAll(List objects); - - /** - * @return the daoFactory - */ - public abstract XmlPersistenceDaoFactory getDaoFactory(); - - /** - * - */ - public abstract void commit(); - - /** - * - */ - public abstract void clear(); -} \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java new file mode 100644 index 000000000..b072576aa --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java @@ -0,0 +1,59 @@ +package ch.eitchnet.xmlpers.impl; + +import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; +import ch.eitchnet.xmlpers.api.PersistenceManager; +import ch.eitchnet.xmlpers.api.PersistenceRealm; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; + +public class DefaultPersistenceRealm implements PersistenceRealm { + private final PersistenceManager persistenceManager; + private final PersistenceContextFactoryDelegator ctxFactory; + private final String realmName; + private final ObjectReferenceCache objectRefCache; + private final PathBuilder pathBuilder; + + public DefaultPersistenceRealm(String realm, PersistenceManager persistenceManager, + PersistenceContextFactoryDelegator ctxFactory, PathBuilder pathBuilder, ObjectReferenceCache objectRefCache) { + this.ctxFactory = ctxFactory; + this.pathBuilder = pathBuilder; + this.realmName = realm; + this.persistenceManager = persistenceManager; + this.objectRefCache = objectRefCache; + } + + /** + * @return the realm + */ + @Override + public String getRealmName() { + return this.realmName; + } + + @Override + public PersistenceContextFactoryDelegator getCtxFactoryDelegator() { + return this.ctxFactory; + } + + /** + * @return the objectRefCache + */ + @Override + public ObjectReferenceCache getObjectRefCache() { + return this.objectRefCache; + } + + /** + * @return the persistenceManager + */ + @Override + public PersistenceManager getPersistenceManager() { + return this.persistenceManager; + } + + /** + * @return the pathBuilder + */ + PathBuilder getPathBuilder() { + return this.pathBuilder; + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java similarity index 53% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java rename to src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index 598ab4dd1..ed1b3fa62 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -19,8 +19,9 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.impl; +import java.text.MessageFormat; import java.util.List; import java.util.Set; @@ -29,8 +30,17 @@ import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.utils.objectfilter.ObjectFilter; +import ch.eitchnet.xmlpers.api.FileDao; +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.MetadataDao; +import ch.eitchnet.xmlpers.api.ObjectDao; import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.XmlIoMode; +import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; +import ch.eitchnet.xmlpers.api.PersistenceRealm; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.api.TransactionCloseStrategy; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; /** * @author Robert von Burg @@ -40,23 +50,36 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { private static final Logger logger = LoggerFactory.getLogger(DefaultPersistenceTransaction.class); - private final FileDao fileDao; + private final DefaultPersistenceRealm realm; + private final boolean verbose; + + private final ObjectFilter objectFilter; private final ObjectDao objectDao; private final MetadataDao metadataDao; - private final ObjectFilter objectFilter; - private final boolean verbose; + + private FileDao fileDao; private boolean committed; private boolean closed; - private XmlIoMode ioMode; + private IoMode ioMode; - public DefaultPersistenceTransaction(FileDao fileDao, boolean verbose) { - this.fileDao = fileDao; + private TransactionCloseStrategy closeStrategy; + + public DefaultPersistenceTransaction(DefaultPersistenceRealm realm, boolean verbose) { + this.realm = realm; this.verbose = verbose; this.objectFilter = new ObjectFilter(); + this.fileDao = new FileDao(this, realm.getPathBuilder(), verbose); this.objectDao = new ObjectDao(this, this.fileDao, this.objectFilter); - this.metadataDao = new MetadataDao(this, this.fileDao, verbose); + this.metadataDao = new MetadataDao(realm.getPathBuilder(), this, verbose); + + this.closeStrategy = TransactionCloseStrategy.COMMIT; + } + + @Override + public PersistenceRealm getRealm() { + return this.realm; } @Override @@ -70,26 +93,45 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { } @Override - public void rollback() { + public ObjectReferenceCache getObjectRefCache() { + return this.realm.getObjectRefCache(); + } + + @Override + public void setCloseStrategy(TransactionCloseStrategy closeStrategy) { + this.closeStrategy = closeStrategy; + } + + @Override + public void close() throws XmlPersistenceException { + this.closeStrategy.close(this); + } + + @Override + public void autoCloseableRollback() { if (this.committed) throw new IllegalStateException("Transaction has already been committed!"); //$NON-NLS-1$ + if (!this.closed) { this.closed = true; - this.objectDao.rollback(); this.objectFilter.clearCache(); } } @Override - public void commit(PersistenceContextFactory ctxFactory) { + public void autoCloseableCommit() throws XmlPersistenceException { + + long start = System.nanoTime(); try { - long start = System.nanoTime(); - if (this.verbose) - logger.info("Committing TX..."); //$NON-NLS-1$ - Set keySet = this.objectFilter.keySet(); + + if (this.verbose) { + String msg = "Committing {0} operations in TX...";//$NON-NLS-1$ + logger.info(MessageFormat.format(msg, keySet.size())); + } + for (String key : keySet) { List removed = this.objectFilter.getRemoved(key); @@ -101,8 +143,11 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$ for (Object object : removed) { - PersistenceContext context = ctxFactory.createCtx(this, object); - this.fileDao.performDelete(context); + PersistenceContextFactoryDelegator ctxFactoryDelegator = this.realm.getCtxFactoryDelegator(); + PersistenceContext ctx = ctxFactoryDelegator.getCtxFactory(object.getClass()) + .createCtx(this.realm.getObjectRefCache(), object); + ctx.setObject(object); + this.fileDao.performDelete(ctx); } } @@ -116,8 +161,11 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { for (Object object : updated) { - PersistenceContext context = ctxFactory.createCtx(this, object); - this.fileDao.performUpdate(context); + PersistenceContextFactoryDelegator ctxFactoryDelegator = this.realm.getCtxFactoryDelegator(); + PersistenceContext ctx = ctxFactoryDelegator.getCtxFactory(object.getClass()) + .createCtx(this.realm.getObjectRefCache(), object); + ctx.setObject(object); + this.fileDao.performUpdate(ctx); } } @@ -131,14 +179,24 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { for (Object object : added) { - PersistenceContext context = ctxFactory.createCtx(this, object); - this.fileDao.performCreate(context); + PersistenceContextFactoryDelegator ctxFactoryDelegator = this.realm.getCtxFactoryDelegator(); + PersistenceContext ctx = ctxFactoryDelegator.getCtxFactory(object.getClass()) + .createCtx(this.realm.getObjectRefCache(), object); + ctx.setObject(object); + this.fileDao.performCreate(ctx); } } } long end = System.nanoTime(); - logger.info("Completed TX in " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ + logger.info("TX completed in " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ + + } catch (Exception e) { + + long end = System.nanoTime(); + logger.info("TX failed after " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ + + throw e; } finally { // clean up @@ -153,12 +211,12 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { } @Override - public void setIoMode(XmlIoMode ioMode) { + public void setIoMode(IoMode ioMode) { this.ioMode = ioMode; } @Override - public XmlIoMode getIoMode() { + public IoMode getIoMode() { return this.ioMode; } } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java new file mode 100644 index 000000000..cab1ddf90 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; +import java.text.MessageFormat; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; +import ch.eitchnet.xmlpers.api.PersistenceManager; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; + +/** + * @author Robert von Burg + * + */ +public class DefaultXmlPersistenceManager implements PersistenceManager { + + protected static final Logger logger = LoggerFactory.getLogger(DefaultXmlPersistenceManager.class); + + protected boolean initialized; + protected boolean verbose; + protected Properties properties; + protected Map realmMap; + private PersistenceContextFactoryDelegator ctxFactory; + + public void initialize(Properties properties) { + if (this.initialized) + throw new IllegalStateException("Already initialized!"); //$NON-NLS-1$ + + String context = DefaultXmlPersistenceManager.class.getSimpleName(); + + // get verbose flag + boolean verbose = PropertiesHelper.getPropertyBool(properties, context, PersistenceConstants.PROP_VERBOSE, + Boolean.FALSE).booleanValue(); + + // validate base path + validateBasePath(properties); + + this.properties = properties; + this.verbose = verbose; + this.realmMap = new HashMap<>(); + this.ctxFactory = new PersistenceContextFactoryDelegator(); + } + + private void validateBasePath(Properties properties) { + String context = DefaultXmlPersistenceManager.class.getSimpleName(); + String basePath = PropertiesHelper.getProperty(properties, context, PersistenceConstants.PROP_BASEPATH, null); + + // validate base path exists and is writable + File basePathF = new File(basePath); + if (!basePathF.exists()) + throw new XmlPersistenceException(MessageFormat.format("The database store path does not exist at {0}", //$NON-NLS-1$ + basePathF.getAbsolutePath())); + if (!basePathF.canWrite()) + throw new XmlPersistenceException(MessageFormat.format("The database store path is not writeable at {0}", //$NON-NLS-1$ + basePathF.getAbsolutePath())); + } + + @Override + public PersistenceContextFactoryDelegator getCtxFactory() { + return this.ctxFactory; + } + + @Override + public PersistenceTransaction openTx() { + return openTx(DEFAULT_REALM); + } + + @Override + public synchronized PersistenceTransaction openTx(String realmName) { + + DefaultPersistenceRealm persistenceRealm = this.realmMap.get(realmName); + if (persistenceRealm == null) { + + PathBuilder pathBuilder = new PathBuilder(realmName, this.properties); + ObjectReferenceCache objectRefCache = new ObjectReferenceCache(realmName); + persistenceRealm = new DefaultPersistenceRealm(realmName, this, this.ctxFactory, pathBuilder, objectRefCache); + + this.realmMap.put(realmName, persistenceRealm); + } + + PersistenceTransaction tx = new DefaultPersistenceTransaction(persistenceRealm, this.verbose); + return tx; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java deleted file mode 100644 index 80dbd6317..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/MetadataXmlDao.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.impl; - -import java.util.Set; - -import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; - -/** - * @author Robert von Burg - * - */ -public class MetadataXmlDao implements XmlPersistenceMetadataDao { - - private XmlPersistenceFileDao fileDao; - - public void initialize(XmlPersistenceFileDao fileDao) { - if (fileDao == null) - throw new IllegalArgumentException("fileDao may not be null!"); - if (this.fileDao != null) - throw new IllegalStateException("DAO is already initialized!"); - this.fileDao = fileDao; - } - - /** - * @return the fileDao - */ - protected XmlPersistenceFileDao getFileDao() { - return this.fileDao; - } - - @Override - public Set queryTypeSet() { - return this.fileDao.queryTypeSet(); - } - - @Override - public Set queryTypeSet(String type) { - return this.fileDao.queryTypeSet(type); - } - - @Override - public Set queryKeySet(String type) { - return this.fileDao.queryKeySet(type); - } - - @Override - public Set queryKeySet(String type, String subType) { - return this.fileDao.queryKeySet(type, subType); - } - - @Override - public long queryTypeSize() { - return this.fileDao.queryTypeSize(); - } - - @Override - public long querySubTypeSize(String type) { - return this.fileDao.queryTypeSize(type); - } - - @Override - public long querySize(String type) { - return this.fileDao.querySize(type); - } - - @Override - public long querySize(String type, String subType) { - return this.fileDao.querySize(type, subType); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java new file mode 100644 index 000000000..a0f593c07 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2012 + * + * This file is part of ch.eitchnet.java.xmlpers + * + * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with ch.eitchnet.java.xmlpers. If not, see . + * + */ +package ch.eitchnet.xmlpers.impl; + +import java.io.File; +import java.io.IOException; +import java.text.MessageFormat; +import java.util.Properties; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; + +/** + * @author Robert von Burg + */ +public class PathBuilder { + + private static final Logger logger = LoggerFactory.getLogger(PathBuilder.class); + + public static final String FILE_EXT = ".xml"; //$NON-NLS-1$ + public static final int EXT_LENGTH = PathBuilder.FILE_EXT.length(); + + private final String basePath; + + public PathBuilder(String realm, Properties properties) { + + // get properties + String context = PathBuilder.class.getSimpleName(); + String basePath = PropertiesHelper.getProperty(properties, context, PersistenceConstants.PROP_BASEPATH, null); + + // validate base path exists and is writable + File basePathF = new File(basePath); + if (!basePathF.exists()) + throw new XmlPersistenceException(MessageFormat.format("The database store path does not exist at {0}", //$NON-NLS-1$ + basePathF.getAbsolutePath())); + if (!basePathF.canWrite()) + throw new XmlPersistenceException(MessageFormat.format("The database store path is not writeable at {0}", //$NON-NLS-1$ + basePathF.getAbsolutePath())); + + File realmPathF = new File(basePathF, realm); + if (!realmPathF.exists() && !realmPathF.mkdir()) + throw new XmlPersistenceException(MessageFormat.format("Could not create path for realm {0} at {1}", //$NON-NLS-1$ + realm, basePathF.getAbsolutePath())); + + // we want a clean base path + String canonicalBasePath; + try { + canonicalBasePath = realmPathF.getCanonicalPath(); + } catch (IOException e) { + throw new XmlPersistenceException(MessageFormat.format( + "Failed to build canonical path from {0}", realmPathF.getAbsolutePath()), e); //$NON-NLS-1$ + } + + // this.basePathF = basePathF; + this.basePath = canonicalBasePath; + logger.info(MessageFormat.format("Using base path {0}", this.basePath)); //$NON-NLS-1$ + } + + String getFilename(String id) { + return id.concat(PathBuilder.FILE_EXT); + } + + String getPathAsString(String type, String subType, String id) { + StringBuilder sb = new StringBuilder(this.basePath); + if (!StringHelper.isEmpty(type)) { + sb.append(File.separatorChar); + sb.append(type); + } + if (!StringHelper.isEmpty(subType)) { + sb.append(File.separatorChar); + sb.append(subType); + } + if (!StringHelper.isEmpty(id)) { + sb.append(File.separatorChar); + sb.append(getFilename(id)); + } + + return sb.toString(); + } + + public File getRootPath() { + File path = new File(getPathAsString(null, null, null)); + return path; + } + + public File getTypePath(String type) { + File path = new File(getPathAsString(type, null, null)); + return path; + } + + public File getSubTypePath(String type, String subType) { + File path = new File(getPathAsString(type, subType, null)); + return path; + } + + public File getIdOfTypePath(String type, String id) { + File path = new File(getPathAsString(type, null, id)); + return path; + } + + public File getIdOfSubTypePath(String type, String subType, String id) { + File path = new File(getPathAsString(type, subType, id)); + return path; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java b/src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java deleted file mode 100644 index 3aa95a8ec..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/TransactionDaoFactoryFacade.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.impl; - -import java.util.Properties; - -import ch.eitchnet.xmlpers.api.XmlPersistenceDao; -import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; - -/** - * @author Robert von Burg - * - */ -public class TransactionDaoFactoryFacade implements XmlPersistenceDaoFactory { - - private XmlPersistenceDaoFactory daoFactory; - private XmlPersistenceTransactionImpl tx; - - TransactionDaoFactoryFacade(XmlPersistenceDaoFactory daoFactory) { - this.daoFactory = daoFactory; - } - - void setTx(XmlPersistenceTransactionImpl tx) { - this.tx = tx; - } - - /** - * @throws UnsupportedOperationException - * as this method may not be called on the facade - */ - @Override - public void initialize(XmlPersistenceFileDao fileDao, Properties properties) throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - /** - * @return - * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getMetadataDao() - */ - @Override - public XmlPersistenceMetadataDao getMetadataDao() { - assertTxOpen(); - return this.daoFactory.getMetadataDao(); - } - - /** - * @param object - * @return - * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getDao(java.lang.Object) - */ - @Override - public XmlPersistenceDao getDao(T object) { - assertTxOpen(); - return this.daoFactory.getDao(object); - } - - /** - * @param type - * @return - * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getDaoBy(java.lang.String) - */ - @Override - public XmlPersistenceDao getDaoBy(String type) { - assertTxOpen(); - return this.daoFactory.getDaoBy(type); - } - - /** - * @param type - * @param subType - * @return - * @see ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory#getDaoBy(java.lang.String, java.lang.String) - */ - @Override - public XmlPersistenceDao getDaoBy(String type, String subType) { - assertTxOpen(); - return this.daoFactory.getDaoBy(type, subType); - } - - private void assertTxOpen() { - if (this.tx.isCleared()) { - throw new XmlPersistenceException( - "The transaction has already been closed, thus no operation may be performed anymore with this dao factory instance"); - } - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java deleted file mode 100644 index 30484e387..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceDomHandler.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.impl; - -import java.io.File; -import java.io.IOException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.xml.sax.SAXException; - -import ch.eitchnet.utils.exceptions.XmlException; -import ch.eitchnet.utils.helper.XmlHelper; -import ch.eitchnet.xmlpers.api.DomUtil; -import ch.eitchnet.xmlpers.api.XmlPersistenceContextData; -import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceDomHandler implements XmlPersistenceFileHandler { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceDomHandler.class); - - @Override - public void read(XmlPersistenceContextData contextData) { - - XmlPersistenceDomContextData cd = (XmlPersistenceDomContextData) contextData; - - // check assertions - if (cd.getFile() == null) - throw new IllegalStateException("No file has been set on the context data!"); - - try { - DocumentBuilder docBuilder = DomUtil.createDocumentBuilder(); - File file = cd.getFile(); - Document document = docBuilder.parse(file); - cd.setDocument(document); - } catch (SAXException | IOException e) { - throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); - } - - logger.info("DOM parsed file " + cd.getFile().getAbsolutePath()); - } - - @Override - public void write(XmlPersistenceContextData contextData) { - - XmlPersistenceDomContextData cd = (XmlPersistenceDomContextData) contextData; - - // check assertions - if (cd.getFile() == null) - throw new IllegalStateException("No file has been set on the context data!"); - if (cd.getDocument() == null) - throw new IllegalStateException("No document has been set on the context data!"); - - String lineSep = System.getProperty(XmlHelper.PROP_LINE_SEPARATOR); - try { - Document document = cd.getDocument(); - String encoding = document.getInputEncoding(); - if (encoding == null || encoding.isEmpty()) { - logger.info("No encoding passed. Using default encoding " + XmlHelper.DEFAULT_ENCODING); - encoding = XmlHelper.DEFAULT_ENCODING; - } - - if (!lineSep.equals("\n")) { - logger.info("Overriding line separator to \\n"); - System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, "\n"); - } - - // Set up a transformer - TransformerFactory transfac = TransformerFactory.newInstance(); - Transformer transformer = transfac.newTransformer(); - transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.METHOD, "xml"); - transformer.setOutputProperty(OutputKeys.ENCODING, encoding); - transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); - // transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\t"); - - // Transform to file - StreamResult result = new StreamResult(cd.getFile()); - Source xmlSource = new DOMSource(document); - transformer.transform(xmlSource, result); - - logger.info("Wrote DOM to " + cd.getFile().getAbsolutePath()); - - } catch (TransformerFactoryConfigurationError | TransformerException e) { - throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); - } finally { - System.setProperty(XmlHelper.PROP_LINE_SEPARATOR, lineSep); - } - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java deleted file mode 100644 index ae905546a..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileDao.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.impl; - -import java.io.File; -import java.text.MessageFormat; -import java.util.Collections; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.PropertiesHelper; -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.test.impl.rewrite.FilenameUtility; - -/** - * @author Robert von Burg - */ -public class XmlPersistenceFileDao { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceFileDao.class); - - private boolean verbose; - private XmlPersistencePathBuilder pathBuilder; - - public XmlPersistenceFileDao(XmlPersistencePathBuilder pathBuilder, Properties properties) { - - // get properties - String context = XmlPersistencePathBuilder.class.getSimpleName(); - boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, - Boolean.FALSE).booleanValue(); - - // initialize - this.verbose = verbose; - this.pathBuilder = pathBuilder; - } - - /** - * Does a recursive and complete deletion of all objects, types and sub-types - */ - public void removeAll() { - - Set types = queryTypeSet(); - for (String type : types) { - - Set idsByType = queryKeySet(type); - for (String id : idsByType) { - remove(type, id); - } - - Set subTypes = queryTypeSet(type); - for (String subType : subTypes) { - - Set idsBySubType = queryKeySet(type, subType); - for (String id : idsBySubType) { - remove(type, subType, id); - } - } - } - } - - public void removeAll(String type) { - - Set idsByType = queryKeySet(type); - for (String id : idsByType) { - remove(type, id); - } - - Set subTypes = queryTypeSet(type); - for (String subType : subTypes) { - - Set idsBySubType = queryKeySet(type, subType); - for (String id : idsBySubType) { - remove(type, subType, id); - } - } - } - - public void removeAll(String type, String subType) { - - Set idsBySubType = queryKeySet(type, subType); - for (String id : idsBySubType) { - remove(type, subType, id); - } - } - - public void remove(String type, String id) { - File removePath = this.pathBuilder.getRemovePath(type, id); - String failMsg = "Deletion of persistence units for {0} / {1} at {2} failed! Check file permissions!"; - remove(removePath, failMsg, type, id, removePath); - - // if no more objects with this type exist, then delete the path - failMsg = "Deletion of empty directory for {0} at {2} failed! Check file permissions!"; - File parentFile = removePath.getParentFile(); - deleteEmptyDirectory(parentFile, failMsg, type, parentFile); - } - - public void remove(String type, String subType, String id) { - File removePath = this.pathBuilder.getRemovePath(type, subType, id); - String failMsg = "Deletion of persistence units for {0} / {1} / {2} at {3} failed! Check file permissions!"; - remove(removePath, failMsg, type, subType, id, removePath); - - // if no more objects with this subType exist, then delete the path - failMsg = "Deletion of empty directory for {0} / {1} at {2} failed! Check file permissions!"; - File parentFile = removePath.getParentFile(); - deleteEmptyDirectory(parentFile, failMsg, type, subType, parentFile); - } - - public File getAddPath(String type, String id) { - return this.pathBuilder.getAddPath(type, id); - } - - public File getAddPath(String type, String subType, String id) { - return this.pathBuilder.getAddPath(type, subType, id); - } - - public File getReadPath(String type, String id) { - return this.pathBuilder.getReadPath(type, id); - } - - public File getReadPath(String type, String subType, String id) { - return this.pathBuilder.getReadPath(type, subType, id); - } - - public File getUpdatePath(String type, String id) { - return this.pathBuilder.getUpdatePath(type, id); - } - - public File getUpdatePath(String type, String subType, String id) { - return this.pathBuilder.getUpdatePath(type, subType, id); - } - - /** - * Returns the set of types - * - * @return - */ - public Set queryTypeSet() { - File queryPath = this.pathBuilder.getQueryPath(); - Set keySet = queryTypeSet(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " types"); - return keySet; - } - - /** - * Returns the set of sub types for the given type - * - * @return - */ - public Set queryTypeSet(String type) { - File queryPath = this.pathBuilder.getQueryPath(type); - Set keySet = queryTypeSet(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " subTypes of type " + type); - return keySet; - } - - /** - * Returns the object ids for the given type - * - * @param type - * - * @return - */ - public Set queryKeySet(String type) { - File queryPath = this.pathBuilder.getQueryPath(type); - Set keySet = queryKeySet(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " elements for " + type); - return keySet; - } - - /** - * Returns the object ids for the give type and sub type - * - * @param type - * @param subType - * - * @return - */ - public Set queryKeySet(String type, String subType) { - File queryPath = this.pathBuilder.getQueryPath(type, subType); - Set keySet = queryKeySet(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + keySet.size() + " elements for " + type); - return keySet; - } - - public long queryTypeSize() { - File queryPath = this.pathBuilder.getQueryPath(); - long numberOfFiles = queryTypeSize(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " types"); - return numberOfFiles; - } - - public long queryTypeSize(String type) { - File queryPath = this.pathBuilder.getQueryPath(type); - long numberOfFiles = queryTypeSize(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " elements for " + type); - return numberOfFiles; - } - - public long querySize(String type) { - File queryPath = this.pathBuilder.getQueryPath(type); - long numberOfFiles = querySize(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " elements for " + type); - return numberOfFiles; - } - - public long querySize(String type, String subType) { - File queryPath = this.pathBuilder.getQueryPath(type, subType); - long numberOfFiles = querySize(queryPath); - if (this.verbose) - XmlPersistenceFileDao.logger.info("Found " + numberOfFiles + " elements for " + type); - return numberOfFiles; - } - - /** - * Returns the types, i.e. directories in the given query path - * - * @param queryPath - * the path for which the types should be gathered - * - * @return a set of types in the given query path - */ - private Set queryTypeSet(File queryPath) { - Set keySet = new HashSet(); - - File[] subTypeFiles = queryPath.listFiles(); - for (File subTypeFile : subTypeFiles) { - if (subTypeFile.isFile()) { - String filename = subTypeFile.getName(); - String id = FilenameUtility.getId(filename); - keySet.add(id); - } - } - - return keySet; - } - - /** - * Returns the ids of all objects in the given query path, i.e. the id part of all the files in the given query path - * - * @param queryPath - * the path for which the ids should be gathered - * - * @return a set of ids for the objects in the given query path - */ - private Set queryKeySet(File queryPath) { - if (!queryPath.exists()) - return Collections.emptySet(); - if (!queryPath.isDirectory()) - throw new IllegalArgumentException("The path is not a directory, thus can not query key set for it: " - + queryPath.getAbsolutePath()); - - Set keySet = new HashSet(); - - File[] subTypeFiles = queryPath.listFiles(); - for (File subTypeFile : subTypeFiles) { - if (subTypeFile.isFile()) { - String filename = subTypeFile.getName(); - String id = FilenameUtility.getId(filename); - keySet.add(id); - } - } - - return keySet; - } - - /** - * Returns the number of all types, i.e. directories in the given query path - * - * @param queryPath - * the path in which to count the types - * - * @return the number of types in the given query path - */ - private long queryTypeSize(File queryPath) { - if (!queryPath.exists()) - return 0L; - if (!queryPath.isDirectory()) - throw new IllegalArgumentException("The path is not a directory, thus can not query type size for it: " - + queryPath.getAbsolutePath()); - - long numberOfFiles = 0l; - - File[] subTypeFiles = queryPath.listFiles(); - for (File subTypeFile : subTypeFiles) { - - if (subTypeFile.isDirectory()) - numberOfFiles++; - } - return numberOfFiles; - } - - /** - * Returns the number of all objects in the given query path - * - * @param queryPath - * the path in which to count the objects - * - * @return the number of objects in the given query path - */ - private long querySize(File queryPath) { - if (!queryPath.exists()) - return 0L; - if (!queryPath.isDirectory()) - throw new IllegalArgumentException("The path is not a directory, thus can not query key size for it: " - + queryPath.getAbsolutePath()); - - long numberOfFiles = 0l; - - File[] subTypeFiles = queryPath.listFiles(); - for (File subTypeFile : subTypeFiles) { - - if (subTypeFile.isFile()) - numberOfFiles++; - } - return numberOfFiles; - } - - private void remove(File removePath, String failMsg, Object... msgParts) { - if (!removePath.isFile()) - throw new IllegalArgumentException("The given path for deletion is not a file:" - + removePath.getAbsolutePath()); - if (!removePath.delete()) { - String msg = MessageFormat.format(failMsg, msgParts); - throw new XmlPersistenceException(msg); - } - } - - private void deleteEmptyDirectory(File directoryPath, String failMsg, Object... msgArgs) { - if (!directoryPath.isDirectory()) - throw new IllegalArgumentException("The given path for deletion when empty is not a directory:" - + directoryPath.getAbsolutePath()); - if (directoryPath.list().length == 0) { - if (this.verbose) { - String msg = "Deleting empty directory for type {0} at {1}"; - logger.info(MessageFormat.format(msg, directoryPath.getName(), directoryPath)); - } - if (!directoryPath.delete()) { - String msg = MessageFormat.format(failMsg, msgArgs); - throw new XmlPersistenceException(msg); - } - } - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java deleted file mode 100644 index 35f377dd9..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceFileIoHandler.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.impl; - -import java.io.File; - -import ch.eitchnet.xmlpers.api.DaoContext; - -/** - * @author Robert von Burg - * - */ -public interface XmlPersistenceFileIoHandler { - - public void read(DaoContext context, File file); - - public void write(DaoContext context, File file); -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java deleted file mode 100644 index 98790ba01..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceHandlerImpl.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.impl; - -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.PropertiesHelper; -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.api.XmlPersistenceHandler; -import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceHandlerImpl implements XmlPersistenceHandler { - - protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandlerImpl.class); - - protected boolean initialized; - protected boolean verbose; - protected XmlPersistenceDaoFactory daoFactory; - - public void initialize(Properties properties) { - if (this.initialized) - throw new IllegalStateException("Already initialized!"); - - // get properties - String context = XmlPersistenceHandlerImpl.class.getSimpleName(); - boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, - Boolean.FALSE).booleanValue(); - String daoFactoryClassName = PropertiesHelper.getProperty(properties, context, - XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, null); - - // load dao factory - XmlPersistenceDaoFactory daoFactory; - try { - @SuppressWarnings("unchecked") - Class xmlDaoFactoryClass = (Class) Class - .forName(daoFactoryClassName); - - daoFactory = xmlDaoFactoryClass.newInstance(); - - } catch (ClassNotFoundException e) { - throw new XmlPersistenceException("XmlDaoFactory class does not exist " + daoFactoryClassName, e); - } catch (Exception e) { - throw new XmlPersistenceException("Failed to load class " + daoFactoryClassName, e); - } - - // initialize the dao factory - XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(properties); - XmlPersistenceFileDao fileDao = new XmlPersistenceFileDao(pathBuilder, properties); - daoFactory.initialize(fileDao, properties); - - this.daoFactory = daoFactory; - this.verbose = verbose; - } - - @Override - public XmlPersistenceTransaction openTx() { - - TransactionDaoFactoryFacade daoFactoryFacade = new TransactionDaoFactoryFacade(this.daoFactory); - XmlPersistenceTransactionImpl tx = new XmlPersistenceTransactionImpl(daoFactoryFacade, this.verbose); - daoFactoryFacade.setTx(tx); - XmlPersistenceTransactionImpl.setTx(tx); - return tx; - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java deleted file mode 100644 index a70d09444..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistencePathBuilder.java +++ /dev/null @@ -1,396 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.impl; - -import java.io.File; -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.PropertiesHelper; -import ch.eitchnet.utils.helper.StringHelper; -import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; - -/** - * @author Robert von Burg - */ -public class XmlPersistencePathBuilder { - private static final String SLASH = "/"; //$NON-NLS-1$ - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistencePathBuilder.class); - - public static final String FILE_EXT = ".xml"; //$NON-NLS-1$ - public static final int EXT_LENGTH = XmlPersistencePathBuilder.FILE_EXT.length(); - - private final boolean verbose; - private final String basePath; - - public XmlPersistencePathBuilder(Properties properties) { - - // get properties - String context = XmlPersistencePathBuilder.class.getSimpleName(); - boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, - Boolean.FALSE).booleanValue(); - String basePath = PropertiesHelper - .getProperty(properties, context, XmlPersistenceConstants.PROP_BASEPATH, null); - - // validate base path exists and is writable - File basePathF = new File(basePath); - if (!basePathF.exists()) - throw new XmlPersistenceException(MessageFormat.format("The database store path does not exist at {0}", //$NON-NLS-1$ - basePathF.getAbsolutePath())); - if (!basePathF.canWrite()) - throw new XmlPersistenceException(MessageFormat.format("The database store path is not writeable at {0}", //$NON-NLS-1$ - basePathF.getAbsolutePath())); - - // we want a clean base path - String canonicalBasePath; - try { - canonicalBasePath = basePathF.getCanonicalPath(); - } catch (IOException e) { - throw new XmlPersistenceException( - MessageFormat.format("Failed to build canonical path from {0}", basePath), e); //$NON-NLS-1$ - } - - // this.basePathF = basePathF; - this.basePath = canonicalBasePath; - this.verbose = verbose; - - logger.info(MessageFormat.format("Using base path {0}", this.basePath)); //$NON-NLS-1$ - } - - String getFilename(String id) { - return id.concat(XmlPersistencePathBuilder.FILE_EXT); - } - - String getPathAsString(String type, String subType, String id) { - StringBuilder sb = new StringBuilder(this.basePath); - if (!StringHelper.isEmpty(type)) { - sb.append(SLASH); - sb.append(type); - } - if (!StringHelper.isEmpty(subType)) { - sb.append(SLASH); - sb.append(subType); - } - if (!StringHelper.isEmpty(id)) { - sb.append(SLASH); - sb.append(getFilename(id)); - } - - return sb.toString(); - } - - File getAddPath(String type, String id) { - assertType(type); - assertId(id); - - File path = new File(getPathAsString(type, null, id)); - - // assert path exists - String msg = "Persistence unit already exists for {0} / {1} at {2}"; //$NON-NLS-1$ - assertPathNotExists(path, msg, type, id, path.getAbsolutePath()); - - // check if parent path exists - msg = "Could not create parent path for {0} / {1} at {2}"; //$NON-NLS-1$ - createMissingParents(path, msg, type, id, path.getAbsolutePath()); - - return path; - } - - File getAddPath(String type, String subType, String id) { - assertType(type); - assertSubType(subType); - assertId(id); - - File path = new File(getPathAsString(type, subType, id)); - - // assert path exists - String msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - assertPathNotExists(path, msg, type, subType, id, path.getAbsolutePath()); - - // check if parent path exists - msg = "Could not create parent path for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - createMissingParents(path, msg, type, subType, id, path.getAbsolutePath()); - - return path; - } - - File getReadPath(String type, String id) { - assertType(type); - assertId(id); - File path = new File(getPathAsString(type, null, id)); - if (this.verbose) { - String msg = "Query path for {0} / {1} is {2}..."; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, type, id, path.getAbsolutePath())); - } - return path; - } - - File getReadPath(String type, String subType, String id) { - assertType(type); - assertSubType(subType); - assertId(id); - File path = new File(getPathAsString(type, subType, id)); - if (this.verbose) { - String msg = "Query path for {0} / {1} / {2} is {3}..."; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } - return path; - } - - File getUpdatePath(String type, String id) { - assertType(type); - assertId(id); - - File path = new File(getPathAsString(type, null, id)); - - if (!path.exists()) { - String msg = "Persistence unit does not exist for {0} / {1} at {2}"; //$NON-NLS-1$ - throw new XmlPersistenceException(MessageFormat.format(msg, type, id, path.getAbsolutePath())); - } - - return path; - } - - File getUpdatePath(String type, String subType, String id) { - assertType(type); - assertSubType(subType); - assertId(id); - - File path = new File(getPathAsString(type, subType, id)); - - if (!path.exists()) { - String msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } - - return path; - } - - File getRemovePath(String type, String id) { - assertType(type); - assertId(id); - - File path = new File(getPathAsString(type, null, id)); - if (!path.exists()) { - String msg = "No Persistence units exist for {0} / {1} at {2}"; //$NON-NLS-1$ - throw new XmlPersistenceException(MessageFormat.format(msg, type, id, path.getAbsolutePath())); - } - - if (this.verbose) { - String msg = "Remove path for {0} / {1} is {2}..."; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, type, id, path.getAbsolutePath())); - } - - return path; - } - - File getRemovePath(String type, String subType, String id) { - assertType(type); - assertSubType(subType); - assertId(id); - - File path = new File(getPathAsString(type, subType, id)); - if (!path.exists()) { - String msg = "Persistence unit for {0} / {1} / {2} does not exist at {3}"; //$NON-NLS-1$ - throw new XmlPersistenceException(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } - - if (this.verbose) { - String msg = "Remove path for {0} / {1} / {2} is {3}..."; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, type, subType, id, path.getAbsolutePath())); - } - - return path; - } - - File getQueryPath() { - return new File(getPathAsString(null, null, null)); - } - - File getQueryPath(String type) { - assertType(type); - File path = new File(getPathAsString(type, null, null)); - if (this.verbose) { - String msg = "Query path for {0} is {1}..."; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, type, path.getAbsolutePath())); - } - return path; - } - - File getQueryPath(String type, String subType) { - assertType(type); - assertSubType(subType); - File path = new File(getPathAsString(type, subType, null)); - if (this.verbose) { - String msg = "Query path for {0} / {1} is {2}..."; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, type, subType, path.getAbsolutePath())); - } - return path; - } - - private void assertId(String id) { - if (StringHelper.isEmpty(id)) - throw new XmlPersistenceException( - "The id can not be empty! An object must always be handled with at least the type and id!"); //$NON-NLS-1$ - } - - private void assertType(String type) { - if (StringHelper.isEmpty(type)) - throw new XmlPersistenceException( - "The type can not be empty! An object must always be handled with at least the type and id!"); //$NON-NLS-1$ - } - - private void assertSubType(String subType) { - if (StringHelper.isEmpty(subType)) - throw new XmlPersistenceException("The subType can not be empty!"); //$NON-NLS-1$ - } - - private void assertPathNotExists(File path, String msg, Object... args) { - if (path.exists()) { - throw new XmlPersistenceException(MessageFormat.format(msg, args)); - } - } - - private void createMissingParents(File path, String msg, Object... args) { - File parentFile = path.getParentFile(); - if (!parentFile.exists() && !parentFile.mkdirs()) { - throw new XmlPersistenceException(MessageFormat.format(msg, args)); - } - } - - private void logPath(String operation, File path, PersistenceContext context) { - if (this.verbose) { - String msg; - if (StringHelper.isEmpty(context.getSubType())) { - msg = "Path for operation {0} for {1} / {2} / is at {3}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, operation, context.getType(), context.getId(), path.getAbsolutePath()); - } else { - msg = "Path for operation {0} for {1} / {2} / {3} / is at {4}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, operation, context.getType(), context.getSubType(), context.getId(), - path.getAbsolutePath()); - } - } - } - - private void createMissingParents(File path, PersistenceContext context) { - File parentFile = path.getParentFile(); - if (!parentFile.exists() && !parentFile.mkdirs()) { - String msg; - if (StringHelper.isEmpty(context.getSubType())) { - msg = "Could not create parent path for {0} / {1} / at {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); - } else { - msg = "Could not create parent path for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), - path.getAbsolutePath()); - } - - throw new XmlPersistenceException(msg); - } - } - - private void assertPathIsFileAndWritable(File path, PersistenceContext context) { - if (!path.exists()) { - String msg; - if (StringHelper.isEmpty(context.getSubType())) { - msg = "Persistence unit does not exist for {0} / {1} at {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); - } else { - msg = "Persistence unit does not exist for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), - path.getAbsolutePath()); - } - - throw new XmlPersistenceException(msg); - } - - if (!path.isFile() || !path.canWrite()) { - String msg; - if (StringHelper.isEmpty(context.getSubType())) { - msg = "Persistence unit is not a file or is not readable for {0} / {1} at {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); - } else { - msg = "Persistence unit is not a file or is not readable for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), - path.getAbsolutePath()); - } - - throw new XmlPersistenceException(msg); - } - } - - private void assertPathNotExists(File path, PersistenceContext context) { - if (path.exists()) { - String msg; - if (StringHelper.isEmpty(context.getSubType())) { - msg = "Persistence unit already exists for {0} / {1} at {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getId(), path.getAbsolutePath()); - } else { - msg = "Persistence unit already exists for {0} / {1} / {2} at {3}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId(), - path.getAbsolutePath()); - } - - throw new XmlPersistenceException(msg); - } - } - - public File getCreatePath(PersistenceContext context) { - File path = getPath(context); - logPath("CREATE", path, context); //$NON-NLS-1$ - assertPathNotExists(path, context); - createMissingParents(path, context); - return path; - } - - public File getDeletePath(PersistenceContext context) { - File path = getPath(context); - logPath("DELETE", path, context); //$NON-NLS-1$ - assertPathIsFileAndWritable(path, context); - return path; - } - - public File getUpdatePath(PersistenceContext context) { - File path = getPath(context); - logPath("UPDATE", path, context); //$NON-NLS-1$ - assertPathIsFileAndWritable(path, context); - return path; - } - - public File getReadPath(PersistenceContext context) { - File path = getPath(context); - logPath("READ", path, context); //$NON-NLS-1$ - if (!path.exists()) - return null; - return path; - } - - public File getPath(PersistenceContext context) { - File path = new File(getPathAsString(context.getType(), context.getSubType(), context.getId())); - return path; - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java deleted file mode 100644 index 52c5ef0cf..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceSaxHandler.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.impl; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -import javanet.staxutils.IndentingXMLStreamWriter; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; -import javax.xml.stream.FactoryConfigurationError; -import javax.xml.stream.XMLOutputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import ch.eitchnet.utils.exceptions.XmlException; -import ch.eitchnet.xmlpers.api.XmlPersistenceContextData; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.api.XmlPersistenceFileHandler; -import ch.eitchnet.xmlpers.api.XmlPersistenceSaxContextData; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceSaxHandler implements XmlPersistenceFileHandler { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceSaxHandler.class); - - @Override - public void read(XmlPersistenceContextData contextData) { - - XmlPersistenceSaxContextData cd = (XmlPersistenceSaxContextData) contextData; - - // check assertions - if (cd.getFile() == null) - throw new IllegalStateException("No file has been set on the context data!"); - if (cd.getDefaultHandler() == null) - throw new IllegalStateException("No DefaultHandler has been set on the context data!"); - - File file; - try { - - SAXParserFactory spf = SAXParserFactory.newInstance(); - SAXParser sp = spf.newSAXParser(); - - file = cd.getFile(); - DefaultHandler defaultHandler = cd.getDefaultHandler(); - sp.parse(file, defaultHandler); - - } catch (ParserConfigurationException | SAXException | IOException e) { - - throw new XmlPersistenceException("Parsing failed due to internal error: " + e.getMessage(), e); - } - - logger.info("SAX parsed file " + file.getAbsolutePath()); - } - - @Override - public void write(XmlPersistenceContextData contextData) { - - XmlPersistenceSaxContextData cd = (XmlPersistenceSaxContextData) contextData; - - // check assertions - if (cd.getFile() == null) - throw new IllegalStateException("No file has been set on the context data!"); - if (cd.getXmlWriter() == null) - throw new IllegalStateException("No Xml writer has been set on the context data!"); - - XMLStreamWriter writer = null; - try { - XMLOutputFactory factory = XMLOutputFactory.newInstance(); - File file = cd.getFile(); - writer = factory.createXMLStreamWriter(new FileWriter(file)); - writer = new IndentingXMLStreamWriter(writer); - - // start document - writer.writeStartDocument("utf-8", "1.0"); - - // then delegate object writing to caller - XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); - cd.getXmlWriter().write(xmlWriter); - - // and now end - writer.writeEndDocument(); - writer.flush(); - - } catch (FactoryConfigurationError | XMLStreamException | IOException e) { - throw new XmlException("Writing to file failed due to internal error: " + e.getMessage(), e); - } finally { - if (writer != null) { - try { - writer.close(); - } catch (Exception e) { - logger.error("Failed to close stream: " + e.getMessage()); - } - } - } - - logger.info("Wrote SAX to " + cd.getFile().getAbsolutePath()); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java b/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java deleted file mode 100644 index 6b27aa0bd..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/impl/XmlPersistenceTransactionImpl.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.impl; - -import java.util.List; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.StringHelper; -import ch.eitchnet.utils.objectfilter.ObjectFilter; -import ch.eitchnet.xmlpers.api.XmlPersistenceDao; -import ch.eitchnet.xmlpers.api.XmlPersistenceDaoFactory; -import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; - -/** - * @author Robert von Burg - */ -public class XmlPersistenceTransactionImpl implements XmlPersistenceTransaction { - - private static final Logger logger = LoggerFactory.getLogger(XmlPersistenceTransactionImpl.class); - - private static final ThreadLocal TX_THREADLOCAL_THREAD_LOCAL; - static { - TX_THREADLOCAL_THREAD_LOCAL = new ThreadLocal<>(); - } - - private XmlPersistenceDaoFactory daoFactory; - private ObjectFilter objectFilter; - private boolean verbose; - private boolean cleared; - - /** - * @param verbose - */ - public XmlPersistenceTransactionImpl(XmlPersistenceDaoFactory daoFactory, boolean verbose) { - this.daoFactory = daoFactory; - this.verbose = verbose; - this.objectFilter = new ObjectFilter(); - } - - /* - * modifying methods - */ - - /** - * @param object - */ - @Override - public void add(T object) { - this.objectFilter.add(object); - } - - /** - * @param objects - */ - @Override - @SuppressWarnings("unchecked") - public void addAll(List objects) { - this.objectFilter.addAll((List) objects); - } - - /** - * @param object - */ - @Override - public void update(T object) { - this.objectFilter.update(object); - } - - /** - * @param objects - */ - @Override - @SuppressWarnings("unchecked") - public void updateAll(List objects) { - this.objectFilter.updateAll((List) objects); - } - - /** - * @param object - */ - @Override - public void remove(T object) { - this.objectFilter.remove(object); - } - - /** - * @param objects - */ - @Override - @SuppressWarnings("unchecked") - public void removeAll(List objects) { - this.objectFilter.removeAll((List) objects); - } - - /** - * @return the daoFactory - */ - @Override - public XmlPersistenceDaoFactory getDaoFactory() { - return this.daoFactory; - } - - /** - * - */ - @Override - public void commit() { - - try { - long start = System.nanoTime(); - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info("Committing TX..."); - Set keySet = this.objectFilter.keySet(); - if (keySet.isEmpty()) - return; - for (String key : keySet) { - - List removed = this.objectFilter.getRemoved(key); - if (removed.isEmpty()) { - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info("No objects removed in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info(removed.size() + " objects removed in this tx."); - - for (Object object : removed) { - XmlPersistenceDao dao = this.daoFactory.getDao(object); - dao.remove(object); - } - } - - List updated = this.objectFilter.getUpdated(key); - if (updated.isEmpty()) { - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info("No objects updated in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info(updated.size() + " objects updated in this tx."); - - for (Object object : updated) { - - XmlPersistenceDao dao = this.daoFactory.getDao(object); - dao.update(object); - } - } - - List added = this.objectFilter.getAdded(key); - if (added.isEmpty()) { - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info("No objects added in this tx."); - } else { - if (this.verbose) - XmlPersistenceTransactionImpl.logger.info(added.size() + " objects added in this tx."); - - for (Object object : added) { - - XmlPersistenceDao dao = this.daoFactory.getDao(object); - dao.add(object); - } - } - } - - long end = System.nanoTime(); - logger.info("Completed TX in " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ - - } finally { - // clean up - clear(); - } - } - - /** - * Clears the object filter and releases the transaction. After calling this method, this transaction instance can - * not be used anymore - */ - @Override - public void clear() { - if (!this.cleared) { - this.objectFilter.clearCache(); - this.objectFilter = null; - - this.daoFactory = null; - TX_THREADLOCAL_THREAD_LOCAL.set(null); - this.cleared = true; - } - } - - /** - * @return - */ - public boolean isCleared() { - return this.cleared; - } - - public static XmlPersistenceTransaction getTx() { - XmlPersistenceTransaction tx = TX_THREADLOCAL_THREAD_LOCAL.get(); - if (tx == null) - throw new IllegalStateException("No transaction is currently open!"); - return tx; - } - - public static void setTx(XmlPersistenceTransactionImpl tx) { - if (TX_THREADLOCAL_THREAD_LOCAL.get() != null) - throw new IllegalStateException("A transaction is already open!"); - TX_THREADLOCAL_THREAD_LOCAL.set(tx); - } -} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java new file mode 100644 index 000000000..d2c4b37a6 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java @@ -0,0 +1,79 @@ +package ch.eitchnet.xmlpers.objref; + +import java.io.File; +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceContextFactory; +import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; + +public class IdOfSubTypeRef extends ObjectRef { + + private final String type; + private final String subType; + private final String id; + + public IdOfSubTypeRef(String realmName, String type, String subType, String id) { + super(realmName, RefNameCreator.createIdOfSubTypeName(realmName, type, subType, id)); + this.type = type; + this.subType = subType; + this.id = id; + } + + public String getType() { + return this.type; + } + + public String getSubType() { + return this.subType; + } + + /** + * @return the id + */ + public String getId() { + return this.id; + } + + @Override + public boolean isRoot() { + return false; + } + + @Override + public boolean isLeaf() { + return true; + } + + @Override + public ObjectRef getParent(PersistenceTransaction tx) { + return tx.getRealm().getObjectRefCache().getSubTypeRef(this.type, this.subType); + } + + @Override + public ObjectRef getChildIdRef(PersistenceTransaction tx, String id) { + String msg = MessageFormat.format("Already a leaf: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public ObjectRef getChildTypeRef(PersistenceTransaction tx, String type) { + String msg = MessageFormat.format("Already a leaf: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public File getPath(PathBuilder pathBuilder) { + return pathBuilder.getIdOfSubTypePath(this.type, this.subType, this.id); + } + + @Override + public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { + PersistenceContextFactoryDelegator ctxFactoryDelegator = tx.getRealm().getCtxFactoryDelegator(); + PersistenceContextFactory persistenceContextFactory = ctxFactoryDelegator + . getCtxFactory(this.type); + return persistenceContextFactory.createCtx(this); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java new file mode 100644 index 000000000..40db517c3 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java @@ -0,0 +1,73 @@ +package ch.eitchnet.xmlpers.objref; + +import java.io.File; +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceContextFactory; +import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; + +public class IdOfTypeRef extends ObjectRef { + + private final String type; + private final String id; + + public IdOfTypeRef(String realmName, String type, String id) { + super(realmName, RefNameCreator.createIdOfTypeName(realmName, type, id)); + this.type = type; + this.id = id; + } + + public String getType() { + return this.type; + } + + /** + * @return the id + */ + public String getId() { + return this.id; + } + + @Override + public boolean isRoot() { + return false; + } + + @Override + public boolean isLeaf() { + return true; + } + + @Override + public ObjectRef getParent(PersistenceTransaction tx) { + return tx.getRealm().getObjectRefCache().getTypeRef(this.type); + } + + @Override + public ObjectRef getChildIdRef(PersistenceTransaction tx, String id) { + String msg = MessageFormat.format("Already a leaf: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public ObjectRef getChildTypeRef(PersistenceTransaction tx, String type) { + String msg = MessageFormat.format("Already a leaf: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public File getPath(PathBuilder pathBuilder) { + return pathBuilder.getIdOfTypePath(this.type, this.id); + } + + @Override + public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { + PersistenceContextFactoryDelegator ctxFactoryDelegator = tx.getRealm().getCtxFactoryDelegator(); + PersistenceContextFactory persistenceContextFactory = ctxFactoryDelegator + . getCtxFactory(this.type); + return persistenceContextFactory.createCtx(this); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java new file mode 100644 index 000000000..250f3e488 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -0,0 +1,29 @@ +package ch.eitchnet.xmlpers.objref; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +public class LockableObject { + + private final Lock lock; + + public LockableObject() { + this.lock = new ReentrantLock(); + } + + /** + * @return + * @see java.util.concurrent.locks.Lock#tryLock() + */ + public boolean tryLock() { + return this.lock.tryLock(); + } + + /** + * + * @see java.util.concurrent.locks.Lock#unlock() + */ + public void unlock() { + this.lock.unlock(); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java new file mode 100644 index 000000000..9feb80282 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java @@ -0,0 +1,40 @@ +package ch.eitchnet.xmlpers.objref; + +import java.io.File; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; + +public abstract class ObjectRef extends LockableObject { + + private String realmName; + private String name; + + protected ObjectRef(String realmName, String name) { + this.realmName = realmName; + this.name = name; + } + + public String getRealmName() { + return this.realmName; + } + + public String getName() { + return this.name; + } + + public abstract boolean isRoot(); + + public abstract boolean isLeaf(); + + public abstract ObjectRef getParent(PersistenceTransaction tx); + + public abstract ObjectRef getChildIdRef(PersistenceTransaction tx, String id); + + public abstract ObjectRef getChildTypeRef(PersistenceTransaction tx, String type); + + public abstract File getPath(PathBuilder pathBuilder); + + public abstract PersistenceContext createPersistenceContext(PersistenceTransaction tx); +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java new file mode 100644 index 000000000..7a2a64412 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java @@ -0,0 +1,80 @@ +package ch.eitchnet.xmlpers.objref; + +import java.util.HashMap; +import java.util.Map; + +import ch.eitchnet.utils.helper.StringHelper; + +public class ObjectReferenceCache { + + private final String realmName; + private final RootRef rootRef; + private final Map typeRefMap; + private final Map subTypeRefMap; + private final Map idOfTypeRefMap; + private final Map idOfSubTypeRefMap; + + public ObjectReferenceCache(String realmName) { + if (StringHelper.isEmpty(realmName)) + throw new IllegalArgumentException("Realm name may not be empty!"); //$NON-NLS-1$ + + this.realmName = realmName; + this.rootRef = new RootRef(this.realmName); + this.typeRefMap = new HashMap<>(); + this.subTypeRefMap = new HashMap<>(); + this.idOfTypeRefMap = new HashMap<>(); + this.idOfSubTypeRefMap = new HashMap<>(); + } + + public String getRealmName() { + return this.realmName; + } + + public synchronized RootRef getRootRef() { + return this.rootRef; + } + + public synchronized TypeRef getTypeRef(String type) { + String key = RefNameCreator.createTypeName(this.realmName, type); + TypeRef ref = this.typeRefMap.get(key); + if (ref == null) { + ref = new TypeRef(this.realmName, type); + this.typeRefMap.put(key, ref); + } + + return ref; + } + + public synchronized SubTypeRef getSubTypeRef(String type, String subType) { + String key = RefNameCreator.createSubTypeName(this.realmName, type, subType); + SubTypeRef ref = this.subTypeRefMap.get(key); + if (ref == null) { + ref = new SubTypeRef(this.realmName, type, subType); + this.subTypeRefMap.put(key, ref); + } + + return ref; + } + + public synchronized IdOfTypeRef getIdOfTypeRef(String type, String id) { + String key = RefNameCreator.createIdOfTypeName(this.realmName, type, id); + IdOfTypeRef idRef = this.idOfTypeRefMap.get(key); + if (idRef == null) { + idRef = new IdOfTypeRef(this.realmName, type, id); + this.idOfTypeRefMap.put(key, idRef); + } + + return idRef; + } + + public synchronized IdOfSubTypeRef getIdOfSubTypeRef(String type, String subType, String id) { + String key = RefNameCreator.createIdOfSubTypeName(this.realmName, type, subType, id); + IdOfSubTypeRef idRef = this.idOfSubTypeRefMap.get(key); + if (idRef == null) { + idRef = new IdOfSubTypeRef(this.realmName, type, subType, id); + this.idOfSubTypeRefMap.put(key, idRef); + } + + return idRef; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java b/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java new file mode 100644 index 000000000..d899a410f --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java @@ -0,0 +1,65 @@ +package ch.eitchnet.xmlpers.objref; + +import ch.eitchnet.utils.helper.StringHelper; + +public class RefNameCreator { + + protected static final String SLASH = "/"; //$NON-NLS-1$ + + public static String createRootName(String realmName) { + assertRealmName(realmName); + return SLASH + realmName + SLASH; + } + + public static String createTypeName(String realmName, String type) { + assertRealmName(realmName); + assertType(type); + return SLASH + realmName + SLASH + type + SLASH; + } + + public static String createIdOfTypeName(String realmName, String type, String id) { + assertRealmName(realmName); + assertType(type); + assertId(id); + return SLASH + realmName + SLASH + type + SLASH + id + SLASH; + } + + public static String createSubTypeName(String realmName, String type, String subType) { + assertRealmName(realmName); + assertType(type); + assertSubType(subType); + return SLASH + realmName + SLASH + type + SLASH + subType + SLASH; + } + + public static String createIdOfSubTypeName(String realmName, String type, String subType, String id) { + assertRealmName(realmName); + assertType(type); + assertSubType(subType); + assertId(id); + return SLASH + realmName + SLASH + type + SLASH + subType + SLASH + id + SLASH; + } + + private static void assertRealmName(String realmName) { + if (StringHelper.isEmpty(realmName)) { + throw new IllegalArgumentException("Realm name may not be empty!"); //$NON-NLS-1$ + } + } + + private static void assertType(String type) { + if (StringHelper.isEmpty(type)) { + throw new IllegalArgumentException("type may not be empty!"); //$NON-NLS-1$ + } + } + + private static void assertSubType(String subType) { + if (StringHelper.isEmpty(subType)) { + throw new IllegalArgumentException("subType may not be empty!"); //$NON-NLS-1$ + } + } + + private static void assertId(String id) { + if (StringHelper.isEmpty(id)) { + throw new IllegalArgumentException("id may not be empty!"); //$NON-NLS-1$ + } + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java new file mode 100644 index 000000000..204ceec8c --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java @@ -0,0 +1,53 @@ +package ch.eitchnet.xmlpers.objref; + +import java.io.File; +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; + +public class RootRef extends ObjectRef { + + public RootRef(String realmName) { + super(realmName, RefNameCreator.createRootName(realmName)); + } + + @Override + public boolean isRoot() { + return true; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public ObjectRef getParent(PersistenceTransaction tx) { + String msg = MessageFormat.format("RootRef has no parent: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public ObjectRef getChildIdRef(PersistenceTransaction tx, String id) { + String msg = MessageFormat.format("RootRef has no child id: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public ObjectRef getChildTypeRef(PersistenceTransaction tx, String type) { + return tx.getRealm().getObjectRefCache().getTypeRef(type); + } + + @Override + public File getPath(PathBuilder pathBuilder) { + return pathBuilder.getRootPath(); + } + + @Override + public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { + String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java new file mode 100644 index 000000000..29064486c --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java @@ -0,0 +1,65 @@ +package ch.eitchnet.xmlpers.objref; + +import java.io.File; +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; + +public class SubTypeRef extends ObjectRef { + + private final String type; + private final String subType; + + public SubTypeRef(String realmName, String type, String subType) { + super(realmName, RefNameCreator.createSubTypeName(realmName, type, subType)); + this.type = type; + this.subType = subType; + } + + public String getType() { + return this.type; + } + + public String getSubType() { + return this.subType; + } + + @Override + public boolean isRoot() { + return false; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public ObjectRef getParent(PersistenceTransaction tx) { + return tx.getRealm().getObjectRefCache().getTypeRef(this.type); + } + + @Override + public ObjectRef getChildIdRef(PersistenceTransaction tx, String id) { + return tx.getRealm().getObjectRefCache().getIdOfSubTypeRef(this.type, this.subType, id); + } + + @Override + public ObjectRef getChildTypeRef(PersistenceTransaction tx, String type) { + String msg = MessageFormat.format("A SubType has no child type: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + + @Override + public File getPath(PathBuilder pathBuilder) { + return pathBuilder.getSubTypePath(this.type, this.subType); + } + + @Override + public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { + String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java new file mode 100644 index 000000000..6a588527f --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java @@ -0,0 +1,58 @@ +package ch.eitchnet.xmlpers.objref; + +import java.io.File; +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; + +public class TypeRef extends ObjectRef { + + private final String type; + + public TypeRef(String realmName, String type) { + super(realmName, RefNameCreator.createTypeName(realmName, type)); + this.type = type; + } + + public String getType() { + return this.type; + } + + @Override + public boolean isRoot() { + return false; + } + + @Override + public boolean isLeaf() { + return false; + } + + @Override + public ObjectRef getParent(PersistenceTransaction tx) { + return tx.getRealm().getObjectRefCache().getRootRef(); + } + + @Override + public ObjectRef getChildIdRef(PersistenceTransaction tx, String id) { + return tx.getRealm().getObjectRefCache().getIdOfTypeRef(this.type, id); + } + + @Override + public ObjectRef getChildTypeRef(PersistenceTransaction tx, String type) { + return tx.getRealm().getObjectRefCache().getSubTypeRef(this.type, type); + } + + @Override + public File getPath(PathBuilder pathBuilder) { + return pathBuilder.getTypePath(this.type); + } + + @Override + public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { + String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java b/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java new file mode 100644 index 000000000..cdd7d24be --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java @@ -0,0 +1,47 @@ +package ch.eitchnet.xmlpers.util; + +import java.text.MessageFormat; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.objref.ObjectRef; + +public class AssertionUtil { + + public static void assertNotNull(Object object) { + if (object == null) + throw new RuntimeException("Object may not be null!"); //$NON-NLS-1$ + } + + public static void assertObjectRead(PersistenceContext context) { + if (context.getObject() == null) { + String msg = "Failed to read object with for {0}"; //$NON-NLS-1$ + ObjectRef objectRef = context.getObjectRef(); + msg = MessageFormat.format(msg, objectRef.getName()); + throw new RuntimeException(msg); + } + } + + public static void assertIsIdRef(ObjectRef objectRef) { + if (!objectRef.isLeaf()) { + String msg = "Expected IdRef not {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName()); + throw new IllegalArgumentException(msg); + } + } + + public static void assertIsNotIdRef(ObjectRef objectRef) { + if (objectRef.isLeaf()) { + String msg = "IdRef not expected {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName()); + throw new IllegalArgumentException(msg); + } + } + + public static void assertIsNotRootRef(ObjectRef objectRef) { + if (!objectRef.isRoot()) { + String msg = "RootRef not expected {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName()); + throw new IllegalArgumentException(msg); + } + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java b/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java similarity index 81% rename from src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java rename to src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java index 54959a342..f3e06cf60 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/DomUtil.java +++ b/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java @@ -19,12 +19,16 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.api; +package ch.eitchnet.xmlpers.util; + +import java.text.MessageFormat; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; + /** * @author Robert von Burg * @@ -37,7 +41,9 @@ public class DomUtil { DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); return docBuilder; } catch (ParserConfigurationException e) { - throw new XmlPersistenceException("No Xml Parser could be loaded: " + e.getMessage(), e); + String msg = "No Xml Parser could be loaded: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, e.getMessage()); + throw new XmlPersistenceException(msg, e); } } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java b/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java similarity index 50% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java rename to src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java index 30cd558fc..2632531c9 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FilenameUtility.java +++ b/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java @@ -1,21 +1,21 @@ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.util; import java.text.MessageFormat; import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; +import ch.eitchnet.xmlpers.impl.PathBuilder; public class FilenameUtility { public static String getId(String filename) { assertFilename(filename); - return filename.substring(0, filename.length() - XmlPersistencePathBuilder.EXT_LENGTH); + return filename.substring(0, filename.length() - PathBuilder.EXT_LENGTH); } public static void assertFilename(String filename) { - if (filename.charAt(filename.length() - XmlPersistencePathBuilder.EXT_LENGTH) != '.') { + if (filename.charAt(filename.length() - PathBuilder.EXT_LENGTH) != '.') { String msg = "The filename does not have a . (dot) at index {0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, (filename.length() - XmlPersistencePathBuilder.EXT_LENGTH)); + msg = MessageFormat.format(msg, (filename.length() - PathBuilder.EXT_LENGTH)); throw new XmlPersistenceException(msg); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java deleted file mode 100644 index a5224b98a..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/AbstractXmlPersistenceTest.java +++ /dev/null @@ -1,372 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test; - -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.BOOK_ID; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE_INEXISTANT; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertBook; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertBookUpdated; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createBook; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateBook; - -import java.io.File; -import java.util.List; -import java.util.Properties; -import java.util.Set; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.FileHelper; -import ch.eitchnet.xmlpers.api.XmlPersistenceDao; -import ch.eitchnet.xmlpers.api.XmlPersistenceHandler; -import ch.eitchnet.xmlpers.api.XmlPersistenceMetadataDao; -import ch.eitchnet.xmlpers.api.XmlPersistenceTransaction; -import ch.eitchnet.xmlpers.impl.XmlPersistenceHandlerImpl; -import ch.eitchnet.xmlpers.test.impl.Book; -import ch.eitchnet.xmlpers.test.impl.TestConstants; -import ch.eitchnet.xmlpers.test.model.ModelBuilder; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - */ -public abstract class AbstractXmlPersistenceTest { - - protected static final Logger logger = LoggerFactory.getLogger(AbstractXmlPersistenceTest.class.getName()); - protected static XmlPersistenceHandler persistenceHandler; - protected XmlPersistenceTransaction tx; - - /** - * @throws Exception - * if something goes wrong - */ - public static void init(Properties props) throws Exception { - - try { - - cleanUpDb(); - - String userDir = System.getProperty("user.dir"); - String basePath = userDir + "/target/testdb"; - File basePathF = new File(basePath); - if (!basePathF.exists() && !basePathF.mkdirs()) - Assert.fail("Could not create temporaray database store in " + basePathF.getAbsolutePath()); - - AbstractXmlPersistenceTest.persistenceHandler = new XmlPersistenceHandlerImpl(); - ((XmlPersistenceHandlerImpl) AbstractXmlPersistenceTest.persistenceHandler).initialize(props); - AbstractXmlPersistenceTest.logger.info("Initialized persistence handler."); - - } catch (Exception e) { - - AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); - throw new RuntimeException("Initialization failed: " + e.getLocalizedMessage(), e); - } - } - - @AfterClass - public static void cleanUpDb() { - String userDir = System.getProperty("user.dir"); - String basePath = userDir + "/target/testdb"; - File basePathF = new File(basePath); - if (basePathF.exists() && !FileHelper.deleteFile(basePathF, true)) - Assert.fail("Could not delete temporaray database store at " + basePathF.getAbsolutePath()); - } - - @After - public void tearDown() { - if (this.tx != null) - this.tx.clear(); - } - - /** - * Tests the following story: - *
    - *
  • create book
  • - *
  • read book
  • - *
  • update book
  • - *
  • remove book
  • - *
- */ - @Test - public void testBookPersistence() { - - // create - Book book = createBook(); - assertBook(book); - this.tx = persistenceHandler.openTx(); - this.tx.add(book); - this.tx.commit(); - - // read - this.tx = persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDao(book); - Book persistedBook = dao.queryById(String.valueOf(BOOK_ID)); - assertBook(persistedBook); - - // update - updateBook(persistedBook); - this.tx.update(persistedBook); - this.tx.commit(); - - // read - this.tx = persistenceHandler.openTx(); - dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_BOOK); - persistedBook = dao.queryById(String.valueOf(BOOK_ID)); - assertBookUpdated(persistedBook); - - // delete - this.tx.remove(book); - this.tx.commit(); - - // fail to read - this.tx = persistenceHandler.openTx(); - dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_BOOK); - persistedBook = dao.queryById(String.valueOf(BOOK_ID)); - Assert.assertNull(persistedBook); - } - - /** - * Tests the following story: - *
    - *
  • create resource
  • - *
  • read resource
  • - *
  • update resource
  • - *
  • remove resource
  • - *
- */ - @Test - public void testResourcePersistence() { - - persistResource(); - readResource(); - updateResource(); - removeResource(); - } - - private void persistResource() { - - try { - AbstractXmlPersistenceTest.logger.info("Trying to create..."); - - // new instance - Resource resource = createResource(); - assertResource(resource); - - // persist instance - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - this.tx.add(resource); - this.tx.commit(); - - AbstractXmlPersistenceTest.logger.info("Done creating."); - - } catch (Exception e) { - AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed by exception: " + e.getLocalizedMessage()); - } - } - - private void readResource() { - - try { - AbstractXmlPersistenceTest.logger.info("Trying to read..."); - - // query Resource - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - Resource resource = dao.queryById(RES_ID); - AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); - assertResource(resource); - this.tx.commit(); - - AbstractXmlPersistenceTest.logger.info("Done reading."); - - } catch (Exception e) { - AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed by exception: " + e.getLocalizedMessage()); - } - } - - private void updateResource() { - - try { - AbstractXmlPersistenceTest.logger.info("Trying to update an object..."); - - // query the instance - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - Resource resource = dao.queryById(RES_ID); - AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); - assertResource(resource); - - // modify the instance - ModelBuilder.updateResource(resource); - - // update the instance - this.tx.update(resource); - this.tx.commit(); - - // re-read and validate - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - resource = dao.queryById(RES_ID); - this.tx.commit(); - AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); - assertResourceUpdated(resource); - - AbstractXmlPersistenceTest.logger.info("Done updating."); - - } catch (Exception e) { - AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed by exception: " + e.getLocalizedMessage()); - } - } - - private void removeResource() { - - AbstractXmlPersistenceTest.logger.info("Trying to remove..."); - - // query the instance - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - Resource resource = dao.queryById(RES_ID); - AbstractXmlPersistenceTest.logger.info("Found Resource: " + resource); - assertResourceUpdated(resource); - - this.tx.remove(resource); - this.tx.commit(); - - AbstractXmlPersistenceTest.logger.info("Done removing."); - } - - @Test - public void testQueryFail() { - - AbstractXmlPersistenceTest.logger.info("Trying to query removed object..."); - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - Resource resource = dao.queryById(RES_ID); - this.tx.commit(); - Assert.assertNull("Expected resource not to be found!", resource); - } - - @Test - public void testReCreate() { - - try { - AbstractXmlPersistenceTest.logger.info("Trying to recreate..."); - - Resource resource = createResource(); - assertResource(resource); - - // persist instance - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - this.tx.add(resource); - this.tx.commit(); - - AbstractXmlPersistenceTest.logger.info("Done creating."); - - } catch (Exception e) { - AbstractXmlPersistenceTest.logger.error(e.getMessage(), e); - Assert.fail("Failed by exception: " + e.getLocalizedMessage()); - } - } - - @Test - @Ignore - public void testQueryFromTo() { - Assert.fail("Not yet implemented"); - } - - @Test - public void testQueryAll() { - - AbstractXmlPersistenceTest.logger.info("Trying to query all..."); - - // query all - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - List list = dao.queryAll(); - Assert.assertEquals("Expected only one object, found " + list, 1, list.size()); - - // and now something useless - dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE_INEXISTANT); - list = dao.queryAll(); - this.tx.commit(); - Assert.assertEquals("Expected no objects, found " + list, 0, list.size()); - - AbstractXmlPersistenceTest.logger.info("Done querying."); - } - - @Test - public void testKeySet() { - - // first prepare by creating a resource - createResource(); - - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceMetadataDao metadataDao = this.tx.getDaoFactory().getMetadataDao(); - - // query by type only, which should return nothing on this level - Set keySet = metadataDao.queryKeySet(TestConstants.TYPE_RES); - Assert.assertEquals("A resource can only be queried by type/subtype, but dao returned values!", 0, - keySet.size()); - - // now we shoud find our resource with the given type - keySet = metadataDao.queryKeySet(TestConstants.TYPE_RES, RES_TYPE); - Assert.assertEquals("Expected one key, found " + keySet, 1, keySet.size()); - - // and now something useless - keySet = metadataDao.queryKeySet(TestConstants.TYPE_RES, RES_TYPE_INEXISTANT); - Assert.assertEquals("Expected no keys, found " + keySet, 0, keySet.size()); - - this.tx.commit(); - } - - @Test - public void testRemoveAll() { - - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceDao dao = this.tx.getDaoFactory().getDaoBy(TestConstants.TYPE_RES, RES_TYPE); - List objects = dao.queryAll(); - this.tx.removeAll(objects); - this.tx.commit(); - } - - @Test - public void testSize() { - - this.tx = AbstractXmlPersistenceTest.persistenceHandler.openTx(); - XmlPersistenceMetadataDao metadataDao = this.tx.getDaoFactory().getMetadataDao(); - long size = metadataDao.querySize(TestConstants.TYPE_RES, RES_TYPE); - this.tx.commit(); - Assert.assertEquals("Expected size = 0, found: " + size, 0, size); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java new file mode 100644 index 000000000..adbb13677 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.util.Properties; + +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.FileDao; +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceContextFactory; +import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; +import ch.eitchnet.xmlpers.api.PersistenceManager; +import ch.eitchnet.xmlpers.api.PersistenceManagerLoader; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.impl.DefaultPersistenceRealm; +import ch.eitchnet.xmlpers.impl.DefaultPersistenceTransaction; +import ch.eitchnet.xmlpers.impl.PathBuilder; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; +import ch.eitchnet.xmlpers.test.impl.ResourceContextFactory; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +@SuppressWarnings("nls") +public class FileDaoTest { + + private static final String TEST_PATH = "target/dbTest"; + private static final boolean VERBOSE = true; + private static Properties properties; + private PersistenceManager persistenceManager; + private DefaultPersistenceRealm realm; + private PathBuilder pathBuilder; + + @BeforeClass + public static void beforeClass() { + File file = new File(TEST_PATH).getAbsoluteFile(); + if (file.exists() && file.isDirectory()) + if (!FileHelper.deleteFiles(file.listFiles(), true)) + throw new RuntimeException("Could not clean up path " + file.getAbsolutePath()); + + if (!file.exists() && !file.mkdir()) + throw new RuntimeException("Failed to create path " + file); + + File domFile = new File(file, "dom"); + if (!domFile.mkdir()) + throw new RuntimeException("Failed to create path " + domFile); + + File saxFile = new File(file, "sax"); + if (!saxFile.mkdir()) + throw new RuntimeException("Failed to create path " + saxFile); + + properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + } + + private void setup(String subPath) { + properties.setProperty(PersistenceConstants.PROP_BASEPATH, TEST_PATH + subPath); + this.persistenceManager = PersistenceManagerLoader.load(properties); + this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Resource.class, + TestConstants.TYPE_RES, new ResourceContextFactory()); + + ObjectReferenceCache objectRefCache = new ObjectReferenceCache(PersistenceManager.DEFAULT_REALM); + this.pathBuilder = new PathBuilder(PersistenceManager.DEFAULT_REALM, FileDaoTest.properties); + this.realm = new DefaultPersistenceRealm(PersistenceManager.DEFAULT_REALM, this.persistenceManager, + this.persistenceManager.getCtxFactory(), this.pathBuilder, objectRefCache); + } + + @Test + public void testCrudSax() { + setup("/sax/"); + try (PersistenceTransaction tx = new DefaultPersistenceTransaction(this.realm, VERBOSE)) { + FileDao fileDao = new FileDao(tx, this.pathBuilder, VERBOSE); + tx.setIoMode(IoMode.SAX); + testCrud(tx, this.realm.getCtxFactoryDelegator(), fileDao); + } + } + + @Test + public void testCrudDom() { + setup("/dom/"); + try (PersistenceTransaction tx = new DefaultPersistenceTransaction(this.realm, VERBOSE)) { + FileDao fileDao = new FileDao(tx, this.pathBuilder, VERBOSE); + tx.setIoMode(IoMode.DOM); + testCrud(tx, this.realm.getCtxFactoryDelegator(), fileDao); + } + } + + private void testCrud(PersistenceTransaction tx, PersistenceContextFactoryDelegator ctxFactoryDelegator, + FileDao fileDao) { + + Resource resource = createResource(); + assertResource(resource); + Class classType = resource.getClass(); + PersistenceContextFactory ctxFactory = ctxFactoryDelegator.getCtxFactory(classType); + ObjectReferenceCache objectRefCache = this.realm.getObjectRefCache(); + PersistenceContext context = ctxFactory.createCtx(objectRefCache, resource); + context.setObject(resource); + fileDao.performCreate(context); + + context.setObject(null); + fileDao.performRead(context); + assertResource(context.getObject()); + + updateResource(context.getObject()); + fileDao.performUpdate(context); + + context.setObject(null); + fileDao.performRead(context); + assertResourceUpdated(context.getObject()); + + fileDao.performDelete(context); + + context.setObject(null); + fileDao.performRead(context); + assertNull(context.getObject()); + + context.setObject(createResource()); + fileDao.performCreate(context); + } +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java new file mode 100644 index 000000000..36503a683 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.ObjectDao; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceManager; +import ch.eitchnet.xmlpers.api.PersistenceManagerLoader; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; +import ch.eitchnet.xmlpers.objref.SubTypeRef; +import ch.eitchnet.xmlpers.test.impl.ResourceContextFactory; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class ObjectDaoTest { + + private static final String BASEPATH = "target/dbTest/rewrite"; //$NON-NLS-1$ + + private PersistenceManager persistenceManager; + + private static Properties properties; + + @BeforeClass + public static void beforeClass() { + + File basePath = new File(BASEPATH); + if (basePath.exists()) { + if (!FileHelper.deleteFile(basePath, true)) { + throw new RuntimeException("Faile to delete base path " + BASEPATH); //$NON-NLS-1$ + } + } + + if (!basePath.mkdirs()) { + throw new RuntimeException("Failed to create base path " + BASEPATH); //$NON-NLS-1$ + } + + new File(BASEPATH + "/sax").mkdir(); //$NON-NLS-1$ + new File(BASEPATH + "/dom").mkdir(); //$NON-NLS-1$ + + properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + } + + private void setup(String subPath) { + properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASEPATH + subPath); + this.persistenceManager = PersistenceManagerLoader.load(properties); + + this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Resource.class, + TestConstants.TYPE_RES, new ResourceContextFactory()); + } + + @Test + public void testCrudSax() { + setup("/sax"); //$NON-NLS-1$ + testCrud(IoMode.SAX); + } + + @Test + public void testCrudDom() { + setup("/dom"); //$NON-NLS-1$ + testCrud(IoMode.DOM); + } + + private PersistenceTransaction freshTx(IoMode ioMode) { + PersistenceTransaction tx = this.persistenceManager.openTx(); + tx.setIoMode(ioMode); + return tx; + } + + private void testCrud(IoMode ioMode) { + + ObjectDao objectDao; + + // create new resource + Resource resource = createResource(); + try (PersistenceTransaction tx = freshTx(ioMode);) { + objectDao = tx.getObjectDao(); + objectDao.add(resource); + } + + // read resource + try (PersistenceTransaction tx = freshTx(ioMode);) { + IdOfSubTypeRef resRef = tx.getObjectRefCache().getIdOfSubTypeRef(TestConstants.TYPE_RES, RES_TYPE, RES_ID); + objectDao = tx.getObjectDao(); + resource = objectDao.queryById(resRef); + assertResource(resource); + + // modify resource + updateResource(resource); + objectDao.update(resource); + } + + // read modified resource + try (PersistenceTransaction tx = freshTx(ioMode);) { + IdOfSubTypeRef resRef = tx.getObjectRefCache().getIdOfSubTypeRef(TestConstants.TYPE_RES, RES_TYPE, RES_ID); + objectDao = tx.getObjectDao(); + resource = objectDao.queryById(resRef); + assertResourceUpdated(resource); + } + + // delete resource + try (PersistenceTransaction tx = freshTx(ioMode);) { + objectDao = tx.getObjectDao(); + objectDao.remove(resource); + } + + // fail to read + try (PersistenceTransaction tx = freshTx(ioMode);) { + IdOfSubTypeRef resRef = tx.getObjectRefCache().getIdOfSubTypeRef(TestConstants.TYPE_RES, RES_TYPE, RES_ID); + objectDao = tx.getObjectDao(); + resource = objectDao.queryById(resRef); + assertNull(resource); + + // and create again + resource = createResource(); + assertResource(resource); + objectDao.add(resource); + } + } + + @Test + public void testBulkSax() { + setup("/sax"); //$NON-NLS-1$ + IoMode ioMode = IoMode.SAX; + testBulk(ioMode); + } + + @Test + public void testBulkDom() { + setup("/dom"); //$NON-NLS-1$ + IoMode ioMode = IoMode.DOM; + testBulk(ioMode); + } + + private void testBulk(IoMode ioMode) { + + // context + String type = "testBulk" + ioMode.name(); //$NON-NLS-1$ + + // create a list of resources + List resources = new ArrayList<>(10); + for (int i = 0; i < 10; i++) { + String id = RES_ID + "_" + i; //$NON-NLS-1$ + String name = "Bulk Test Object. " + i; //$NON-NLS-1$ + + Resource resource = createResource(id, name, type); + resources.add(resource); + } + + ObjectDao objectDao; + + // save all + try (PersistenceTransaction tx = freshTx(ioMode);) { + objectDao = tx.getObjectDao(); + objectDao.addAll(resources); + resources.clear(); + } + + // query all + try (PersistenceTransaction tx = freshTx(ioMode);) { + SubTypeRef subTypeRef = tx.getObjectRefCache().getSubTypeRef(TestConstants.TYPE_RES, type); + objectDao = tx.getObjectDao(); + resources = objectDao.queryAll(subTypeRef); + assertEquals("Expected to find 10 entries!", 10, resources.size()); //$NON-NLS-1$ + + // delete them all + objectDao.removeAll(resources); + } + + // now query them again + try (PersistenceTransaction tx = freshTx(ioMode);) { + SubTypeRef subTypeRef = tx.getObjectRefCache().getSubTypeRef(TestConstants.TYPE_RES, type); + objectDao = tx.getObjectDao(); + resources = objectDao.queryAll(subTypeRef); + assertEquals("Expected to find 0 entries!", 0, resources.size()); //$NON-NLS-1$ + } + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java deleted file mode 100644 index 2143e62b4..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceDomTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test; - -import java.util.Properties; - -import org.junit.BeforeClass; - -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; - -/** - * @author Robert von Burg - */ -public class XmlPersistenceDomTest extends AbstractXmlPersistenceTest { - - /** - * @throws Exception - * if something goes wrong - */ - @BeforeClass - public static void init() throws Exception { - - Properties props = new Properties(); - props.setProperty(XmlPersistenceConstants.PROP_BASEPATH, "target/testdb"); - props.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); - props.setProperty(XmlPersistenceConstants.PROP_XML_IO_MOD, "dom"); - props.setProperty(XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, TestModelDaoFactory.class.getName()); - - init(props); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java deleted file mode 100644 index fba8c2eb2..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlPersistenceSaxTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test; - -import java.util.Properties; - -import org.junit.BeforeClass; - -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.test.impl.TestModelDaoFactory; - -/** - * @author Robert von Burg - */ -public class XmlPersistenceSaxTest extends AbstractXmlPersistenceTest { - - /** - * @throws Exception - * if something goes wrong - */ - @BeforeClass - public static void init() throws Exception { - - Properties props = new Properties(); - props.setProperty(XmlPersistenceConstants.PROP_BASEPATH, "target/testdb"); - props.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); - props.setProperty(XmlPersistenceConstants.PROP_XML_IO_MOD, "sax"); - props.setProperty(XmlPersistenceConstants.PROP_DAO_FACTORY_CLASS, TestModelDaoFactory.class.getName()); - - init(props); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index 2575aa3c1..decef2036 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -60,6 +60,7 @@ import ch.eitchnet.xmlpers.test.model.Resource; * @author Robert von Burg * */ +@SuppressWarnings("nls") public class XmlTestMain { private static final Logger logger = LoggerFactory.getLogger(XmlTestMain.class); @@ -119,10 +120,6 @@ public class XmlTestMain { return resources; } - /** - * @param res2 - * @param paramElements - */ private static void parseParameters(Resource res, NodeList paramElements) { for (int i = 0; i < paramElements.getLength(); i++) { Element paramElement = (Element) paramElements.item(i); @@ -263,43 +260,45 @@ public class XmlTestMain { XMLOutputFactory factory = XMLOutputFactory.newInstance(); File file = new File("target/res_sax.xml"); - XMLStreamWriter writer = factory.createXMLStreamWriter(new FileWriter(file)); + try (FileWriter fileWriter = new FileWriter(file)) { + XMLStreamWriter writer = factory.createXMLStreamWriter(fileWriter); - writer = new IndentingXMLStreamWriter(writer); + writer = new IndentingXMLStreamWriter(writer); - writer.writeStartDocument("utf-8", "1.0"); - writer.writeStartElement("model"); + writer.writeStartDocument("utf-8", "1.0"); + writer.writeStartElement("model"); - writer.writeStartElement("Resource"); - writer.writeAttribute("id", res.getId()); - writer.writeAttribute("name", res.getName()); - writer.writeAttribute("type", res.getType()); + writer.writeStartElement("Resource"); + writer.writeAttribute("id", res.getId()); + writer.writeAttribute("name", res.getName()); + writer.writeAttribute("type", res.getType()); - for (String paramId : res.getParameterKeySet()) { - Parameter param = res.getParameterBy(paramId); - writer.writeEmptyElement("Parameter"); - writer.writeAttribute("id", param.getId()); - writer.writeAttribute("name", param.getName()); - writer.writeAttribute("type", param.getType()); - writer.writeAttribute("value", param.getValue()); + for (String paramId : res.getParameterKeySet()) { + Parameter param = res.getParameterBy(paramId); + writer.writeEmptyElement("Parameter"); + writer.writeAttribute("id", param.getId()); + writer.writeAttribute("name", param.getName()); + writer.writeAttribute("type", param.getType()); + writer.writeAttribute("value", param.getValue()); + } + + //writer.writeEmptyElement("data"); + //writer.writeAttribute("name", "value"); + ////writer.writeEndElement(); + //writer.writeEmptyElement("stuff"); + //writer.writeAttribute("attr", "attrVal"); + + writer.writeEndElement(); + writer.writeEndDocument(); + + writer.flush(); + writer.close(); + logger.info("Wrote SAX to " + file.getAbsolutePath()); + + //Transformer transformer = TransformerFactory.newInstance().newTransformer(); + //Result outputTarget = new StaxR; + //Source xmlSource; + //transformer.transform(xmlSource, outputTarget); } - - //writer.writeEmptyElement("data"); - //writer.writeAttribute("name", "value"); - ////writer.writeEndElement(); - //writer.writeEmptyElement("stuff"); - //writer.writeAttribute("attr", "attrVal"); - - writer.writeEndElement(); - writer.writeEndDocument(); - - writer.flush(); - writer.close(); - logger.info("Wrote SAX to " + file.getAbsolutePath()); - - //Transformer transformer = TransformerFactory.newInstance().newTransformer(); - //Result outputTarget = new StaxR; - //Source xmlSource; - //transformer.transform(xmlSource, outputTarget); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java index 7df3b66b9..533715026 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java @@ -54,7 +54,7 @@ public class Book { */ public Book(Long id) { if (id == null) - throw new IllegalArgumentException("Id may not be null!"); + throw new IllegalArgumentException("Id may not be null!"); //$NON-NLS-1$ this.id = id; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java deleted file mode 100644 index a6b1f05bd..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDao.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl; - -import ch.eitchnet.xmlpers.api.AbstractXmlDao; - -/** - * @author Robert von Burg - * - */ -public abstract class BookDao extends AbstractXmlDao { - - @Override - protected String getType() { - return Book.class.getSimpleName(); - } - - @Override - protected String getId(Book object) { - return object.getId().toString(); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java index 36a0f098a..2f5702ce8 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java @@ -21,44 +21,15 @@ */ package ch.eitchnet.xmlpers.test.impl; -import java.io.File; - -import javax.xml.parsers.DocumentBuilder; - import org.w3c.dom.Document; import org.w3c.dom.Element; -import ch.eitchnet.xmlpers.api.DomUtil; -import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; - /** * @author Robert von Burg * */ -public class BookDomDao extends BookDao { - - @Override - protected Book read(File filePath) { - - XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); - cd.setFile(filePath); - getFileHandler().read(cd); - Document document = cd.getDocument(); - Book book = parseFromDom(document.getDocumentElement()); - return book; - } - - @Override - protected void write(Book book, File filePath) { - - XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); - cd.setFile(filePath); - DocumentBuilder documentBuilder = DomUtil.createDocumentBuilder(); - Document document = documentBuilder.getDOMImplementation().createDocument(null, null, null); - serializeToDom(book, document); - cd.setDocument(document); - getFileHandler().write(cd); - } +@SuppressWarnings("nls") +public class BookDomDao { public Element serializeToDom(Book book, Document document) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java similarity index 93% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java index 35c584904..d363769c4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java @@ -19,12 +19,11 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.test.impl; import org.w3c.dom.Document; import ch.eitchnet.xmlpers.api.DomParser; -import ch.eitchnet.xmlpers.test.impl.Book; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java similarity index 92% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java index 01ab00143..26442a97a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java @@ -19,12 +19,11 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.ParserFactory; import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.test.impl.Book; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java index ad151c351..889dc49f4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java @@ -21,64 +21,30 @@ */ package ch.eitchnet.xmlpers.test.impl; -import java.io.File; - import javax.xml.stream.XMLStreamException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; -import ch.eitchnet.xmlpers.api.XmlPersistenceSaxContextData; -import ch.eitchnet.xmlpers.api.XmlPersistenceSaxWriter; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; /** * @author Robert von Burg * */ -public class BookSaxDao extends BookDao { +@SuppressWarnings("nls") +public class BookSaxDao { - @Override - protected Book read(File filePath) { + private Book book; - XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); - cd.setFile(filePath); - BookDefaultHandler bookDefaultHandler = new BookDefaultHandler(); - cd.setDefaultHandler(bookDefaultHandler); - - getFileHandler().read(cd); - - return bookDefaultHandler.getBook(); - } - - @Override - protected void write(Book book, File filePath) { - - XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); - cd.setFile(filePath); - cd.setXmlWriter(new BookSaxWriter(book)); - - getFileHandler().write(cd); - } - - private class BookSaxWriter implements XmlPersistenceSaxWriter { - - private final Book book; - - public BookSaxWriter(Book book) { - this.book = book; - } - - @Override - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { - writer.writeEmptyElement("Book"); - writer.writeAttribute("id", Long.toString(this.book.getId())); - writer.writeAttribute("title", this.book.getTitle()); - writer.writeAttribute("author", this.book.getAuthor()); - writer.writeAttribute("press", this.book.getPress()); - writer.writeAttribute("price", Double.toString(this.book.getPrice())); - } + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + writer.writeEmptyElement("Book"); + writer.writeAttribute("id", Long.toString(this.book.getId())); + writer.writeAttribute("title", this.book.getTitle()); + writer.writeAttribute("author", this.book.getAuthor()); + writer.writeAttribute("press", this.book.getPress()); + writer.writeAttribute("price", Double.toString(this.book.getPrice())); } private class BookDefaultHandler extends DefaultHandler { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java similarity index 90% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java index ab4d012f5..b2cb36186 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/BookSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java @@ -19,15 +19,14 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.test.impl; import javax.xml.stream.XMLStreamException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; -import ch.eitchnet.xmlpers.test.impl.Book; +import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java new file mode 100644 index 000000000..977ca09f3 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java @@ -0,0 +1,25 @@ +package ch.eitchnet.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceContextFactory; +import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; +import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; +import ch.eitchnet.xmlpers.test.model.Resource; + +public class ResourceContextFactory implements PersistenceContextFactory { + + @Override + public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, Resource t) { + IdOfSubTypeRef objectRef = objectRefCache.getIdOfSubTypeRef(TestConstants.TYPE_RES, t.getType(), t.getId()); + return createCtx(objectRef); + } + + @Override + public PersistenceContext createCtx(ObjectRef objectRef) { + PersistenceContext ctx = new PersistenceContext<>(objectRef); + ctx.setParserFactory(new ResourceParserFactory()); + return ctx; + } + +} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java deleted file mode 100644 index ce61da6a3..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDao.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl; - -import ch.eitchnet.xmlpers.api.AbstractXmlDao; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -public abstract class ResourceDao extends AbstractXmlDao { - - private final String subType; - - public ResourceDao(String subType) { - this.subType = subType; - } - - @Override - public String getType() { - return Resource.class.getSimpleName(); - } - - @Override - public String getSubType() { - return this.subType; - } - - @Override - public String getId(Resource object) { - return object.getId(); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java index 0267b70eb..d555eb2dd 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java @@ -19,17 +19,11 @@ */ package ch.eitchnet.xmlpers.test.impl; -import java.io.File; - -import javax.xml.parsers.DocumentBuilder; - import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import ch.eitchnet.xmlpers.api.DomUtil; -import ch.eitchnet.xmlpers.api.XmlPersistenceDomContextData; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; @@ -37,37 +31,8 @@ import ch.eitchnet.xmlpers.test.model.Resource; * @author Robert von Burg * */ -public class ResourceDomDao extends ResourceDao { - - /** - * @param subType - */ - public ResourceDomDao(String subType) { - super(subType); - } - - @Override - protected Resource read(File filePath) { - - XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); - cd.setFile(filePath); - getFileHandler().read(cd); - Document document = cd.getDocument(); - Resource resource = parseFromDom(document.getDocumentElement()); - return resource; - } - - @Override - protected void write(Resource resource, File filePath) { - - XmlPersistenceDomContextData cd = new XmlPersistenceDomContextData(); - cd.setFile(filePath); - DocumentBuilder documentBuilder = DomUtil.createDocumentBuilder(); - Document document = documentBuilder.getDOMImplementation().createDocument(null, null, null); - serializeToDom(resource, document); - cd.setDocument(document); - getFileHandler().write(cd); - } +@SuppressWarnings("nls") +public class ResourceDomDao { public Element serializeToDom(Resource resource, Document document) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java similarity index 95% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java index 869664596..9b86472e8 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.test.impl; import javax.xml.parsers.DocumentBuilder; @@ -29,9 +29,9 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ch.eitchnet.xmlpers.api.DomParser; -import ch.eitchnet.xmlpers.api.DomUtil; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.util.DomUtil; public class ResourceDomParser implements DomParser { @@ -47,6 +47,7 @@ public class ResourceDomParser implements DomParser { this.resource = resource; } + @SuppressWarnings("nls") @Override public Document toDom() { @@ -74,6 +75,7 @@ public class ResourceDomParser implements DomParser { return document; } + @SuppressWarnings("nls") @Override public void fromDom(Document document) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java similarity index 96% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java index 0e062b1ae..002b83ad8 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.ParserFactory; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java index 5db3afe5b..742b9cc63 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java @@ -19,17 +19,13 @@ */ package ch.eitchnet.xmlpers.test.impl; -import java.io.File; - import javax.xml.stream.XMLStreamException; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; -import ch.eitchnet.xmlpers.api.XmlPersistenceSaxContextData; -import ch.eitchnet.xmlpers.api.XmlPersistenceSaxWriter; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; @@ -37,60 +33,23 @@ import ch.eitchnet.xmlpers.test.model.Resource; * @author Robert von Burg * */ -public class ResourceSaxDao extends ResourceDao { +@SuppressWarnings("nls") +public class ResourceSaxDao { - /** - * @param subType - */ - public ResourceSaxDao(String subType) { - super(subType); - } + private Resource resource; - @Override - protected Resource read(File filePath) { - - XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); - cd.setFile(filePath); - ResourceDefaultHandler bookDefaultHandler = new ResourceDefaultHandler(); - cd.setDefaultHandler(bookDefaultHandler); - - getFileHandler().read(cd); - - return bookDefaultHandler.getResource(); - } - - @Override - protected void write(Resource resource, File filePath) { - - XmlPersistenceSaxContextData cd = new XmlPersistenceSaxContextData(); - cd.setFile(filePath); - cd.setXmlWriter(new ResourceSaxWriter(resource)); - - getFileHandler().write(cd); - } - - private class ResourceSaxWriter implements XmlPersistenceSaxWriter { - - private final Resource resource; - - public ResourceSaxWriter(Resource resource) { - this.resource = resource; - } - - @Override - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { - writer.writeElement("Resource"); - writer.writeAttribute("id", this.resource.getId()); - writer.writeAttribute("name", this.resource.getName()); - writer.writeAttribute("type", this.resource.getType()); - for (String paramId : this.resource.getParameterKeySet()) { - Parameter param = this.resource.getParameterBy(paramId); - writer.writeElement("Parameter"); - writer.writeAttribute("id", param.getId()); - writer.writeAttribute("name", param.getName()); - writer.writeAttribute("type", param.getType()); - writer.writeAttribute("value", param.getValue()); - } + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + writer.writeElement("Resource"); + writer.writeAttribute("id", this.resource.getId()); + writer.writeAttribute("name", this.resource.getName()); + writer.writeAttribute("type", this.resource.getType()); + for (String paramId : this.resource.getParameterKeySet()) { + Parameter param = this.resource.getParameterBy(paramId); + writer.writeElement("Parameter"); + writer.writeAttribute("id", param.getId()); + writer.writeAttribute("name", param.getName()); + writer.writeAttribute("type", param.getType()); + writer.writeAttribute("value", param.getValue()); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java similarity index 94% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java index 1bc512827..f3cdf82d4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ResourceSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl.rewrite; +package ch.eitchnet.xmlpers.test.impl; import javax.xml.stream.XMLStreamException; @@ -28,7 +28,7 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.impl.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; import ch.eitchnet.xmlpers.test.model.Parameter; import ch.eitchnet.xmlpers.test.model.Resource; @@ -51,6 +51,7 @@ class ResourceSaxParser extends DefaultHandler implements SaxParser { return this; } + @SuppressWarnings("nls") @Override public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { @@ -68,6 +69,7 @@ class ResourceSaxParser extends DefaultHandler implements SaxParser { } } + @SuppressWarnings("nls") @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java deleted file mode 100644 index 43474a8d4..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestModelDaoFactory.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test.impl; - -import java.text.MessageFormat; - -import ch.eitchnet.xmlpers.api.AbstractDaoFactory; -import ch.eitchnet.xmlpers.api.XmlIoMode; -import ch.eitchnet.xmlpers.api.XmlPersistenceDao; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -public class TestModelDaoFactory extends AbstractDaoFactory { - - @Override - public XmlPersistenceDao getDao(T object) { - - XmlPersistenceDao dao; - if (object instanceof Resource) { - dao = getDaoBy(object.getClass().getSimpleName(), ((Resource) object).getType()); - } else if (object instanceof Book) { - dao = getDaoBy(Book.class.getSimpleName()); - } else { - String msg = "The object with class {0} is not handled!"; - msg = MessageFormat.format(msg, object.getClass()); - throw new IllegalArgumentException(msg); - } - - return dao; - } - - @SuppressWarnings("unchecked") - @Override - public XmlPersistenceDao getDaoBy(String type) { - - XmlPersistenceDao dao; - if (TestConstants.TYPE_BOOK.equals(type)) { - XmlIoMode ioMode = getXmlIoMode(); - if (ioMode == XmlIoMode.DOM) { - dao = (XmlPersistenceDao) new BookDomDao(); - } else if (ioMode == XmlIoMode.SAX) { - dao = (XmlPersistenceDao) new BookSaxDao(); - } else { - throw new IllegalArgumentException("The XmlIoMode " + ioMode + " is not yet supported!"); - } - } else { - String msg = "The object with type {0} is not handled!"; - msg = MessageFormat.format(msg, type); - throw new IllegalArgumentException(msg); - } - - return initializeDao(dao); - } - - @SuppressWarnings("unchecked") - @Override - public XmlPersistenceDao getDaoBy(String type, String subType) { - - XmlPersistenceDao dao; - if (TestConstants.TYPE_RES.equals(type)) { - XmlIoMode ioMode = getXmlIoMode(); - if (ioMode == XmlIoMode.DOM) { - dao = (XmlPersistenceDao) new ResourceDomDao(subType); - } else if (ioMode == XmlIoMode.SAX) { - dao = (XmlPersistenceDao) new ResourceSaxDao(subType); - } else { - throw new IllegalArgumentException("The XmlIoMode " + ioMode + " is not yet supported!"); - } - } else { - String msg = "The object with type {0} and subType {1} is not handled!"; - msg = MessageFormat.format(msg, type, subType); - throw new IllegalArgumentException(msg); - } - - return initializeDao(dao); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java deleted file mode 100644 index d83f5edeb..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/AssertionUtil.java +++ /dev/null @@ -1,33 +0,0 @@ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import java.text.MessageFormat; - -import ch.eitchnet.utils.helper.StringHelper; -import ch.eitchnet.xmlpers.api.PersistenceContext; - -public class AssertionUtil { - - public static void assertNotNull(Object object) { - if (object == null) - throw new RuntimeException("Object may not be null!"); //$NON-NLS-1$ - } - - public static void assertObjectRead(PersistenceContext context) { - if (context.getObject() == null) { - String msg = "Failed to read object with for {0} / {1} / {2}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, context.getType(), context.getSubType(), context.getId()); - throw new RuntimeException(msg); - } - } - - public static void assertHasType(PersistenceContext context) { - if (StringHelper.isEmpty(context.getType())) - throw new RuntimeException("Type is always needed on a persistence context!"); //$NON-NLS-1$ - } - - public static void assertHasId(PersistenceContext context) { - if (StringHelper.isEmpty(context.getId())) - throw new RuntimeException("Id is not set on persistence context!"); //$NON-NLS-1$ - } - -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java deleted file mode 100644 index 30ee6cac0..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/DefaultXmlPersistenceManager.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.utils.helper.PropertiesHelper; -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.impl.XmlPersistenceHandlerImpl; -import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; - -/** - * @author Robert von Burg - * - */ -public class DefaultXmlPersistenceManager implements XmlPersistenceManager { - - protected static final Logger logger = LoggerFactory.getLogger(XmlPersistenceHandlerImpl.class); - - protected boolean initialized; - protected boolean verbose; - - private XmlPersistencePathBuilder pathBuilder; - - public void initialize(Properties properties) { - if (this.initialized) - throw new IllegalStateException("Already initialized!"); //$NON-NLS-1$ - - // get properties - String context = XmlPersistenceHandlerImpl.class.getSimpleName(); - boolean verbose = PropertiesHelper.getPropertyBool(properties, context, XmlPersistenceConstants.PROP_VERBOSE, - Boolean.FALSE).booleanValue(); - - this.verbose = verbose; - - this.pathBuilder = new XmlPersistencePathBuilder(properties); - } - - @Override - public PersistenceTransaction openTx() { - - FileDao fileDao = new FileDao(this.pathBuilder, this.verbose); - PersistenceTransaction tx = new DefaultPersistenceTransaction(fileDao, this.verbose); - - return tx; - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java deleted file mode 100644 index 1e8898bfa..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDao.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import java.io.File; -import java.text.MessageFormat; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.XmlPersistenceException; -import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; - -public class FileDao { - - private static final Logger logger = LoggerFactory.getLogger(FileDao.class); - - private final boolean verbose; - private final XmlPersistencePathBuilder pathBuilder; - - public FileDao(XmlPersistencePathBuilder pathBuilder, boolean verbose) { - this.pathBuilder = pathBuilder; - this.verbose = verbose; - } - - File getPath(PersistenceContext context) { - return this.pathBuilder.getPath(context); - } - - void performCreate(PersistenceContext context) { - File path = this.pathBuilder.getCreatePath(context); - FileIo fileIo = new FileIo(path); - fileIo.write(context); - } - - void performRead(PersistenceContext context) { - File path = this.pathBuilder.getReadPath(context); - if (path == null) { - context.setObject(null); - } else { - FileIo fileIo = new FileIo(path); - fileIo.read(context); - } - } - - void performUpdate(PersistenceContext context) { - File path = this.pathBuilder.getUpdatePath(context); - FileIo fileIo = new FileIo(path); - fileIo.write(context); - } - - void performDelete(PersistenceContext context) { - File path = this.pathBuilder.getDeletePath(context); - if (!path.delete()) { - String msg = "Failed to delete file {0}"; //$NON-NLS-1$ - throw new RuntimeException(MessageFormat.format(msg, path.getAbsolutePath())); - } - - deleteEmptyDirectory(path.getParentFile(), context); - } - - private void deleteEmptyDirectory(File directoryPath, PersistenceContext ctx) { - if (!directoryPath.isDirectory()) { - String msg = "The given path for deletion when empty is not a directory:{0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, directoryPath.getAbsolutePath()); - throw new IllegalArgumentException(msg); - } - if (directoryPath.list().length == 0) { - if (!ctx.hasSubType()) { - if (!directoryPath.delete()) { - throw failedToDelete(directoryPath, ctx); - } - if (this.verbose) { - String msg = "Deleted empty directory for type {0} at {1}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, ctx.getType(), directoryPath)); - } - } else { - - if (!directoryPath.delete()) { - throw failedToDelete(directoryPath, ctx); - } - if (this.verbose) { - String msg = "Deleted empty directory for subType {0} of type {1} at {2}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, ctx.getSubType(), ctx.getType(), directoryPath)); - } - - File typePath = directoryPath.getParentFile(); - if (typePath.list().length == 0) { - - if (!typePath.delete()) { - throw failedToDelete(typePath, ctx); - } - if (this.verbose) { - String msg = "Deleted empty directory for type {0} at {1}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, ctx.getType(), typePath)); - } - } - } - } - } - - private XmlPersistenceException failedToDelete(File directoryPath, PersistenceContext ctx) { - String msg; - if (ctx.hasSubType()) { - msg = "Deletion of empty directory for {0} / {1} / {2} at {3} failed! Check file permissions!"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, ctx.getType(), ctx.getSubType(), ctx.getId(), - directoryPath.getAbsolutePath()); - } else { - - msg = "Deletion of empty directory for {0} / {1} / at {2} failed! Check file permissions!"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, ctx.getType(), ctx.getId(), directoryPath.getAbsolutePath()); - } - return new XmlPersistenceException(msg); - } -} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java deleted file mode 100644 index b5d980543..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/FileDaoTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; -import static org.junit.Assert.assertNull; - -import java.io.File; -import java.util.Properties; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import ch.eitchnet.utils.helper.FileHelper; -import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.XmlIoMode; -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.impl.XmlPersistencePathBuilder; -import ch.eitchnet.xmlpers.test.impl.TestConstants; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -@SuppressWarnings("nls") -public class FileDaoTest { - - private static final String TEST_PATH = "target/dbTest"; - private static final boolean VERBOSE = true; - - private FileDao fileDao; - private Properties properties; - - @BeforeClass - public static void beforeClass() { - File file = new File(TEST_PATH).getAbsoluteFile(); - if (file.exists() && file.isDirectory()) - if (!FileHelper.deleteFiles(file.listFiles(), true)) - throw new RuntimeException("Could not clean up path " + file.getAbsolutePath()); - - if (!file.exists() && !file.mkdir()) - throw new RuntimeException("Failed to create path " + file); - - File domFile = new File(file, "dom"); - if (!domFile.mkdir()) - throw new RuntimeException("Failed to create path " + domFile); - - File saxFile = new File(file, "sax"); - if (!saxFile.mkdir()) - throw new RuntimeException("Failed to create path " + saxFile); - } - - @Before - public void setUp() { - this.properties = new Properties(); - this.properties.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); - } - - @Test - public void testCrudSax() { - this.properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, TEST_PATH + "/sax/"); - XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(this.properties); - this.fileDao = new FileDao(pathBuilder, VERBOSE); - - Resource resource = createResource(); - assertResource(resource); - XmlIoMode ioMode = XmlIoMode.SAX; - PersistenceContext context = createPersistenceContext(resource, ioMode); - testCrud(context); - } - - @Test - public void testCrudDom() { - this.properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, TEST_PATH + "/dom/"); - XmlPersistencePathBuilder pathBuilder = new XmlPersistencePathBuilder(this.properties); - this.fileDao = new FileDao(pathBuilder, VERBOSE); - - Resource resource = createResource(); - assertResource(resource); - XmlIoMode ioMode = XmlIoMode.DOM; - PersistenceContext context = createPersistenceContext(resource, ioMode); - testCrud(context); - } - - private void testCrud(PersistenceContext context) { - - this.fileDao.performCreate(context); - - context.setObject(null); - this.fileDao.performRead(context); - assertResource(context.getObject()); - - updateResource(context.getObject()); - this.fileDao.performUpdate(context); - - context.setObject(null); - this.fileDao.performRead(context); - assertResourceUpdated(context.getObject()); - - this.fileDao.performDelete(context); - - context.setObject(null); - this.fileDao.performRead(context); - assertNull(context.getObject()); - - context.setObject(createResource()); - this.fileDao.performCreate(context); - } - - private PersistenceContext createPersistenceContext(Resource resource, XmlIoMode ioMode) { - PersistenceContext context = new PersistenceContext(); - context.setId(resource.getId()); - context.setType(TestConstants.TYPE_RES); - context.setSubType(resource.getType()); - context.setObject(resource); - context.setIoMode(ioMode); - context.setParserFactory(new ResourceParserFactory()); - - return context; - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java deleted file mode 100644 index d5e6e9c59..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/ObjectDaoTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; -import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.junit.After; -import org.junit.BeforeClass; -import org.junit.Test; - -import ch.eitchnet.utils.helper.FileHelper; -import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.XmlIoMode; -import ch.eitchnet.xmlpers.api.XmlPersistenceConstants; -import ch.eitchnet.xmlpers.test.impl.TestConstants; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -public class ObjectDaoTest { - - private static final String BASEPATH = "target/dbTest/rewrite"; //$NON-NLS-1$ - - private PersistenceContextFactory ctxFactory; - private XmlPersistenceManager persistenceManager; - private PersistenceTransaction tx; - - @BeforeClass - public static void beforeClass() { - - File basePath = new File(BASEPATH); - if (basePath.exists()) { - if (!FileHelper.deleteFile(basePath, true)) { - throw new RuntimeException("Faile to delete base path " + BASEPATH); //$NON-NLS-1$ - } - } - - if (!basePath.mkdirs()) { - throw new RuntimeException("Failed to create base path " + BASEPATH); //$NON-NLS-1$ - } - - new File(BASEPATH + "/sax").mkdir(); //$NON-NLS-1$ - new File(BASEPATH + "/dom").mkdir(); //$NON-NLS-1$ - } - - @After - public void tearDown() { - if (this.tx != null && this.tx.isOpen()) { - this.tx.rollback(); - } - } - - @Test - public void testCrudSax() { - this.ctxFactory = new TestPersistenceContextFactory(); - Properties properties = new Properties(); - properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ - this.persistenceManager = XmlPersistenceManagerLoader.load(properties); - - testCrud(XmlIoMode.SAX); - } - - @Test - public void testCrudDom() { - this.ctxFactory = new TestPersistenceContextFactory(); - Properties properties = new Properties(); - properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/dom"); //$NON-NLS-1$ - this.persistenceManager = XmlPersistenceManagerLoader.load(properties); - - testCrud(XmlIoMode.DOM); - } - - private PersistenceTransaction freshTx(XmlIoMode ioMode) { - if (this.tx != null && this.tx.isOpen()) - this.tx.rollback(); - - this.tx = this.persistenceManager.openTx(); - this.tx.setIoMode(ioMode); - - return this.tx; - } - - private void testCrud(XmlIoMode ioMode) { - - ObjectDao objectDao; - - // create new resource - Resource resource = createResource(); - objectDao = freshTx(ioMode).getObjectDao(); - objectDao.add(resource); - this.tx.commit(this.ctxFactory); - - // read resource - PersistenceContext ctx = this.ctxFactory.createCtx(this.tx, TestConstants.TYPE_RES, RES_TYPE, RES_ID); - objectDao = freshTx(ioMode).getObjectDao(); - resource = objectDao.queryById(ctx); - assertResource(resource); - - // modify resource - updateResource(resource); - objectDao = freshTx(ioMode).getObjectDao(); - objectDao.update(resource); - this.tx.commit(this.ctxFactory); - - // read modified resource - objectDao = freshTx(ioMode).getObjectDao(); - resource = objectDao.queryById(ctx); - assertResourceUpdated(resource); - this.tx.commit(this.ctxFactory); - - // delete resource - objectDao = freshTx(ioMode).getObjectDao(); - objectDao.remove(resource); - this.tx.commit(this.ctxFactory); - - // fail to read - objectDao = freshTx(ioMode).getObjectDao(); - resource = objectDao.queryById(ctx); - assertNull(resource); - - // and create again - resource = createResource(); - assertResource(resource); - objectDao = freshTx(ioMode).getObjectDao(); - objectDao.add(resource); - this.tx.commit(this.ctxFactory); - } - - @Test - public void testBulkSax() { - - this.ctxFactory = new TestPersistenceContextFactory(); - Properties properties = new Properties(); - properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ - properties.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ - this.persistenceManager = XmlPersistenceManagerLoader.load(properties); - - XmlIoMode ioMode = XmlIoMode.SAX; - testBulk(ioMode); - } - - @Test - public void testBulkDom() { - - this.ctxFactory = new TestPersistenceContextFactory(); - Properties properties = new Properties(); - properties.setProperty(XmlPersistenceConstants.PROP_BASEPATH, BASEPATH + "/sax"); //$NON-NLS-1$ - properties.setProperty(XmlPersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ - this.persistenceManager = XmlPersistenceManagerLoader.load(properties); - - XmlIoMode ioMode = XmlIoMode.DOM; - testBulk(ioMode); - } - - private void testBulk(XmlIoMode ioMode) { - - // context - String type = "testBulk" + ioMode.name(); //$NON-NLS-1$ - - // create a list of resources - List resources = new ArrayList<>(10); - for (int i = 0; i < 10; i++) { - String id = RES_ID + "_" + i; //$NON-NLS-1$ - String name = "Bulk Test Object. " + i; //$NON-NLS-1$ - - Resource resource = createResource(id, name, type); - resources.add(resource); - } - - ObjectDao objectDao; - - // save all - objectDao = freshTx(ioMode).getObjectDao(); - objectDao.addAll(resources); - resources.clear(); - this.tx.commit(this.ctxFactory); - - // query all - objectDao = freshTx(ioMode).getObjectDao(); - PersistenceContext ctx = this.ctxFactory.createCtx(this.tx, TestConstants.TYPE_RES, type); - resources = objectDao.queryAll(ctx); - assertEquals("Expected to find 10 entries!", 10, resources.size()); //$NON-NLS-1$ - - // delete them all - objectDao.removeAll(resources); - this.tx.commit(this.ctxFactory); - - // now query them again - objectDao = freshTx(ioMode).getObjectDao(); - ctx = this.ctxFactory.createCtx(this.tx, TestConstants.TYPE_RES, type); - resources = objectDao.queryAll(ctx); - assertEquals("Expected to find 0 entries!", 0, resources.size()); //$NON-NLS-1$ - this.tx.commit(this.ctxFactory); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java deleted file mode 100644 index 5f1a20900..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/PersistenceContextFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import ch.eitchnet.xmlpers.api.PersistenceContext; - -/** - * @author Robert von Burg - * - */ -public interface PersistenceContextFactory { - - public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType, String id); - - public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType); - - public PersistenceContext createCtx(PersistenceTransaction tx, String type); - - public PersistenceContext createCtx(PersistenceTransaction tx, T t); -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java deleted file mode 100644 index bdb02f306..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/rewrite/TestPersistenceContextFactory.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl.rewrite; - -import java.text.MessageFormat; - -import ch.eitchnet.xmlpers.api.ParserFactory; -import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.test.impl.Book; -import ch.eitchnet.xmlpers.test.impl.TestConstants; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -public class TestPersistenceContextFactory implements PersistenceContextFactory { - - @Override - public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType, String id) { - return buildPersistenceContext(tx, type, subType, id); - } - - @Override - public PersistenceContext createCtx(PersistenceTransaction tx, String type, String subType) { - return buildPersistenceContext(tx, type, subType, null); - } - - @Override - public PersistenceContext createCtx(PersistenceTransaction tx, String type) { - return buildPersistenceContext(tx, type, null, null); - } - - @Override - public PersistenceContext createCtx(PersistenceTransaction tx, T t) { - if (t == null) - throw new RuntimeException("T may not be null!"); //$NON-NLS-1$ - - PersistenceContext context; - - if (t instanceof Resource) { - Resource resource = (Resource) t; - context = buildPersistenceContext(tx, TestConstants.TYPE_RES, resource.getType(), resource.getId()); - } else if (t instanceof Book) { - context = buildPersistenceContext(tx, TestConstants.TYPE_BOOK, null, ((Book) t).getId().toString()); - } else { - String msg = "Handling of {0} is not implemented!"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, t.getClass().getName()); - throw new UnsupportedOperationException(msg); - } - - context.setObject(t); - return context; - } - - private PersistenceContext buildPersistenceContext(PersistenceTransaction tx, String type, String subType, - String id) { - - PersistenceContext context = new PersistenceContext<>(); - - context.setType(type); - context.setSubType(subType); - context.setId(id); - - context.setIoMode(tx.getIoMode()); - context.setParserFactory(this. getParserFactoryInstance(type)); - - return context; - } - - /** - * @param type - * @return - */ - @SuppressWarnings("unchecked") - private ParserFactory getParserFactoryInstance(String type) { - - ParserFactory parserFactory; - if (type.equals(TestConstants.TYPE_RES)) - parserFactory = (ParserFactory) new ResourceParserFactory(); - else if (type.equals(TestConstants.TYPE_BOOK)) - parserFactory = (ParserFactory) new BookParserFactory(); - else { - String msg = "No ParserFactory can be returned for type {0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, type); - throw new UnsupportedOperationException(msg); - } - - return parserFactory; - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index f44cc6590..08dc5d582 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -29,6 +29,7 @@ import ch.eitchnet.xmlpers.test.impl.Book; * @author Robert von Burg * */ +@SuppressWarnings("nls") public class ModelBuilder { public static final String RES_TYPE = "@subType"; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java index 99fa52403..1f6ee3b25 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java @@ -49,6 +49,7 @@ public class Parameter { this.value = value; } + @SuppressWarnings("nls") @Override public String toString() { StringBuilder builder = new StringBuilder(); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java index 283b758d5..b647b9d7c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java @@ -52,6 +52,7 @@ public class Resource { this.type = type; } + @SuppressWarnings("nls") @Override public String toString() { StringBuilder builder = new StringBuilder(); From 0d106c071495ea08ec8267e7efa24a6524b2796a Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 16 Oct 2013 07:59:03 +0200 Subject: [PATCH 33/87] [Minor] refactored tests to have a base class for cleaning up and preparing the db store --- .../xmlpers/test/AbstractPersistenceTest.java | 55 +++++++++++++++++++ .../ch/eitchnet/xmlpers/test/FileDaoTest.java | 45 ++++----------- .../eitchnet/xmlpers/test/ObjectDaoTest.java | 49 ++++------------- .../ch/eitchnet/xmlpers/test/RealmTest.java | 11 ++++ .../xmlpers/test/impl/BookContextFactory.java | 24 ++++++++ .../xmlpers/test/impl/BookDomDao.java | 2 + .../xmlpers/test/impl/BookDomParser.java | 1 + .../xmlpers/test/impl/BookParserFactory.java | 2 +- .../xmlpers/test/impl/BookSaxDao.java | 1 + .../xmlpers/test/impl/BookSaxParser.java | 1 + .../xmlpers/test/impl/TestConstants.java | 1 + .../xmlpers/test/{impl => model}/Book.java | 2 +- .../xmlpers/test/model/ModelBuilder.java | 2 - 13 files changed, 119 insertions(+), 77 deletions(-) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java rename src/test/java/ch/eitchnet/xmlpers/test/{impl => model}/Book.java (98%) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java new file mode 100644 index 000000000..5a47834d8 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java @@ -0,0 +1,55 @@ +package ch.eitchnet.xmlpers.test; + +import java.io.File; +import java.util.Properties; + +import ch.eitchnet.utils.helper.FileHelper; +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceManager; +import ch.eitchnet.xmlpers.api.PersistenceManagerLoader; +import ch.eitchnet.xmlpers.test.impl.BookContextFactory; +import ch.eitchnet.xmlpers.test.impl.ResourceContextFactory; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Book; +import ch.eitchnet.xmlpers.test.model.Resource; + +public abstract class AbstractPersistenceTest { + + protected PersistenceManager persistenceManager; + + @SuppressWarnings("nls") + protected static void cleanPath(String path) { + + File file = new File(path).getAbsoluteFile(); + File parent = file.getParentFile(); + if (!parent.getAbsolutePath().endsWith("/target/db")) + throw new RuntimeException("Bad parent! Must be /target/db/: " + parent); + if (!parent.exists() && !parent.mkdirs()) + throw new RuntimeException("Failed to create path " + parent); + + if (file.exists() && file.isDirectory()) + if (!FileHelper.deleteFiles(file.listFiles(), true)) + throw new RuntimeException("Could not clean up path " + file.getAbsolutePath()); + + if (!file.exists() && !file.mkdir()) + throw new RuntimeException("Failed to create path " + file); + + File domFile = new File(file, IoMode.DOM.name()); + if (!domFile.mkdir()) + throw new RuntimeException("Failed to create path " + domFile); + + File saxFile = new File(file, IoMode.SAX.name()); + if (!saxFile.mkdir()) + throw new RuntimeException("Failed to create path " + saxFile); + } + + protected void setup(Properties properties) { + properties.setProperty(PersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + this.persistenceManager = PersistenceManagerLoader.load(properties); + this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Resource.class, + TestConstants.TYPE_RES, new ResourceContextFactory()); + this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Book.class, TestConstants.TYPE_BOOK, + new BookContextFactory()); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java index adbb13677..2ba28bcd7 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java @@ -27,13 +27,11 @@ import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; import static org.junit.Assert.assertNull; -import java.io.File; import java.util.Properties; import org.junit.BeforeClass; import org.junit.Test; -import ch.eitchnet.utils.helper.FileHelper; import ch.eitchnet.xmlpers.api.FileDao; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.PersistenceConstants; @@ -41,14 +39,11 @@ import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.api.PersistenceContextFactory; import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; import ch.eitchnet.xmlpers.api.PersistenceManager; -import ch.eitchnet.xmlpers.api.PersistenceManagerLoader; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.impl.DefaultPersistenceRealm; import ch.eitchnet.xmlpers.impl.DefaultPersistenceTransaction; import ch.eitchnet.xmlpers.impl.PathBuilder; import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; -import ch.eitchnet.xmlpers.test.impl.ResourceContextFactory; -import ch.eitchnet.xmlpers.test.impl.TestConstants; import ch.eitchnet.xmlpers.test.model.Resource; /** @@ -56,52 +51,32 @@ import ch.eitchnet.xmlpers.test.model.Resource; * */ @SuppressWarnings("nls") -public class FileDaoTest { +public class FileDaoTest extends AbstractPersistenceTest { - private static final String TEST_PATH = "target/dbTest"; + private static final String TEST_PATH = "target/db/FileDaoTest/"; private static final boolean VERBOSE = true; - private static Properties properties; - private PersistenceManager persistenceManager; private DefaultPersistenceRealm realm; private PathBuilder pathBuilder; @BeforeClass public static void beforeClass() { - File file = new File(TEST_PATH).getAbsoluteFile(); - if (file.exists() && file.isDirectory()) - if (!FileHelper.deleteFiles(file.listFiles(), true)) - throw new RuntimeException("Could not clean up path " + file.getAbsolutePath()); - - if (!file.exists() && !file.mkdir()) - throw new RuntimeException("Failed to create path " + file); - - File domFile = new File(file, "dom"); - if (!domFile.mkdir()) - throw new RuntimeException("Failed to create path " + domFile); - - File saxFile = new File(file, "sax"); - if (!saxFile.mkdir()) - throw new RuntimeException("Failed to create path " + saxFile); - - properties = new Properties(); - properties.setProperty(PersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + cleanPath(TEST_PATH); } - private void setup(String subPath) { - properties.setProperty(PersistenceConstants.PROP_BASEPATH, TEST_PATH + subPath); - this.persistenceManager = PersistenceManagerLoader.load(properties); - this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Resource.class, - TestConstants.TYPE_RES, new ResourceContextFactory()); + private void setup(IoMode ioMode) { + Properties properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_BASEPATH, TEST_PATH + ioMode.name()); + setup(properties); ObjectReferenceCache objectRefCache = new ObjectReferenceCache(PersistenceManager.DEFAULT_REALM); - this.pathBuilder = new PathBuilder(PersistenceManager.DEFAULT_REALM, FileDaoTest.properties); + this.pathBuilder = new PathBuilder(PersistenceManager.DEFAULT_REALM, properties); this.realm = new DefaultPersistenceRealm(PersistenceManager.DEFAULT_REALM, this.persistenceManager, this.persistenceManager.getCtxFactory(), this.pathBuilder, objectRefCache); } @Test public void testCrudSax() { - setup("/sax/"); + setup(IoMode.SAX); try (PersistenceTransaction tx = new DefaultPersistenceTransaction(this.realm, VERBOSE)) { FileDao fileDao = new FileDao(tx, this.pathBuilder, VERBOSE); tx.setIoMode(IoMode.SAX); @@ -111,7 +86,7 @@ public class FileDaoTest { @Test public void testCrudDom() { - setup("/dom/"); + setup(IoMode.DOM); try (PersistenceTransaction tx = new DefaultPersistenceTransaction(this.realm, VERBOSE)) { FileDao fileDao = new FileDao(tx, this.pathBuilder, VERBOSE); tx.setIoMode(IoMode.DOM); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java index 36503a683..c13712a8a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java @@ -30,7 +30,6 @@ import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -38,16 +37,12 @@ import java.util.Properties; import org.junit.BeforeClass; import org.junit.Test; -import ch.eitchnet.utils.helper.FileHelper; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.ObjectDao; import ch.eitchnet.xmlpers.api.PersistenceConstants; -import ch.eitchnet.xmlpers.api.PersistenceManager; -import ch.eitchnet.xmlpers.api.PersistenceManagerLoader; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; import ch.eitchnet.xmlpers.objref.SubTypeRef; -import ch.eitchnet.xmlpers.test.impl.ResourceContextFactory; import ch.eitchnet.xmlpers.test.impl.TestConstants; import ch.eitchnet.xmlpers.test.model.Resource; @@ -55,52 +50,30 @@ import ch.eitchnet.xmlpers.test.model.Resource; * @author Robert von Burg * */ -public class ObjectDaoTest { +public class ObjectDaoTest extends AbstractPersistenceTest { - private static final String BASEPATH = "target/dbTest/rewrite"; //$NON-NLS-1$ - - private PersistenceManager persistenceManager; - - private static Properties properties; + private static final String BASEPATH = "target/db/ObjectDaoTest/"; //$NON-NLS-1$ @BeforeClass public static void beforeClass() { - - File basePath = new File(BASEPATH); - if (basePath.exists()) { - if (!FileHelper.deleteFile(basePath, true)) { - throw new RuntimeException("Faile to delete base path " + BASEPATH); //$NON-NLS-1$ - } - } - - if (!basePath.mkdirs()) { - throw new RuntimeException("Failed to create base path " + BASEPATH); //$NON-NLS-1$ - } - - new File(BASEPATH + "/sax").mkdir(); //$NON-NLS-1$ - new File(BASEPATH + "/dom").mkdir(); //$NON-NLS-1$ - - properties = new Properties(); - properties.setProperty(PersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ + cleanPath(BASEPATH); } - private void setup(String subPath) { - properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASEPATH + subPath); - this.persistenceManager = PersistenceManagerLoader.load(properties); - - this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Resource.class, - TestConstants.TYPE_RES, new ResourceContextFactory()); + private void setup(IoMode ioMode) { + Properties properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASEPATH + ioMode.name()); + setup(properties); } @Test public void testCrudSax() { - setup("/sax"); //$NON-NLS-1$ + setup(IoMode.SAX); testCrud(IoMode.SAX); } @Test public void testCrudDom() { - setup("/dom"); //$NON-NLS-1$ + setup(IoMode.DOM); testCrud(IoMode.DOM); } @@ -163,14 +136,14 @@ public class ObjectDaoTest { @Test public void testBulkSax() { - setup("/sax"); //$NON-NLS-1$ + setup(IoMode.SAX); IoMode ioMode = IoMode.SAX; testBulk(ioMode); } @Test public void testBulkDom() { - setup("/dom"); //$NON-NLS-1$ + setup(IoMode.DOM); IoMode ioMode = IoMode.DOM; testBulk(ioMode); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java new file mode 100644 index 000000000..755a09c56 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java @@ -0,0 +1,11 @@ +package ch.eitchnet.xmlpers.test; + +@SuppressWarnings("nls") +public class RealmTest extends AbstractPersistenceTest { + + protected static final String BASE_PATH = "target/db/RealmTest"; + + public static void beforeClass() { + cleanPath(BASE_PATH); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java new file mode 100644 index 000000000..c092b735d --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java @@ -0,0 +1,24 @@ +package ch.eitchnet.xmlpers.test.impl; + +import ch.eitchnet.xmlpers.api.PersistenceContext; +import ch.eitchnet.xmlpers.api.PersistenceContextFactory; +import ch.eitchnet.xmlpers.objref.IdOfTypeRef; +import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; +import ch.eitchnet.xmlpers.test.model.Book; + +public class BookContextFactory implements PersistenceContextFactory { + + @Override + public PersistenceContext createCtx(ObjectRef objectRef) { + PersistenceContext ctx = new PersistenceContext<>(objectRef); + ctx.setParserFactory(new BookParserFactory()); + return ctx; + } + + @Override + public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, Book t) { + IdOfTypeRef objectRef = objectRefCache.getIdOfTypeRef(TestConstants.TYPE_BOOK, t.getId().toString()); + return createCtx(objectRef); + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java index 2f5702ce8..d5756af25 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java @@ -24,6 +24,8 @@ package ch.eitchnet.xmlpers.test.impl; import org.w3c.dom.Document; import org.w3c.dom.Element; +import ch.eitchnet.xmlpers.test.model.Book; + /** * @author Robert von Burg * diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java index d363769c4..f98f57576 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java @@ -24,6 +24,7 @@ package ch.eitchnet.xmlpers.test.impl; import org.w3c.dom.Document; import ch.eitchnet.xmlpers.api.DomParser; +import ch.eitchnet.xmlpers.test.model.Book; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java index 26442a97a..8ca161052 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java @@ -24,6 +24,7 @@ package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.ParserFactory; import ch.eitchnet.xmlpers.api.SaxParser; +import ch.eitchnet.xmlpers.test.model.Book; /** * @author Robert von Burg @@ -40,5 +41,4 @@ public class BookParserFactory implements ParserFactory { public SaxParser getSaxParser() { return new BookSaxParser(); } - } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java index 889dc49f4..3ef898df8 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java @@ -28,6 +28,7 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.test.model.Book; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java index b2cb36186..950dc0896 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java @@ -27,6 +27,7 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; +import ch.eitchnet.xmlpers.test.model.Book; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java index 5ec56aaa5..1ac98b08c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java @@ -21,6 +21,7 @@ */ package ch.eitchnet.xmlpers.test.impl; +import ch.eitchnet.xmlpers.test.model.Book; import ch.eitchnet.xmlpers.test.model.Resource; /** diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java similarity index 98% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java rename to src/test/java/ch/eitchnet/xmlpers/test/model/Book.java index 533715026..21318298c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/Book.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java @@ -19,7 +19,7 @@ * along with XXX. If not, see * . */ -package ch.eitchnet.xmlpers.test.impl; +package ch.eitchnet.xmlpers.test.model; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index 08dc5d582..7aa72e6c0 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -23,8 +23,6 @@ package ch.eitchnet.xmlpers.test.model; import org.junit.Assert; -import ch.eitchnet.xmlpers.test.impl.Book; - /** * @author Robert von Burg * From a0d5904db9768f739d01513e8d778c9ecabbe860 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 16 Oct 2013 18:53:32 +0200 Subject: [PATCH 34/87] [Minor] added default IoMode, so that it must no be set on each TX --- .../xmlpers/impl/DefaultXmlPersistenceManager.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java index cab1ddf90..76c24c5bd 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java @@ -31,6 +31,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; import ch.eitchnet.xmlpers.api.PersistenceManager; @@ -48,6 +49,7 @@ public class DefaultXmlPersistenceManager implements PersistenceManager { protected boolean initialized; protected boolean verbose; + protected IoMode defaultIoMode; protected Properties properties; protected Map realmMap; private PersistenceContextFactoryDelegator ctxFactory; @@ -61,12 +63,16 @@ public class DefaultXmlPersistenceManager implements PersistenceManager { // get verbose flag boolean verbose = PropertiesHelper.getPropertyBool(properties, context, PersistenceConstants.PROP_VERBOSE, Boolean.FALSE).booleanValue(); + String ioModeS = PropertiesHelper.getProperty(properties, context, PersistenceConstants.PROP_XML_IO_MOD, + IoMode.DOM.name()); + IoMode ioMode = IoMode.valueOf(ioModeS); // validate base path validateBasePath(properties); this.properties = properties; this.verbose = verbose; + this.defaultIoMode = ioMode; this.realmMap = new HashMap<>(); this.ctxFactory = new PersistenceContextFactoryDelegator(); } @@ -103,12 +109,14 @@ public class DefaultXmlPersistenceManager implements PersistenceManager { PathBuilder pathBuilder = new PathBuilder(realmName, this.properties); ObjectReferenceCache objectRefCache = new ObjectReferenceCache(realmName); - persistenceRealm = new DefaultPersistenceRealm(realmName, this, this.ctxFactory, pathBuilder, objectRefCache); + persistenceRealm = new DefaultPersistenceRealm(realmName, this, this.ctxFactory, pathBuilder, + objectRefCache); this.realmMap.put(realmName, persistenceRealm); } PersistenceTransaction tx = new DefaultPersistenceTransaction(persistenceRealm, this.verbose); + tx.setIoMode(this.defaultIoMode); return tx; } } From bce78769c04d8547f239234d91fdb7792c090653 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 19 Oct 2013 17:43:36 +0200 Subject: [PATCH 35/87] [New] added testing of the *byId() methods Here i found a conceptual problem where the *byId() methods didn't properly resolve ObjectRefs and add them to the TX because, we added the ObjectRefs to the filter, which made the TX resolve PersistenContexts by the wrong type. Now we always add the same type of object to the ObjectFilter; the PersistentContext. This means that when we call ObjectDao.add(T), etc. we must already create such the context. This helps resolve another issue at the back of my mind: We don't want to partially commit a TX if such a basic information as the object's CTX is not available. --- .../java/ch/eitchnet/xmlpers/api/FileDao.java | 1 + .../ch/eitchnet/xmlpers/api/ObjectDao.java | 63 +++++++++---- .../PersistenceContextFactoryDelegator.java | 3 + .../xmlpers/api/PersistenceManagerLoader.java | 4 +- ...er.java => DefaultPersistenceManager.java} | 8 +- .../impl/DefaultPersistenceTransaction.java | 21 ++--- .../ch/eitchnet/xmlpers/objref/ObjectRef.java | 7 ++ .../xmlpers/objref/RefNameCreator.java | 6 +- .../ch/eitchnet/xmlpers/objref/RootRef.java | 6 ++ .../xmlpers/test/impl/BookDomDao.java | 62 ------------- .../xmlpers/test/impl/BookDomParser.java | 46 ++++++++-- .../xmlpers/test/impl/BookSaxDao.java | 84 ----------------- .../xmlpers/test/impl/BookSaxParser.java | 47 ++++++++-- .../xmlpers/test/impl/ResourceDomDao.java | 86 ----------------- .../xmlpers/test/impl/ResourceSaxDao.java | 92 ------------------- .../xmlpers/test/model/ModelBuilder.java | 5 + 16 files changed, 160 insertions(+), 381 deletions(-) rename src/main/java/ch/eitchnet/xmlpers/impl/{DefaultXmlPersistenceManager.java => DefaultPersistenceManager.java} (94%) delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java delete mode 100644 src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java index 2c0c3e0ca..c646d19f1 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java @@ -145,6 +145,7 @@ public class FileDao { if (this.verbose) { String msg = "Path for operation {0} for {1} is at {2}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, operation, objectRef.getName(), path.getAbsolutePath()); + logger.info(msg); } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index ef5ead550..872c37a3b 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -43,59 +43,80 @@ public class ObjectDao { private final ObjectFilter objectFilter; private final FileDao fileDao; private final PersistenceTransaction tx; + private PersistenceContextFactoryDelegator ctxFactoryDelegator; public ObjectDao(PersistenceTransaction tx, FileDao fileDao, ObjectFilter objectFilter) { this.tx = tx; this.fileDao = fileDao; this.objectFilter = objectFilter; + this.ctxFactoryDelegator = this.tx.getRealm().getCtxFactoryDelegator(); } public void add(T object) { assertNotClosed(); assertNotNull(object); - this.objectFilter.add(object); + PersistenceContext ctx = createCtx(object); + ctx.setObject(object); + this.objectFilter.add(object.getClass().getName(), ctx); } - @SuppressWarnings("unchecked") public void addAll(List objects) { assertNotClosed(); assertNotNull(objects); - if (!objects.isEmpty()) - this.objectFilter.addAll((List) objects); + if (!objects.isEmpty()) { + for (T object : objects) { + PersistenceContext ctx = createCtx(object); + ctx.setObject(object); + this.objectFilter.add(object.getClass().getName(), ctx); + } + } } public void update(T object) { assertNotClosed(); assertNotNull(object); - this.objectFilter.update(object); + PersistenceContext ctx = createCtx(object); + ctx.setObject(object); + this.objectFilter.update(object.getClass().getName(), ctx); } - @SuppressWarnings("unchecked") public void updateAll(List objects) { assertNotClosed(); assertNotNull(objects); - if (!objects.isEmpty()) - this.objectFilter.updateAll((List) objects); + if (!objects.isEmpty()) { + for (T object : objects) { + PersistenceContext ctx = createCtx(object); + ctx.setObject(object); + this.objectFilter.update(object.getClass().getName(), ctx); + } + } } public void remove(T object) { assertNotClosed(); assertNotNull(object); - this.objectFilter.remove(object); + PersistenceContext ctx = createCtx(object); + ctx.setObject(object); + this.objectFilter.remove(object.getClass().getName(), ctx); } - @SuppressWarnings("unchecked") public void removeAll(List objects) { assertNotClosed(); assertNotNull(objects); - if (!objects.isEmpty()) - this.objectFilter.removeAll((List) objects); + if (!objects.isEmpty()) { + for (T object : objects) { + PersistenceContext ctx = createCtx(object); + ctx.setObject(object); + this.objectFilter.remove(object.getClass().getName(), ctx); + } + } } public void removeById(ObjectRef objectRef) { assertNotClosed(); assertIsIdRef(objectRef); - this.objectFilter.remove(objectRef); + PersistenceContext ctx = createCtx(objectRef); + this.objectFilter.remove(objectRef.getType(), ctx); } public void removeAll(ObjectRef parentRef) { @@ -107,9 +128,8 @@ public class ObjectDao { for (String id : keySet) { ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); - PersistenceContext childCtx = childRef. createPersistenceContext(this.tx); - - this.objectFilter.remove(childCtx); + PersistenceContext ctx = createCtx(childRef); + this.objectFilter.remove(childRef.getType(), ctx); } } @@ -160,6 +180,17 @@ public class ObjectDao { return size; } + private PersistenceContext createCtx(T object) { + return this.ctxFactoryDelegator. getCtxFactory(object.getClass()).createCtx(this.tx.getObjectRefCache(), + object); + } + + private PersistenceContext createCtx(ObjectRef objectRef) { + String type = objectRef.getType(); + PersistenceContextFactory ctxFactory = this.ctxFactoryDelegator. getCtxFactory(type); + return ctxFactory.createCtx(objectRef); + } + private void assertNotClosed() { if (!this.tx.isOpen()) throw new IllegalStateException("Transaction has been closed and thus no operation can be performed!"); //$NON-NLS-1$ diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java index 92bff9299..bddabd33c 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java @@ -41,8 +41,11 @@ public class PersistenceContextFactoryDelegator { public void registerPersistenceContextFactory(Class classType, String type, PersistenceContextFactory ctxFactory) { + this.contextFactoryCacheByClass.put(classType, ctxFactory); this.contextFactoryCacheByType.put(type, ctxFactory); + if (!classType.getName().equals(type)) + this.contextFactoryCacheByType.put(classType.getName(), ctxFactory); } public PersistenceContextFactory getCtxFactory(Class classType) { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java index 64e6aef82..16fb0d667 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java @@ -23,7 +23,7 @@ package ch.eitchnet.xmlpers.api; import java.util.Properties; -import ch.eitchnet.xmlpers.impl.DefaultXmlPersistenceManager; +import ch.eitchnet.xmlpers.impl.DefaultPersistenceManager; /** * @author Robert von Burg @@ -33,7 +33,7 @@ public class PersistenceManagerLoader { public static PersistenceManager load(Properties properties) { - DefaultXmlPersistenceManager persistenceManager = new DefaultXmlPersistenceManager(); + DefaultPersistenceManager persistenceManager = new DefaultPersistenceManager(); persistenceManager.initialize(properties); return persistenceManager; } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java similarity index 94% rename from src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java rename to src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java index 76c24c5bd..950f1dfeb 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultXmlPersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java @@ -43,9 +43,9 @@ import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; * @author Robert von Burg * */ -public class DefaultXmlPersistenceManager implements PersistenceManager { +public class DefaultPersistenceManager implements PersistenceManager { - protected static final Logger logger = LoggerFactory.getLogger(DefaultXmlPersistenceManager.class); + protected static final Logger logger = LoggerFactory.getLogger(DefaultPersistenceManager.class); protected boolean initialized; protected boolean verbose; @@ -58,7 +58,7 @@ public class DefaultXmlPersistenceManager implements PersistenceManager { if (this.initialized) throw new IllegalStateException("Already initialized!"); //$NON-NLS-1$ - String context = DefaultXmlPersistenceManager.class.getSimpleName(); + String context = DefaultPersistenceManager.class.getSimpleName(); // get verbose flag boolean verbose = PropertiesHelper.getPropertyBool(properties, context, PersistenceConstants.PROP_VERBOSE, @@ -78,7 +78,7 @@ public class DefaultXmlPersistenceManager implements PersistenceManager { } private void validateBasePath(Properties properties) { - String context = DefaultXmlPersistenceManager.class.getSimpleName(); + String context = DefaultPersistenceManager.class.getSimpleName(); String basePath = PropertiesHelper.getProperty(properties, context, PersistenceConstants.PROP_BASEPATH, null); // validate base path exists and is writable diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index ed1b3fa62..d9c524212 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -35,7 +35,6 @@ import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.MetadataDao; import ch.eitchnet.xmlpers.api.ObjectDao; import ch.eitchnet.xmlpers.api.PersistenceContext; -import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; import ch.eitchnet.xmlpers.api.PersistenceRealm; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.api.TransactionCloseStrategy; @@ -143,10 +142,8 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info(removed.size() + " objects removed in this tx."); //$NON-NLS-1$ for (Object object : removed) { - PersistenceContextFactoryDelegator ctxFactoryDelegator = this.realm.getCtxFactoryDelegator(); - PersistenceContext ctx = ctxFactoryDelegator.getCtxFactory(object.getClass()) - .createCtx(this.realm.getObjectRefCache(), object); - ctx.setObject(object); + @SuppressWarnings("unchecked") + PersistenceContext ctx = (PersistenceContext) object; this.fileDao.performDelete(ctx); } } @@ -160,11 +157,8 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info(updated.size() + " objects updated in this tx."); //$NON-NLS-1$ for (Object object : updated) { - - PersistenceContextFactoryDelegator ctxFactoryDelegator = this.realm.getCtxFactoryDelegator(); - PersistenceContext ctx = ctxFactoryDelegator.getCtxFactory(object.getClass()) - .createCtx(this.realm.getObjectRefCache(), object); - ctx.setObject(object); + @SuppressWarnings("unchecked") + PersistenceContext ctx = (PersistenceContext) object; this.fileDao.performUpdate(ctx); } } @@ -178,11 +172,8 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { logger.info(added.size() + " objects added in this tx."); //$NON-NLS-1$ for (Object object : added) { - - PersistenceContextFactoryDelegator ctxFactoryDelegator = this.realm.getCtxFactoryDelegator(); - PersistenceContext ctx = ctxFactoryDelegator.getCtxFactory(object.getClass()) - .createCtx(this.realm.getObjectRefCache(), object); - ctx.setObject(object); + @SuppressWarnings("unchecked") + PersistenceContext ctx = (PersistenceContext) object; this.fileDao.performCreate(ctx); } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java index 9feb80282..a97b4f681 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java @@ -28,6 +28,8 @@ public abstract class ObjectRef extends LockableObject { public abstract boolean isLeaf(); + public abstract String getType(); + public abstract ObjectRef getParent(PersistenceTransaction tx); public abstract ObjectRef getChildIdRef(PersistenceTransaction tx, String id); @@ -37,4 +39,9 @@ public abstract class ObjectRef extends LockableObject { public abstract File getPath(PathBuilder pathBuilder); public abstract PersistenceContext createPersistenceContext(PersistenceTransaction tx); + + @Override + public String toString() { + return getName(); + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java b/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java index d899a410f..b47e87d2a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java @@ -6,6 +6,8 @@ public class RefNameCreator { protected static final String SLASH = "/"; //$NON-NLS-1$ + // FIXME validate each name part that it is a valid literal for file names... + public static String createRootName(String realmName) { assertRealmName(realmName); return SLASH + realmName + SLASH; @@ -21,7 +23,7 @@ public class RefNameCreator { assertRealmName(realmName); assertType(type); assertId(id); - return SLASH + realmName + SLASH + type + SLASH + id + SLASH; + return SLASH + realmName + SLASH + type + SLASH + id; } public static String createSubTypeName(String realmName, String type, String subType) { @@ -36,7 +38,7 @@ public class RefNameCreator { assertType(type); assertSubType(subType); assertId(id); - return SLASH + realmName + SLASH + type + SLASH + subType + SLASH + id + SLASH; + return SLASH + realmName + SLASH + type + SLASH + subType + SLASH + id; } private static void assertRealmName(String realmName) { diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java index 204ceec8c..cb621a3d9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java @@ -23,6 +23,12 @@ public class RootRef extends ObjectRef { return false; } + @Override + public String getType() { + String msg = MessageFormat.format("RootRef has no type: {0}", getName()); //$NON-NLS-1$ + throw new UnsupportedOperationException(msg); + } + @Override public ObjectRef getParent(PersistenceTransaction tx) { String msg = MessageFormat.format("RootRef has no parent: {0}", getName()); //$NON-NLS-1$ diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java deleted file mode 100644 index d5756af25..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomDao.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import ch.eitchnet.xmlpers.test.model.Book; - -/** - * @author Robert von Burg - * - */ -@SuppressWarnings("nls") -public class BookDomDao { - - public Element serializeToDom(Book book, Document document) { - - Element element = document.createElement("Book"); - document.appendChild(element); - element.setAttribute("id", Long.toString(book.getId())); - element.setAttribute("title", book.getTitle()); - element.setAttribute("author", book.getAuthor()); - element.setAttribute("press", book.getPress()); - element.setAttribute("price", Double.toString(book.getPrice())); - - return element; - } - - public Book parseFromDom(Element element) { - - String idS = element.getAttribute("id"); - long id = Long.parseLong(idS); - String title = element.getAttribute("title"); - String author = element.getAttribute("author"); - String press = element.getAttribute("press"); - String priceS = element.getAttribute("price"); - double price = Double.parseDouble(priceS); - - Book book = new Book(id, title, author, press, price); - return book; - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java index f98f57576..291a09250 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java @@ -21,39 +21,67 @@ */ package ch.eitchnet.xmlpers.test.impl; +import javax.xml.parsers.DocumentBuilder; + import org.w3c.dom.Document; +import org.w3c.dom.Element; import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.test.model.Book; +import ch.eitchnet.xmlpers.util.DomUtil; /** * @author Robert von Burg - * + * */ public class BookDomParser implements DomParser { + private Book book; + @Override public Book getObject() { - // TODO Auto-generated method stub - return null; + return this.book; } @Override public void setObject(Book object) { - // TODO Auto-generated method stub - + this.book = object; } + @SuppressWarnings("nls") @Override public Document toDom() { - // TODO Auto-generated method stub - return null; + + DocumentBuilder documentBuilder = DomUtil.createDocumentBuilder(); + Document document = documentBuilder.getDOMImplementation().createDocument(null, null, null); + + Element rootElement = document.createElement("Book"); + document.appendChild(rootElement); + rootElement.setAttribute("id", Long.toString(this.book.getId())); + rootElement.setAttribute("title", this.book.getTitle()); + rootElement.setAttribute("author", this.book.getAuthor()); + rootElement.setAttribute("press", this.book.getPress()); + rootElement.setAttribute("price", Double.toString(this.book.getPrice())); + + return document; + } + @SuppressWarnings("nls") @Override public void fromDom(Document document) { - // TODO Auto-generated method stub + Element rootElement = document.getDocumentElement(); + + String idS = rootElement.getAttribute("id"); + long id = Long.parseLong(idS); + String title = rootElement.getAttribute("title"); + String author = rootElement.getAttribute("author"); + String press = rootElement.getAttribute("press"); + String priceS = rootElement.getAttribute("price"); + double price = Double.parseDouble(priceS); + + Book book = new Book(id, title, author, press, price); + this.book = book; } - } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java deleted file mode 100644 index 3ef898df8..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxDao.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . - */ -package ch.eitchnet.xmlpers.test.impl; - -import javax.xml.stream.XMLStreamException; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; -import ch.eitchnet.xmlpers.test.model.Book; - -/** - * @author Robert von Burg - * - */ -@SuppressWarnings("nls") -public class BookSaxDao { - - private Book book; - - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { - writer.writeEmptyElement("Book"); - writer.writeAttribute("id", Long.toString(this.book.getId())); - writer.writeAttribute("title", this.book.getTitle()); - writer.writeAttribute("author", this.book.getAuthor()); - writer.writeAttribute("press", this.book.getPress()); - writer.writeAttribute("price", Double.toString(this.book.getPrice())); - } - - private class BookDefaultHandler extends DefaultHandler { - - private Book book; - - public BookDefaultHandler() { - // default constructor - } - - public Book getBook() { - return this.book; - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - - switch (qName) { - case "Book": - String idS = attributes.getValue("id"); - long id = Long.parseLong(idS); - Book book = new Book(id); - book.setTitle(attributes.getValue("title")); - book.setAuthor(attributes.getValue("author")); - book.setPress(attributes.getValue("press")); - String priceS = attributes.getValue("price"); - double price = Double.parseDouble(priceS); - book.setPrice(price); - this.book = book; - break; - default: - throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); - } - } - } -} \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java index 950dc0896..37acd83a0 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java @@ -23,6 +23,8 @@ package ch.eitchnet.xmlpers.test.impl; import javax.xml.stream.XMLStreamException; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; @@ -31,32 +33,59 @@ import ch.eitchnet.xmlpers.test.model.Book; /** * @author Robert von Burg - * + * */ -public class BookSaxParser implements SaxParser { +public class BookSaxParser extends DefaultHandler implements SaxParser { + + private Book book; @Override public Book getObject() { - // TODO Auto-generated method stub - return null; + return this.book; } @Override public void setObject(Book object) { - // TODO Auto-generated method stub + this.book = object; } @Override public DefaultHandler getDefaultHandler() { - // TODO Auto-generated method stub - return null; + return this; } + @SuppressWarnings("nls") @Override - public void write(XmlPersistenceStreamWriter xmlWriter) throws XMLStreamException { - // TODO Auto-generated method stub + public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + writer.writeEmptyElement("Book"); + writer.writeAttribute("id", Long.toString(this.book.getId())); + writer.writeAttribute("title", this.book.getTitle()); + writer.writeAttribute("author", this.book.getAuthor()); + writer.writeAttribute("press", this.book.getPress()); + writer.writeAttribute("price", Double.toString(this.book.getPrice())); } + @SuppressWarnings("nls") + @Override + public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { + + switch (qName) { + case "Book": + String idS = attributes.getValue("id"); + long id = Long.parseLong(idS); + Book book = new Book(id); + book.setTitle(attributes.getValue("title")); + book.setAuthor(attributes.getValue("author")); + book.setPress(attributes.getValue("press")); + String priceS = attributes.getValue("price"); + double price = Double.parseDouble(priceS); + book.setPrice(price); + this.book = book; + break; + default: + throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); + } + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java deleted file mode 100644 index d555eb2dd..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomDao.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test.impl; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import ch.eitchnet.xmlpers.test.model.Parameter; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -@SuppressWarnings("nls") -public class ResourceDomDao { - - public Element serializeToDom(Resource resource, Document document) { - - Element element = document.createElement("Resource"); - document.appendChild(element); - - element.setAttribute("id", resource.getId()); - element.setAttribute("name", resource.getName()); - element.setAttribute("type", resource.getType()); - - for (String paramId : resource.getParameterKeySet()) { - Parameter param = resource.getParameterBy(paramId); - Element paramElement = document.createElement("Parameter"); - element.appendChild(paramElement); - - paramElement.setAttribute("id", param.getId()); - paramElement.setAttribute("name", param.getName()); - paramElement.setAttribute("type", param.getType()); - paramElement.setAttribute("value", param.getValue()); - } - - return element; - } - - public Resource parseFromDom(Element element) { - - String id = element.getAttribute("id"); - String name = element.getAttribute("name"); - String type = element.getAttribute("type"); - - Resource resource = new Resource(id, name, type); - - NodeList children = element.getChildNodes(); - for (int i = 0; i < children.getLength(); i++) { - Node item = children.item(i); - if (!item.getNodeName().equals("Parameter")) - continue; - - Element paramElement = (Element) item; - String paramId = paramElement.getAttribute("id"); - String paramName = paramElement.getAttribute("name"); - String paramType = paramElement.getAttribute("type"); - String paramValue = paramElement.getAttribute("value"); - - Parameter param = new Parameter(paramId, paramName, paramType, paramValue); - resource.addParameter(param); - } - - return resource; - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java deleted file mode 100644 index 742b9cc63..000000000 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxDao.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2012 - * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . - * - */ -package ch.eitchnet.xmlpers.test.impl; - -import javax.xml.stream.XMLStreamException; - -import org.xml.sax.Attributes; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.DefaultHandler; - -import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; -import ch.eitchnet.xmlpers.test.model.Parameter; -import ch.eitchnet.xmlpers.test.model.Resource; - -/** - * @author Robert von Burg - * - */ -@SuppressWarnings("nls") -public class ResourceSaxDao { - - private Resource resource; - - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { - writer.writeElement("Resource"); - writer.writeAttribute("id", this.resource.getId()); - writer.writeAttribute("name", this.resource.getName()); - writer.writeAttribute("type", this.resource.getType()); - for (String paramId : this.resource.getParameterKeySet()) { - Parameter param = this.resource.getParameterBy(paramId); - writer.writeElement("Parameter"); - writer.writeAttribute("id", param.getId()); - writer.writeAttribute("name", param.getName()); - writer.writeAttribute("type", param.getType()); - writer.writeAttribute("value", param.getValue()); - } - } - - private class ResourceDefaultHandler extends DefaultHandler { - - private Resource resource; - - public ResourceDefaultHandler() { - // default constructor - } - - public Resource getResource() { - return this.resource; - } - - @Override - public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { - - switch (qName) { - case "Resource": - String id = attributes.getValue("id"); - String name = attributes.getValue("name"); - String type = attributes.getValue("type"); - Resource resource = new Resource(id, name, type); - this.resource = resource; - break; - case "Parameter": - id = attributes.getValue("id"); - name = attributes.getValue("name"); - type = attributes.getValue("type"); - String value = attributes.getValue("value"); - Parameter param = new Parameter(id, name, type, value); - this.resource.addParameter(param); - break; - default: - throw new IllegalArgumentException("The element '" + qName + "' is unhandled!"); - } - } - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index 7aa72e6c0..238f11464 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -70,6 +70,11 @@ public class ModelBuilder { return book; } + public static Book createBook(long id, String title, String author, String press, double price) { + Book book = new Book(id, title, author, press, price); + return book; + } + public static void updateBook(Book book) { book.setPress(BOOK_PRESS_2); } From 977d604a95bc1543d281d60b9b5d4f43c019afd1 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 19 Oct 2013 17:44:59 +0200 Subject: [PATCH 36/87] [New] created tests for object with no subType This is implemented with the Book model in the test folder --- .../xmlpers/test/ObjectDaoBookTest.java | 232 ++++++++++++++++++ ...aoTest.java => ObjectDaoResourceTest.java} | 55 ++++- 2 files changed, 277 insertions(+), 10 deletions(-) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java rename src/test/java/ch/eitchnet/xmlpers/test/{ObjectDaoTest.java => ObjectDaoResourceTest.java} (75%) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java new file mode 100644 index 000000000..591dcc542 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.BOOK_ID; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertBook; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertBookUpdated; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createBook; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateBook; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; + +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.ObjectDao; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.objref.IdOfTypeRef; +import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.objref.TypeRef; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.Book; + +/** + * @author Robert von Burg + * + */ +public class ObjectDaoBookTest extends AbstractPersistenceTest { + + private static final String BASEPATH = "target/db/ObjectDaoTest/"; //$NON-NLS-1$ + + @Before + public void before() { + cleanPath(BASEPATH); + } + + private void setup(IoMode ioMode) { + Properties properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASEPATH + ioMode.name()); + setup(properties); + } + + @Test + public void testCrudSax() { + setup(IoMode.SAX); + testCrud(IoMode.SAX); + } + + @Test + public void testCrudDom() { + setup(IoMode.DOM); + testCrud(IoMode.DOM); + } + + private PersistenceTransaction freshTx(IoMode ioMode) { + PersistenceTransaction tx = this.persistenceManager.openTx(); + tx.setIoMode(ioMode); + return tx; + } + + private void testCrud(IoMode ioMode) { + + ObjectDao objectDao; + + // create new book + Book book = createBook(); + try (PersistenceTransaction tx = freshTx(ioMode);) { + objectDao = tx.getObjectDao(); + objectDao.add(book); + } + + // read book + try (PersistenceTransaction tx = freshTx(ioMode);) { + IdOfTypeRef bookRef = tx.getObjectRefCache() + .getIdOfTypeRef(TestConstants.TYPE_BOOK, Long.toString(BOOK_ID)); + objectDao = tx.getObjectDao(); + book = objectDao.queryById(bookRef); + assertBook(book); + + // modify book + updateBook(book); + objectDao.update(book); + } + + // read modified book + try (PersistenceTransaction tx = freshTx(ioMode);) { + IdOfTypeRef bookRef = tx.getObjectRefCache() + .getIdOfTypeRef(TestConstants.TYPE_BOOK, Long.toString(BOOK_ID)); + objectDao = tx.getObjectDao(); + book = objectDao.queryById(bookRef); + assertBookUpdated(book); + } + + // delete book + try (PersistenceTransaction tx = freshTx(ioMode);) { + objectDao = tx.getObjectDao(); + objectDao.remove(book); + } + + // fail to read + try (PersistenceTransaction tx = freshTx(ioMode);) { + IdOfTypeRef bookRef = tx.getObjectRefCache() + .getIdOfTypeRef(TestConstants.TYPE_BOOK, Long.toString(BOOK_ID)); + objectDao = tx.getObjectDao(); + book = objectDao.queryById(bookRef); + assertNull(book); + + // and create again + book = createBook(); + assertBook(book); + objectDao.add(book); + } + } + + @Test + public void testBulkSax() { + setup(IoMode.SAX); + testBulk(IoMode.SAX); + } + + @Test + public void testBulkDom() { + setup(IoMode.DOM); + testBulk(IoMode.DOM); + } + + private void testBulk(IoMode ioMode) { + + // create a list of books + List books = new ArrayList<>(10); + for (int i = 0; i < 10; i++) { + long id = i; + String title = "Bulk Test Book. " + i; //$NON-NLS-1$ + String author = "Nick Hornby"; //$NON-NLS-1$ + String press = "Penguin Books"; //$NON-NLS-1$ + double price = 21.30; + + Book book = createBook(id, title, author, press, price); + books.add(book); + } + + // save all + try (PersistenceTransaction tx = freshTx(ioMode);) { + ObjectDao objectDao = tx.getObjectDao(); + objectDao.addAll(books); + books.clear(); + } + + // query all + try (PersistenceTransaction tx = freshTx(ioMode);) { + TypeRef typeRef = tx.getObjectRefCache().getTypeRef(TestConstants.TYPE_BOOK); + ObjectDao objectDao = tx.getObjectDao(); + books = objectDao.queryAll(typeRef); + assertEquals("Expected to find 10 entries!", 10, books.size()); //$NON-NLS-1$ + + // delete them all + objectDao.removeAll(books); + } + + // now query them again + try (PersistenceTransaction tx = freshTx(ioMode);) { + TypeRef typeRef = tx.getObjectRefCache().getTypeRef(TestConstants.TYPE_BOOK); + ObjectDao objectDao = tx.getObjectDao(); + books = objectDao.queryAll(typeRef); + assertEquals("Expected to find 0 entries!", 0, books.size()); //$NON-NLS-1$ + } + } + + @Test + public void shouldPersistById() { + setup(IoMode.SAX); + + String classType = TestConstants.TYPE_BOOK; + long id = System.currentTimeMillis(); + String title = "About a boy"; //$NON-NLS-1$ + String author = "Nick Hornby"; //$NON-NLS-1$ + String press = "Penguin Books"; //$NON-NLS-1$ + double price = 21.30; + + // create a book + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + Book book = createBook(id, title, author, press, price); + tx.getObjectDao().add(book); + } + + // read by id + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + ObjectRef objectRef = tx.getObjectRefCache().getIdOfTypeRef(classType, Long.toString(id)); + Book book = tx.getObjectDao().queryById(objectRef); + assertNotNull("Expected to read book by ID", book); //$NON-NLS-1$ + } + + // delete by id + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + ObjectRef objectRef = tx.getObjectRefCache().getIdOfTypeRef(classType, Long.toString(id)); + tx.getObjectDao().removeById(objectRef); + } + + // fail to read by id + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + ObjectRef objectRef = tx.getObjectRefCache().getIdOfTypeRef(classType, Long.toString(id)); + Book book = tx.getObjectDao().queryById(objectRef); + assertNull("Expected that book was deleted by ID, thus can not be read anymore", book); //$NON-NLS-1$ + } + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java similarity index 75% rename from src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java rename to src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java index c13712a8a..0932971f2 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java @@ -28,6 +28,7 @@ import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.ArrayList; @@ -42,15 +43,17 @@ import ch.eitchnet.xmlpers.api.ObjectDao; import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; +import ch.eitchnet.xmlpers.objref.ObjectRef; import ch.eitchnet.xmlpers.objref.SubTypeRef; import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.ModelBuilder; import ch.eitchnet.xmlpers.test.model.Resource; /** * @author Robert von Burg * */ -public class ObjectDaoTest extends AbstractPersistenceTest { +public class ObjectDaoResourceTest extends AbstractPersistenceTest { private static final String BASEPATH = "target/db/ObjectDaoTest/"; //$NON-NLS-1$ @@ -137,15 +140,13 @@ public class ObjectDaoTest extends AbstractPersistenceTest { @Test public void testBulkSax() { setup(IoMode.SAX); - IoMode ioMode = IoMode.SAX; - testBulk(ioMode); + testBulk(IoMode.SAX); } @Test public void testBulkDom() { setup(IoMode.DOM); - IoMode ioMode = IoMode.DOM; - testBulk(ioMode); + testBulk(IoMode.DOM); } private void testBulk(IoMode ioMode) { @@ -163,11 +164,9 @@ public class ObjectDaoTest extends AbstractPersistenceTest { resources.add(resource); } - ObjectDao objectDao; - // save all try (PersistenceTransaction tx = freshTx(ioMode);) { - objectDao = tx.getObjectDao(); + ObjectDao objectDao = tx.getObjectDao(); objectDao.addAll(resources); resources.clear(); } @@ -175,7 +174,7 @@ public class ObjectDaoTest extends AbstractPersistenceTest { // query all try (PersistenceTransaction tx = freshTx(ioMode);) { SubTypeRef subTypeRef = tx.getObjectRefCache().getSubTypeRef(TestConstants.TYPE_RES, type); - objectDao = tx.getObjectDao(); + ObjectDao objectDao = tx.getObjectDao(); resources = objectDao.queryAll(subTypeRef); assertEquals("Expected to find 10 entries!", 10, resources.size()); //$NON-NLS-1$ @@ -186,9 +185,45 @@ public class ObjectDaoTest extends AbstractPersistenceTest { // now query them again try (PersistenceTransaction tx = freshTx(ioMode);) { SubTypeRef subTypeRef = tx.getObjectRefCache().getSubTypeRef(TestConstants.TYPE_RES, type); - objectDao = tx.getObjectDao(); + ObjectDao objectDao = tx.getObjectDao(); resources = objectDao.queryAll(subTypeRef); assertEquals("Expected to find 0 entries!", 0, resources.size()); //$NON-NLS-1$ } } + + @Test + public void shouldPersistById() { + setup(IoMode.SAX); + + String classType = TestConstants.TYPE_RES; + String subType = ModelBuilder.RES_TYPE; + String id = "shouldPersistById"; //$NON-NLS-1$ + String name = "shouldPersistById "; //$NON-NLS-1$ + + // create a resource + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + Resource resource = createResource(id, name, subType); + tx.getObjectDao().add(resource); + } + + // read by id + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(classType, subType, id); + Resource resource = tx.getObjectDao().queryById(objectRef); + assertNotNull("Expected to read resource by ID", resource); //$NON-NLS-1$ + } + + // delete by id + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(classType, subType, id); + tx.getObjectDao().removeById(objectRef); + } + + // fail to read by id + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(classType, subType, id); + Resource resource = tx.getObjectDao().queryById(objectRef); + assertNull("Expected that resource was deleted by ID, thus can not be read anymore", resource); //$NON-NLS-1$ + } + } } From 30ddf3cfbf8ff1106d5268e553a93c280d3aee64 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 19 Oct 2013 17:45:33 +0200 Subject: [PATCH 37/87] [New] implemented a basic test for multiple realms (mandates) --- .../ch/eitchnet/xmlpers/test/RealmTest.java | 101 +++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java index 755a09c56..aeef634ca 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java @@ -1,11 +1,110 @@ package ch.eitchnet.xmlpers.test; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.test.impl.TestConstants; +import ch.eitchnet.xmlpers.test.model.ModelBuilder; +import ch.eitchnet.xmlpers.test.model.Resource; + @SuppressWarnings("nls") public class RealmTest extends AbstractPersistenceTest { - protected static final String BASE_PATH = "target/db/RealmTest"; + private static final String REALM_2 = "Realm2"; + private static final String REALM_1 = "Realm1"; + protected static final String BASE_PATH = "target/db/RealmTest/"; + @BeforeClass public static void beforeClass() { cleanPath(BASE_PATH); } + + @Before + public void before() { + Properties properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASE_PATH + IoMode.DOM.name()); + setup(properties); + } + + @Test + public void shouldNotFindObjInBothRealms() { + + // object details + String objType = TestConstants.TYPE_RES; + String type = ModelBuilder.RES_TYPE; + String name = ModelBuilder.RES_NAME; + String id = "shouldNotFindObjInBothRealms"; + + // create in first realm + try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { + Resource resource1 = ModelBuilder.createResource(id, name, type); + txRealm1.getObjectDao().add(resource1); + } + + // find in first realm + try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { + ObjectRef objectRef = txRealm1.getObjectRefCache().getIdOfSubTypeRef(objType, type, id); + Resource resource = txRealm1.getObjectDao().queryById(objectRef); + assertNotNull("Resource was not found in first realm!", resource); + } + + // fail to find in second realm + try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { + ObjectRef objectRef = txRealm2.getObjectRefCache().getIdOfSubTypeRef(objType, type, id); + Resource resource = txRealm2.getObjectDao().queryById(objectRef); + assertNull("Resource was not created in second realm, thus not expected to be found there!", resource); + } + } + + @Test + public void shouldNotDeleteObjInWrongRealm() { + + // object details + String objType = TestConstants.TYPE_RES; + String subType = ModelBuilder.RES_TYPE; + String name = ModelBuilder.RES_NAME; + String id = "shouldNotDeleteObjInWrongRealm"; + + // create in first realm + try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { + Resource resource1 = ModelBuilder.createResource(id, name, subType); + txRealm1.getObjectDao().add(resource1); + } + + // create in second realm + try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { + Resource resource1 = ModelBuilder.createResource(id, name, subType); + txRealm2.getObjectDao().add(resource1); + } + + // delete in second realm + try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { + ObjectRef objectRef = txRealm2.getObjectRefCache().getIdOfSubTypeRef(objType, subType, id); + txRealm2.getObjectDao().removeById(objectRef); + } + + // fail to find in second realm + try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { + ObjectRef objectRef = txRealm2.getObjectRefCache().getIdOfSubTypeRef(objType, subType, id); + Resource resource = txRealm2.getObjectDao().queryById(objectRef); + assertNull("Resource was not deleted from second realm, thus not expected to be found there!", resource); + } + + // find in first realm + try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { + ObjectRef objectRef = txRealm1.getObjectRefCache().getIdOfSubTypeRef(objType, subType, id); + Resource resource = txRealm1.getObjectDao().queryById(objectRef); + assertNotNull("Resource was not found in first realm!", resource); + } + } } From 5be5cd3fa098ff7a978e7553b949fe3f916af9e6 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 19 Oct 2013 17:49:27 +0200 Subject: [PATCH 38/87] [Minor] fixed compiler warnings --- src/main/java/ch/eitchnet/xmlpers/api/IoMode.java | 8 ++++++++ .../ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java | 3 +++ .../java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java | 1 + src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java | 1 + src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java | 1 + src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java | 1 + src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java | 7 +++---- 7 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java b/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java index 7464bff31..2b80e64b0 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java @@ -50,10 +50,18 @@ public enum IoMode { } }; + /** + * @param ctx + * @param fileIo + */ public void write(PersistenceContext ctx, FileIo fileIo) { throw new UnsupportedOperationException("Override me!"); //$NON-NLS-1$ } + /** + * @param ctx + * @param fileIo + */ public void read(PersistenceContext ctx, FileIo fileIo) { throw new UnsupportedOperationException("Override me!"); //$NON-NLS-1$ } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java index a535fe5c6..7f93e02a9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java @@ -15,6 +15,9 @@ public enum TransactionCloseStrategy { } }; + /** + * @param tx + */ public void close(PersistenceTransaction tx) { throw new UnsupportedOperationException("Override in enum!"); //$NON-NLS-1$ } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java index d2c4b37a6..8312a93da 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java @@ -22,6 +22,7 @@ public class IdOfSubTypeRef extends ObjectRef { this.id = id; } + @Override public String getType() { return this.type; } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java index 40db517c3..a6f09dbef 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java @@ -20,6 +20,7 @@ public class IdOfTypeRef extends ObjectRef { this.id = id; } + @Override public String getType() { return this.type; } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java index 29064486c..560526b3d 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java @@ -18,6 +18,7 @@ public class SubTypeRef extends ObjectRef { this.subType = subType; } + @Override public String getType() { return this.type; } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java index 6a588527f..44e2770a1 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java @@ -16,6 +16,7 @@ public class TypeRef extends ObjectRef { this.type = type; } + @Override public String getType() { return this.type; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java index 2ba28bcd7..150b18f36 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java @@ -80,7 +80,7 @@ public class FileDaoTest extends AbstractPersistenceTest { try (PersistenceTransaction tx = new DefaultPersistenceTransaction(this.realm, VERBOSE)) { FileDao fileDao = new FileDao(tx, this.pathBuilder, VERBOSE); tx.setIoMode(IoMode.SAX); - testCrud(tx, this.realm.getCtxFactoryDelegator(), fileDao); + testCrud(this.realm.getCtxFactoryDelegator(), fileDao); } } @@ -90,12 +90,11 @@ public class FileDaoTest extends AbstractPersistenceTest { try (PersistenceTransaction tx = new DefaultPersistenceTransaction(this.realm, VERBOSE)) { FileDao fileDao = new FileDao(tx, this.pathBuilder, VERBOSE); tx.setIoMode(IoMode.DOM); - testCrud(tx, this.realm.getCtxFactoryDelegator(), fileDao); + testCrud(this.realm.getCtxFactoryDelegator(), fileDao); } } - private void testCrud(PersistenceTransaction tx, PersistenceContextFactoryDelegator ctxFactoryDelegator, - FileDao fileDao) { + private void testCrud(PersistenceContextFactoryDelegator ctxFactoryDelegator, FileDao fileDao) { Resource resource = createResource(); assertResource(resource); From 3c623bd20cd57e7ce2eb5ac27c4ab6c7d4634eff Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 19 Oct 2013 21:28:02 +0200 Subject: [PATCH 39/87] [Project] Set maven parent for this project to ch.eitchnet.parent --- pom.xml | 118 ++++---------------------------------------------------- 1 file changed, 8 insertions(+), 110 deletions(-) diff --git a/pom.xml b/pom.xml index bd8741828..a865ef0ea 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,14 @@ 4.0.0 - ch.eitchnet + + + ch.eitchnet + ch.eitchnet.parent + 0.0.1-SNAPSHOT + ../ch.eitchnet.parent/pom.xml + + ch.eitchnet.xmlpers jar 0.3.0-SNAPSHOT @@ -15,95 +22,24 @@ 2011 - - - GNU Lesser General Public License - http://www.gnu.org/licenses/lgpl.html - repo - - - - eitchnet.ch - http://blog.eitchnet.ch - - - - eitch - Robert von Vurg - eitch@eitchnet.ch - http://blog.eitchnet.ch - eitchnet.ch - http://blog.eitchnet.ch - - architect - developer - - +1 - - http://localhost - - - Github Issues https://github.com/eitch/ch.eitchnet.xmlpers/issues - - scm:git:https://github.com/eitch/ch.eitchnet.xmlpers.git scm:git:git@github.com:eitch/ch.eitchnet.xmlpers.git https://github.com/eitch/ch.eitchnet.xmlpers - - - - - deployment - Internal Releases - http://nexus.eitchnet.ch/content/repositories/releases/ - - - deployment - Internal Releases - http://nexus.eitchnet.ch/content/repositories/snapshots/ - - - - - junit - junit - 4.10 - test - ch.eitchnet ch.eitchnet.utils 0.2.0-SNAPSHOT - - org.slf4j - slf4j-api - 1.7.2 - - - org.slf4j - slf4j-log4j12 - 1.7.2 - test - @@ -112,60 +48,22 @@ org.apache.maven.plugins maven-eclipse-plugin - 2.9 - - true - true - - org.apache.maven.plugins maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - org.apache.maven.plugins maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - org.apache.maven.plugins maven-jar-plugin - 2.4 - - - - true - true - - - - - org.apache.maven.plugins maven-site-plugin - 2.3 - - UTF-8 - From 3c006b541a24ae29b4a5b0de7aebbb07dbf25889 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 19 Oct 2013 21:28:11 +0200 Subject: [PATCH 40/87] [New] implemented a test to allow multiple operations This test makes sure that updating after adding, or any other operation in the same TX works properly. Found a problem where the PersistenceContext didn't implement hashCode() and equals() which lead to each operation being added even though a previous operation was already registered --- .../xmlpers/api/PersistenceContext.java | 39 +++++ .../xmlpers/objref/IdOfSubTypeRef.java | 46 +++++- .../eitchnet/xmlpers/objref/IdOfTypeRef.java | 40 +++++- .../ch/eitchnet/xmlpers/objref/ObjectRef.java | 10 +- .../ch/eitchnet/xmlpers/objref/RootRef.java | 25 ++++ .../eitchnet/xmlpers/objref/SubTypeRef.java | 37 +++++ .../ch/eitchnet/xmlpers/objref/TypeRef.java | 31 ++++ .../java/javanet/staxutils/Indentation.java | 3 +- .../staxutils/IndentingXMLStreamWriter.java | 2 + .../xmlpers/test/ObjectDaoResourceTest.java | 134 ++++++++++++++++++ 10 files changed, 360 insertions(+), 7 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index 5a074832f..9655d5e35 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -52,4 +52,43 @@ public class PersistenceContext { public void setParserFactory(ParserFactory parserFactory) { this.parserFactory = parserFactory; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.objectRef == null) ? 0 : this.objectRef.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PersistenceContext other = (PersistenceContext) obj; + if (this.objectRef == null) { + if (other.objectRef != null) + return false; + } else if (!this.objectRef.equals(other.objectRef)) + return false; + return true; + } + + @SuppressWarnings("nls") + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("PersistenceContext [objectRef="); + builder.append(this.objectRef); + builder.append(", object="); + builder.append(this.object); + builder.append(", parserFactory="); + builder.append(this.parserFactory); + builder.append("]"); + return builder.toString(); + } } \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java index 8312a93da..7c7060e8a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java @@ -73,8 +73,50 @@ public class IdOfSubTypeRef extends ObjectRef { @Override public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { PersistenceContextFactoryDelegator ctxFactoryDelegator = tx.getRealm().getCtxFactoryDelegator(); - PersistenceContextFactory persistenceContextFactory = ctxFactoryDelegator - . getCtxFactory(this.type); + PersistenceContextFactory persistenceContextFactory = ctxFactoryDelegator. getCtxFactory(this.type); return persistenceContextFactory.createCtx(this); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.id == null) ? 0 : this.id.hashCode()); + result = prime * result + ((this.realmName == null) ? 0 : this.realmName.hashCode()); + result = prime * result + ((this.subType == null) ? 0 : this.subType.hashCode()); + result = prime * result + ((this.type == null) ? 0 : this.type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + IdOfSubTypeRef other = (IdOfSubTypeRef) obj; + if (this.realmName == null) { + if (other.realmName != null) + return false; + } else if (!this.realmName.equals(other.realmName)) + return false; + if (this.id == null) { + if (other.id != null) + return false; + } else if (!this.id.equals(other.id)) + return false; + if (this.subType == null) { + if (other.subType != null) + return false; + } else if (!this.subType.equals(other.subType)) + return false; + if (this.type == null) { + if (other.type != null) + return false; + } else if (!this.type.equals(other.type)) + return false; + return true; + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java index a6f09dbef..dec93808e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java @@ -67,8 +67,44 @@ public class IdOfTypeRef extends ObjectRef { @Override public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { PersistenceContextFactoryDelegator ctxFactoryDelegator = tx.getRealm().getCtxFactoryDelegator(); - PersistenceContextFactory persistenceContextFactory = ctxFactoryDelegator - . getCtxFactory(this.type); + PersistenceContextFactory persistenceContextFactory = ctxFactoryDelegator. getCtxFactory(this.type); return persistenceContextFactory.createCtx(this); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.id == null) ? 0 : this.id.hashCode()); + result = prime * result + ((this.realmName == null) ? 0 : this.realmName.hashCode()); + result = prime * result + ((this.type == null) ? 0 : this.type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + IdOfTypeRef other = (IdOfTypeRef) obj; + if (this.realmName == null) { + if (other.realmName != null) + return false; + } else if (!this.realmName.equals(other.realmName)) + return false; + if (this.id == null) { + if (other.id != null) + return false; + } else if (!this.id.equals(other.id)) + return false; + if (this.type == null) { + if (other.type != null) + return false; + } else if (!this.type.equals(other.type)) + return false; + return true; + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java index a97b4f681..356bdff4e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java @@ -8,8 +8,8 @@ import ch.eitchnet.xmlpers.impl.PathBuilder; public abstract class ObjectRef extends LockableObject { - private String realmName; - private String name; + protected final String realmName; + protected final String name; protected ObjectRef(String realmName, String name) { this.realmName = realmName; @@ -44,4 +44,10 @@ public abstract class ObjectRef extends LockableObject { public String toString() { return getName(); } + + @Override + public abstract boolean equals(Object obj); + + @Override + public abstract int hashCode(); } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java index cb621a3d9..65640ab24 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java @@ -56,4 +56,29 @@ public class RootRef extends ObjectRef { String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ throw new UnsupportedOperationException(msg); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.realmName == null) ? 0 : this.realmName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + RootRef other = (RootRef) obj; + if (this.realmName == null) { + if (other.realmName != null) + return false; + } else if (!this.realmName.equals(other.realmName)) + return false; + return true; + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java index 560526b3d..fefcba6ef 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java @@ -63,4 +63,41 @@ public class SubTypeRef extends ObjectRef { String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ throw new UnsupportedOperationException(msg); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.realmName == null) ? 0 : this.realmName.hashCode()); + result = prime * result + ((this.subType == null) ? 0 : this.subType.hashCode()); + result = prime * result + ((this.type == null) ? 0 : this.type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + SubTypeRef other = (SubTypeRef) obj; + if (this.realmName == null) { + if (other.realmName != null) + return false; + } else if (!this.realmName.equals(other.realmName)) + return false; + if (this.subType == null) { + if (other.subType != null) + return false; + } else if (!this.subType.equals(other.subType)) + return false; + if (this.type == null) { + if (other.type != null) + return false; + } else if (!this.type.equals(other.type)) + return false; + return true; + } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java index 44e2770a1..be34fff63 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java @@ -56,4 +56,35 @@ public class TypeRef extends ObjectRef { String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ throw new UnsupportedOperationException(msg); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((this.realmName == null) ? 0 : this.realmName.hashCode()); + result = prime * result + ((this.type == null) ? 0 : this.type.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TypeRef other = (TypeRef) obj; + if (this.realmName == null) { + if (other.realmName != null) + return false; + } else if (!this.realmName.equals(other.realmName)) + return false; + if (this.type == null) { + if (other.type != null) + return false; + } else if (!this.type.equals(other.type)) + return false; + return true; + } } diff --git a/src/main/java/javanet/staxutils/Indentation.java b/src/main/java/javanet/staxutils/Indentation.java index 4dfa7b48e..e7f554b92 100644 --- a/src/main/java/javanet/staxutils/Indentation.java +++ b/src/main/java/javanet/staxutils/Indentation.java @@ -4,10 +4,11 @@ package javanet.staxutils; * Characters that represent line breaks and indentation. These are represented * as String-valued JavaBean properties. */ +@SuppressWarnings("nls") public interface Indentation { /** Two spaces; the default indentation. */ - public static final String DEFAULT_INDENT = " "; + public static final String DEFAULT_INDENT = " "; /** * Set the characters used for one level of indentation. The default is diff --git a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java index dd5438e24..aa9ffc3b6 100644 --- a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java +++ b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java @@ -32,6 +32,7 @@ package javanet.staxutils; import javanet.staxutils.helpers.StreamWriterDelegate; + import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; @@ -68,6 +69,7 @@ import javax.xml.stream.XMLStreamWriter; * * @author John Kristian */ +@SuppressWarnings("nls") public class IndentingXMLStreamWriter extends StreamWriterDelegate implements Indentation { public IndentingXMLStreamWriter(XMLStreamWriter out) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java index 0932971f2..69b1f2edf 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java @@ -21,12 +21,14 @@ */ package ch.eitchnet.xmlpers.test; +import static ch.eitchnet.xmlpers.test.impl.TestConstants.TYPE_RES; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResource; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.assertResourceUpdated; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; +import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -36,12 +38,15 @@ import java.util.List; import java.util.Properties; import org.junit.BeforeClass; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.ObjectDao; import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; import ch.eitchnet.xmlpers.objref.ObjectRef; import ch.eitchnet.xmlpers.objref.SubTypeRef; @@ -55,6 +60,9 @@ import ch.eitchnet.xmlpers.test.model.Resource; */ public class ObjectDaoResourceTest extends AbstractPersistenceTest { + @Rule + public ExpectedException thrown = ExpectedException.none(); + private static final String BASEPATH = "target/db/ObjectDaoTest/"; //$NON-NLS-1$ @BeforeClass @@ -226,4 +234,130 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { assertNull("Expected that resource was deleted by ID, thus can not be read anymore", resource); //$NON-NLS-1$ } } + + @Test + public void shouldFailModifyNotExisting() { + setup(IoMode.SAX); + + this.thrown.expect(XmlPersistenceException.class); + this.thrown.expectMessage(containsString("Persistence unit does not exist for")); //$NON-NLS-1$ + + // update + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + Resource resource = createResource(); + tx.getObjectDao().update(resource); + } + } + + @Test + public void shouldFailDeleteNotExisting() { + setup(IoMode.SAX); + + this.thrown.expect(XmlPersistenceException.class); + this.thrown.expectMessage(containsString("Persistence unit does not exist for")); //$NON-NLS-1$ + + // delete + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + Resource resource = createResource(); + tx.getObjectDao().remove(resource); + } + } + + @Test + public void shouldAllowAllOperationsInSameTx() { + setup(IoMode.SAX); + + String subType = ModelBuilder.RES_TYPE; + String name = "shouldPersistById "; //$NON-NLS-1$ + + // create + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + String id = "shouldAllowAllOperationsInSameTx_create"; //$NON-NLS-1$ + Resource resource = createResource(id, name, subType); + + tx.getObjectDao().add(resource); + } + + // create / modify + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + String id = "shouldAllowAllOperationsInSameTx_create_modify"; //$NON-NLS-1$ + Resource resource = createResource(id, name, subType); + + tx.getObjectDao().add(resource); + tx.getObjectDao().update(resource); + } + + // create / delete + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + String id = "shouldAllowAllOperationsInSameTx_create_delete"; //$NON-NLS-1$ + Resource resource = createResource(id, name, subType); + + tx.getObjectDao().add(resource); + tx.getObjectDao().remove(resource); + } + + // create / modify / delete + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + String id = "shouldAllowAllOperationsInSameTx_create_modify_delete"; //$NON-NLS-1$ + Resource resource = createResource(id, name, subType); + + tx.getObjectDao().add(resource); + tx.getObjectDao().update(resource); + tx.getObjectDao().remove(resource); + } + + String id = "shouldAllowAllOperationsInSameTx_read_modify"; //$NON-NLS-1$ + + // prepare for read/modify + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + Resource resource = createResource(id, name, subType); + tx.getObjectDao().add(resource); + } + + // read / modify + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, subType, id); + Object resource = tx.getObjectDao().queryById(objectRef); + assertNotNull(resource); + tx.getObjectDao().update(resource); + } + + // read / delete + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, subType, id); + Object resource = tx.getObjectDao().queryById(objectRef); + assertNotNull(resource); + tx.getObjectDao().remove(resource); + } + + // make sure deleted, then recreate + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, subType, id); + Object resource = tx.getObjectDao().queryById(objectRef); + assertNull(resource); + + // recreate + resource = createResource(id, name, subType); + tx.getObjectDao().add(resource); + } + + // read / modify / delete + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + + ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, subType, id); + Object resource = tx.getObjectDao().queryById(objectRef); + assertNotNull(resource); + tx.getObjectDao().update(resource); + tx.getObjectDao().remove(resource); + } + } } From 87f82e19797e88052e6995bd51f08ce835483653 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 20 Oct 2013 01:14:59 +0200 Subject: [PATCH 41/87] [New] implemented locking for all persistence operations A LockingTest tests the locking, but still needs to be extended to test further use cases, but basic locking works. --- .../java/ch/eitchnet/xmlpers/api/FileDao.java | 76 ++++---- .../ch/eitchnet/xmlpers/api/MetadataDao.java | 84 +++++---- .../ch/eitchnet/xmlpers/api/ObjectDao.java | 96 ++++++++--- .../xmlpers/api/PersistenceConstants.java | 1 + .../impl/DefaultPersistenceManager.java | 15 +- .../impl/DefaultPersistenceTransaction.java | 15 +- .../xmlpers/objref/LockableObject.java | 45 ++++- .../xmlpers/test/AbstractPersistenceTest.java | 5 + .../ch/eitchnet/xmlpers/test/LockingTest.java | 162 ++++++++++++++++++ .../xmlpers/test/model/ModelBuilder.java | 4 + 10 files changed, 402 insertions(+), 101 deletions(-) create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java index c646d19f1..ffd55b2e9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java @@ -112,33 +112,41 @@ public class FileDao { throw new IllegalArgumentException("IdRefs don't reference directories!"); //$NON-NLS-1$ } - File directoryPath = objectRef.getPath(this.pathBuilder); - if (!directoryPath.isDirectory()) { - String msg = "The path for {0} is not a directory: {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, objectRef.getName(), directoryPath.getAbsolutePath()); - throw new IllegalArgumentException(msg); + objectRef.lock(); + + try { + + File directoryPath = objectRef.getPath(this.pathBuilder); + if (!directoryPath.isDirectory()) { + String msg = "The path for {0} is not a directory: {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), directoryPath.getAbsolutePath()); + throw new IllegalArgumentException(msg); + } + + // stop if empty + if (directoryPath.list().length != 0) + return; + + // delete + if (!directoryPath.delete()) { + String msg = "Deletion of empty directory for {0} at {1} failed! Check file permissions!"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), directoryPath.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + + // log + if (this.verbose) { + String msg = "Deleted empty directory for {0} at {1}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, objectRef.getName(), directoryPath)); + } + + // recursively delete + ObjectRef parent = objectRef.getParent(this.tx); + deleteEmptyDirectories(parent); + + } finally { + objectRef.unlock(); } - - // stop if empty - if (directoryPath.list().length != 0) - return; - - // delete - if (!directoryPath.delete()) { - String msg = "Deletion of empty directory for {0} at {1} failed! Check file permissions!"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, objectRef.getName(), directoryPath.getAbsolutePath()); - throw new XmlPersistenceException(msg); - } - - // log - if (this.verbose) { - String msg = "Deleted empty directory for {0} at {1}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, objectRef.getName(), directoryPath)); - } - - // recursively delete - ObjectRef parent = objectRef.getParent(this.tx); - deleteEmptyDirectories(parent); } private void logPath(IoOperation operation, File path, ObjectRef objectRef) { @@ -150,11 +158,17 @@ public class FileDao { } private void createMissingParents(File path, ObjectRef objectRef) { - File parentFile = path.getParentFile(); - if (!parentFile.exists() && !parentFile.mkdirs()) { - String msg = "Could not create parent path for {0} at {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, objectRef.getName(), path.getAbsolutePath()); - throw new XmlPersistenceException(msg); + ObjectRef parentRef = objectRef.getParent(this.tx); + parentRef.lock(); + try { + File parentFile = parentRef.getPath(this.pathBuilder); + if (!parentFile.exists() && !parentFile.mkdirs()) { + String msg = "Could not create parent path for {0} at {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, objectRef.getName(), path.getAbsolutePath()); + throw new XmlPersistenceException(msg); + } + } finally { + parentRef.unlock(); } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java index b2e57e7e6..c2f80da0d 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java @@ -56,16 +56,21 @@ public class MetadataDao { assertNotClosed(this.tx); assertNotIdRef(parentRef); - File queryPath = parentRef.getPath(this.pathBuilder); - Set keySet = queryTypeSet(queryPath); + parentRef.lock(); + try { + File queryPath = parentRef.getPath(this.pathBuilder); + Set keySet = queryTypeSet(queryPath); - if (this.verbose) { - String msg = "Found {0} types for {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, keySet.size(), parentRef.getName()); - logger.info(msg); + if (this.verbose) { + String msg = "Found {0} types for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), parentRef.getName()); + logger.info(msg); + } + + return keySet; + } finally { + parentRef.unlock(); } - - return keySet; } public Set queryKeySet(ObjectRef parentRef) { @@ -73,16 +78,21 @@ public class MetadataDao { assertNotRootRef(parentRef); assertNotIdRef(parentRef); - File queryPath = parentRef.getPath(this.pathBuilder); - Set keySet = queryKeySet(queryPath); + parentRef.lock(); + try { + File queryPath = parentRef.getPath(this.pathBuilder); + Set keySet = queryKeySet(queryPath); - if (this.verbose) { - String msg = "Found {0} objects for {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, keySet.size(), parentRef.getName()); - logger.info(msg); + if (this.verbose) { + String msg = "Found {0} objects for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, keySet.size(), parentRef.getName()); + logger.info(msg); + } + + return keySet; + } finally { + parentRef.unlock(); } - - return keySet; } public long queryTypeSize(ObjectRef parentRef) { @@ -90,31 +100,41 @@ public class MetadataDao { assertNotRootRef(parentRef); assertNotIdRef(parentRef); - File queryPath = parentRef.getPath(this.pathBuilder); - long numberOfFiles = queryTypeSize(queryPath); + parentRef.lock(); + try { + File queryPath = parentRef.getPath(this.pathBuilder); + long numberOfFiles = queryTypeSize(queryPath); - if (this.verbose) { - String msg = "Found {0} types for {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, numberOfFiles, parentRef.getName()); - logger.info(msg); + if (this.verbose) { + String msg = "Found {0} types for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, parentRef.getName()); + logger.info(msg); + } + + return numberOfFiles; + } finally { + parentRef.unlock(); } - - return numberOfFiles; } public long querySize(ObjectRef parentRef) { assertNotClosed(this.tx); - File queryPath = parentRef.getPath(this.pathBuilder); - long numberOfFiles = querySize(queryPath); + parentRef.lock(); + try { + File queryPath = parentRef.getPath(this.pathBuilder); + long numberOfFiles = querySize(queryPath); - if (this.verbose) { - String msg = "Found {0} objects for {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, numberOfFiles, parentRef.getName()); - logger.info(msg); + if (this.verbose) { + String msg = "Found {0} objects for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, numberOfFiles, parentRef.getName()); + logger.info(msg); + } + + return numberOfFiles; + } finally { + parentRef.unlock(); } - - return numberOfFiles; } /** diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index 872c37a3b..c884db65f 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -57,6 +57,7 @@ public class ObjectDao { assertNotNull(object); PersistenceContext ctx = createCtx(object); ctx.setObject(object); + ctx.getObjectRef().lock(); this.objectFilter.add(object.getClass().getName(), ctx); } @@ -67,6 +68,7 @@ public class ObjectDao { for (T object : objects) { PersistenceContext ctx = createCtx(object); ctx.setObject(object); + ctx.getObjectRef().lock(); this.objectFilter.add(object.getClass().getName(), ctx); } } @@ -77,6 +79,7 @@ public class ObjectDao { assertNotNull(object); PersistenceContext ctx = createCtx(object); ctx.setObject(object); + ctx.getObjectRef().lock(); this.objectFilter.update(object.getClass().getName(), ctx); } @@ -87,6 +90,7 @@ public class ObjectDao { for (T object : objects) { PersistenceContext ctx = createCtx(object); ctx.setObject(object); + ctx.getObjectRef().lock(); this.objectFilter.update(object.getClass().getName(), ctx); } } @@ -97,6 +101,7 @@ public class ObjectDao { assertNotNull(object); PersistenceContext ctx = createCtx(object); ctx.setObject(object); + ctx.getObjectRef().lock(); this.objectFilter.remove(object.getClass().getName(), ctx); } @@ -107,6 +112,7 @@ public class ObjectDao { for (T object : objects) { PersistenceContext ctx = createCtx(object); ctx.setObject(object); + ctx.getObjectRef().lock(); this.objectFilter.remove(object.getClass().getName(), ctx); } } @@ -116,6 +122,7 @@ public class ObjectDao { assertNotClosed(); assertIsIdRef(objectRef); PersistenceContext ctx = createCtx(objectRef); + ctx.getObjectRef().lock(); this.objectFilter.remove(objectRef.getType(), ctx); } @@ -124,60 +131,99 @@ public class ObjectDao { assertIsNotIdRef(parentRef); assertIsNotRootRef(parentRef); - Set keySet = queryKeySet(parentRef); - for (String id : keySet) { + parentRef.lock(); + try { - ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); - PersistenceContext ctx = createCtx(childRef); - this.objectFilter.remove(childRef.getType(), ctx); + Set keySet = queryKeySet(parentRef); + for (String id : keySet) { + + ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); + PersistenceContext ctx = createCtx(childRef); + ctx.getObjectRef().lock(); + this.objectFilter.remove(childRef.getType(), ctx); + } + } finally { + parentRef.unlock(); } } public T queryById(ObjectRef objectRef) { assertNotClosed(); assertIsIdRef(objectRef); - PersistenceContext ctx = objectRef. createPersistenceContext(this.tx); - this.fileDao.performRead(ctx); - return ctx.getObject(); + + objectRef.lock(); + try { + PersistenceContext ctx = objectRef. createPersistenceContext(this.tx); + ctx.getObjectRef().lock(); + try { + this.fileDao.performRead(ctx); + return ctx.getObject(); + } finally { + ctx.getObjectRef().unlock(); + } + } finally { + objectRef.unlock(); + } } public List queryAll(ObjectRef parentRef) { assertNotClosed(); assertIsNotIdRef(parentRef); - MetadataDao metadataDao = this.tx.getMetadataDao(); - Set keySet = metadataDao.queryKeySet(parentRef); + parentRef.lock(); + try { - List result = new ArrayList<>(); - for (String id : keySet) { + MetadataDao metadataDao = this.tx.getMetadataDao(); + Set keySet = metadataDao.queryKeySet(parentRef); - ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); - PersistenceContext childCtx = childRef.createPersistenceContext(this.tx); + List result = new ArrayList<>(); + for (String id : keySet) { - this.fileDao.performRead(childCtx); - assertObjectRead(childCtx); - result.add(childCtx.getObject()); + ObjectRef childRef = parentRef.getChildIdRef(this.tx, id); + PersistenceContext childCtx = childRef.createPersistenceContext(this.tx); + childCtx.getObjectRef().lock(); + try { + this.fileDao.performRead(childCtx); + assertObjectRead(childCtx); + result.add(childCtx.getObject()); + } finally { + childCtx.getObjectRef().unlock(); + } + } + + return result; + + } finally { + parentRef.unlock(); } - - return result; } public Set queryKeySet(ObjectRef parentRef) { assertNotClosed(); assertIsNotIdRef(parentRef); - MetadataDao metadataDao = this.tx.getMetadataDao(); - Set keySet = metadataDao.queryKeySet(parentRef); - return keySet; + parentRef.lock(); + try { + MetadataDao metadataDao = this.tx.getMetadataDao(); + Set keySet = metadataDao.queryKeySet(parentRef); + return keySet; + } finally { + parentRef.unlock(); + } } public long querySize(ObjectRef parentRef) { assertNotClosed(); assertIsNotIdRef(parentRef); - MetadataDao metadataDao = this.tx.getMetadataDao(); - long size = metadataDao.querySize(parentRef); - return size; + parentRef.lock(); + try { + MetadataDao metadataDao = this.tx.getMetadataDao(); + long size = metadataDao.querySize(parentRef); + return size; + } finally { + parentRef.unlock(); + } } private PersistenceContext createCtx(T object) { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java index c06b54717..85ed328f9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java @@ -33,4 +33,5 @@ public class PersistenceConstants { public static final String PROP_BASEPATH = PROP_PREFIX + "basePath"; public static final String PROP_DAO_FACTORY_CLASS = PROP_PREFIX + "daoFactoryClass"; public static final String PROP_XML_IO_MOD = PROP_PREFIX + "ioMode"; + public static final String PROP_XML_LOCK_TIME_MILLIS = PROP_PREFIX + "lockTimeSeconds"; } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java index 950f1dfeb..262efed02 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java @@ -22,6 +22,7 @@ package ch.eitchnet.xmlpers.impl; import java.io.File; +import java.lang.reflect.Field; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; @@ -37,6 +38,7 @@ import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; import ch.eitchnet.xmlpers.api.PersistenceManager; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.api.XmlPersistenceException; +import ch.eitchnet.xmlpers.objref.LockableObject; import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; /** @@ -60,12 +62,23 @@ public class DefaultPersistenceManager implements PersistenceManager { String context = DefaultPersistenceManager.class.getSimpleName(); - // get verbose flag + // get properties boolean verbose = PropertiesHelper.getPropertyBool(properties, context, PersistenceConstants.PROP_VERBOSE, Boolean.FALSE).booleanValue(); String ioModeS = PropertiesHelper.getProperty(properties, context, PersistenceConstants.PROP_XML_IO_MOD, IoMode.DOM.name()); IoMode ioMode = IoMode.valueOf(ioModeS); + long lockTime = PropertiesHelper.getPropertyLong(properties, context, + PersistenceConstants.PROP_XML_LOCK_TIME_MILLIS, 10000L); + + // set lock time on LockableObject + try { + Field lockTimeField = LockableObject.class.getDeclaredField("tryLockTime");//$NON-NLS-1$ + lockTimeField.setAccessible(true); + lockTimeField.setLong(null, lockTime); + } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException("Failed to configure tryLockTime on LockableObject!", e); //$NON-NLS-1$ + } // validate base path validateBasePath(properties); diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index d9c524212..225085423 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -112,6 +112,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { throw new IllegalStateException("Transaction has already been committed!"); //$NON-NLS-1$ if (!this.closed) { + unlockObjectRefs(); this.closed = true; this.objectFilter.clearCache(); } @@ -124,13 +125,12 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { try { - Set keySet = this.objectFilter.keySet(); - if (this.verbose) { String msg = "Committing {0} operations in TX...";//$NON-NLS-1$ - logger.info(MessageFormat.format(msg, keySet.size())); + logger.info(MessageFormat.format(msg, this.objectFilter.sizeCache())); } + Set keySet = this.objectFilter.keySet(); for (String key : keySet) { List removed = this.objectFilter.getRemoved(key); @@ -191,11 +191,20 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { } finally { // clean up + unlockObjectRefs(); this.objectFilter.clearCache(); this.committed = true; } } + @SuppressWarnings("rawtypes") + private void unlockObjectRefs() { + List lockedObjects = this.objectFilter.getAll(PersistenceContext.class); + for (PersistenceContext lockedObject : lockedObjects) { + lockedObject.getObjectRef().unlock(); + } + } + @Override public boolean isOpen() { return !this.closed && !this.committed; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java index 250f3e488..2de5447e6 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -1,29 +1,56 @@ package ch.eitchnet.xmlpers.objref; -import java.util.concurrent.locks.Lock; +import java.text.MessageFormat; +import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ch.eitchnet.utils.helper.StringHelper; +import ch.eitchnet.xmlpers.api.XmlPersistenceException; + public class LockableObject { - private final Lock lock; + private static final Logger logger = LoggerFactory.getLogger(LockableObject.class); + private static long tryLockTime = 10000L; + + private final ReentrantLock lock; public LockableObject() { - this.lock = new ReentrantLock(); + this.lock = new ReentrantLock(true); + } + + public static long getLockTime() { + return tryLockTime; + } + + public boolean isLockedByCurrentThread() { + return this.lock.isHeldByCurrentThread(); } /** - * @return - * @see java.util.concurrent.locks.Lock#tryLock() + * @see java.util.concurrent.locks.ReentrantLock#tryLock(long, TimeUnit) */ - public boolean tryLock() { - return this.lock.tryLock(); + public void lock() { + try { + + logger.info("locking " + this.toString()); //$NON-NLS-1$ + if (!this.lock.tryLock(tryLockTime, TimeUnit.MILLISECONDS)) { + String msg = "Failed to acquire lock after {0} for {1}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, StringHelper.formatMillisecondsDuration(tryLockTime), this.toString()); + throw new XmlPersistenceException(msg); + } + } catch (InterruptedException e) { + throw new XmlPersistenceException("Thread interrupted: " + e.getMessage(), e); //$NON-NLS-1$ + } } /** - * - * @see java.util.concurrent.locks.Lock#unlock() + * @see java.util.concurrent.locks.ReentrantLock#unlock() */ public void unlock() { this.lock.unlock(); + logger.info("unlocking " + this.toString()); //$NON-NLS-1$ } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java index 5a47834d8..9b6086e84 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java @@ -3,6 +3,9 @@ package ch.eitchnet.xmlpers.test; import java.io.File; import java.util.Properties; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import ch.eitchnet.utils.helper.FileHelper; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.PersistenceConstants; @@ -16,6 +19,8 @@ import ch.eitchnet.xmlpers.test.model.Resource; public abstract class AbstractPersistenceTest { + protected static final Logger logger = LoggerFactory.getLogger(AbstractPersistenceTest.class); + protected PersistenceManager persistenceManager; @SuppressWarnings("nls") diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java new file mode 100644 index 000000000..9793a66b2 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.objref.LockableObject; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class LockingTest extends AbstractPersistenceTest { + + private static final String BASE_PATH = "target/db/LockingTest/"; //$NON-NLS-1$ + + long waitForWorkersTime = LockableObject.getLockTime() + 2000L; + + @BeforeClass + public static void beforeClass() { + cleanPath(BASE_PATH); + } + + @Before + public void before() { + Properties properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASE_PATH + IoMode.DOM.name()); + setup(properties); + } + + @Test + public void shouldLockObjects() throws InterruptedException { + + List workers = new ArrayList<>(5); + + for (int i = 0; i < 5; i++) { + + String workerName = "worker_" + i; //$NON-NLS-1$ + Worker worker = new Worker(workerName, workerName); + worker.start(); + workers.add(worker); + logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$ + } + + int nrOfSuccess = runWorkers(workers); + + assertEquals("Only one thread should be able to perform the TX!", 5, nrOfSuccess); //$NON-NLS-1$ + } + + @Test + public void shouldFailIfLockNotAcquirable() throws InterruptedException { + + List workers = new ArrayList<>(5); + + for (int i = 0; i < 5; i++) { + + String workerName = "workerRes"; //$NON-NLS-1$ + Worker worker = new Worker(workerName, workerName); + worker.start(); + workers.add(worker); + logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$ + } + + int nrOfSuccess = runWorkers(workers); + + assertEquals("Only one thread should be able to perform the TX!", 1, nrOfSuccess); //$NON-NLS-1$ + } + + private int runWorkers(List workers) throws InterruptedException { + + synchronized (this) { + this.notifyAll(); + } + + for (Worker worker : workers) { + worker.join(this.waitForWorkersTime + 2000L); + } + + int nrOfSuccess = 0; + for (Worker worker : workers) { + if (worker.isSuccess()) + nrOfSuccess++; + } + + return nrOfSuccess; + } + + public class Worker extends Thread { + + private boolean success; + private String resourceId; + + public Worker(String name, String resourceId) { + super(name); + this.resourceId = resourceId; + } + + public void run() { + + synchronized (LockingTest.this) { + try { + logger.info("Waiting for ok to work..."); //$NON-NLS-1$ + LockingTest.this.wait(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } + + logger.info("Starting work..."); //$NON-NLS-1$ + try (PersistenceTransaction tx = LockingTest.this.persistenceManager.openTx()) { + + Resource resource = createResource(this.resourceId); + tx.getObjectDao().add(resource); + } + this.success = true; + + try { + Thread.sleep(LockingTest.this.waitForWorkersTime); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + + logger.info("Work completed."); //$NON-NLS-1$ + } + + public boolean isSuccess() { + return this.success; + } + } +} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index 238f11464..1f6dfc432 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -52,6 +52,10 @@ public class ModelBuilder { public static Resource createResource() { return createResource(RES_ID, RES_NAME, RES_TYPE); } + + public static Resource createResource(String id) { + return createResource(id, RES_NAME, RES_TYPE); + } public static Resource createResource(String id, String name, String type) { Resource resource = new Resource(id, name, type); From f24a10992c40a4f8325d9be05c08ab927c258493 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 21 Oct 2013 18:48:23 +0200 Subject: [PATCH 42/87] [New] added test to check acquiring locks Added a test which checks that a TX fails if a lock can not be acquired, but succeeds before the timeout to acquire the lock is exceeded. Further fixed the brittle tests by using a different semaphore to synchronize the threads. --- .../xmlpers/api/PersistenceConstants.java | 2 +- .../impl/DefaultPersistenceManager.java | 4 +- .../ch/eitchnet/xmlpers/test/LockingTest.java | 137 ++++++++++++++---- 3 files changed, 110 insertions(+), 33 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java index 85ed328f9..482389e60 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java @@ -33,5 +33,5 @@ public class PersistenceConstants { public static final String PROP_BASEPATH = PROP_PREFIX + "basePath"; public static final String PROP_DAO_FACTORY_CLASS = PROP_PREFIX + "daoFactoryClass"; public static final String PROP_XML_IO_MOD = PROP_PREFIX + "ioMode"; - public static final String PROP_XML_LOCK_TIME_MILLIS = PROP_PREFIX + "lockTimeSeconds"; + public static final String PROP_LOCK_TIME_MILLIS = PROP_PREFIX + "lockTimeSeconds"; } diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java index 262efed02..21f2ee04b 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java @@ -32,6 +32,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.eitchnet.utils.helper.PropertiesHelper; +import ch.eitchnet.utils.helper.StringHelper; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; @@ -69,13 +70,14 @@ public class DefaultPersistenceManager implements PersistenceManager { IoMode.DOM.name()); IoMode ioMode = IoMode.valueOf(ioModeS); long lockTime = PropertiesHelper.getPropertyLong(properties, context, - PersistenceConstants.PROP_XML_LOCK_TIME_MILLIS, 10000L); + PersistenceConstants.PROP_LOCK_TIME_MILLIS, 10000L); // set lock time on LockableObject try { Field lockTimeField = LockableObject.class.getDeclaredField("tryLockTime");//$NON-NLS-1$ lockTimeField.setAccessible(true); lockTimeField.setLong(null, lockTime); + logger.info("Using a max lock acquire time of " + StringHelper.formatMillisecondsDuration(lockTime)); //$NON-NLS-1$ } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("Failed to configure tryLockTime on LockableObject!", e); //$NON-NLS-1$ } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index 9793a66b2..f70ab8a21 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -21,8 +21,12 @@ */ package ch.eitchnet.xmlpers.test; +import static ch.eitchnet.xmlpers.test.impl.TestConstants.TYPE_RES; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_TYPE; import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.updateResource; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.List; @@ -35,6 +39,7 @@ import org.junit.Test; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; import ch.eitchnet.xmlpers.objref.LockableObject; import ch.eitchnet.xmlpers.test.model.Resource; @@ -46,7 +51,8 @@ public class LockingTest extends AbstractPersistenceTest { private static final String BASE_PATH = "target/db/LockingTest/"; //$NON-NLS-1$ - long waitForWorkersTime = LockableObject.getLockTime() + 2000L; + private long waitForWorkersTime; + private boolean run; @BeforeClass public static void beforeClass() { @@ -57,18 +63,21 @@ public class LockingTest extends AbstractPersistenceTest { public void before() { Properties properties = new Properties(); properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASE_PATH + IoMode.DOM.name()); + properties.setProperty(PersistenceConstants.PROP_LOCK_TIME_MILLIS, Long.toString(500L)); setup(properties); + + this.waitForWorkersTime = LockableObject.getLockTime() + (long) ((double) this.getWaitForWorkersTime() * .2); } @Test public void shouldLockObjects() throws InterruptedException { - List workers = new ArrayList<>(5); + List workers = new ArrayList<>(5); + String resoureId = "worker"; //$NON-NLS-1$ for (int i = 0; i < 5; i++) { - - String workerName = "worker_" + i; //$NON-NLS-1$ - Worker worker = new Worker(workerName, workerName); + String workerName = resoureId + "_" + i; //$NON-NLS-1$ + CreateResourceWorker worker = new CreateResourceWorker(workerName, workerName); worker.start(); workers.add(worker); logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$ @@ -80,14 +89,13 @@ public class LockingTest extends AbstractPersistenceTest { } @Test - public void shouldFailIfLockNotAcquirable() throws InterruptedException { + public void shouldFailIfResourceAlreadyExists() throws InterruptedException { - List workers = new ArrayList<>(5); + List workers = new ArrayList<>(5); + String resourceId = "createWorkerRes"; //$NON-NLS-1$ for (int i = 0; i < 5; i++) { - - String workerName = "workerRes"; //$NON-NLS-1$ - Worker worker = new Worker(workerName, workerName); + CreateResourceWorker worker = new CreateResourceWorker(resourceId, resourceId); worker.start(); workers.add(worker); logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$ @@ -98,18 +106,41 @@ public class LockingTest extends AbstractPersistenceTest { assertEquals("Only one thread should be able to perform the TX!", 1, nrOfSuccess); //$NON-NLS-1$ } - private int runWorkers(List workers) throws InterruptedException { + @Test + public void shouldFailUpdateIfLockNotAcquirable() throws InterruptedException { - synchronized (this) { - this.notifyAll(); + // prepare workers + List workers = new ArrayList<>(5); + String resourceId = "updatWorkerRes"; //$NON-NLS-1$ + for (int i = 0; i < 5; i++) { + String workerName = resourceId + "_" + i; //$NON-NLS-1$ + UpdateResourceWorker worker = new UpdateResourceWorker(workerName, resourceId); + worker.start(); + workers.add(worker); + logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$ } - for (Worker worker : workers) { - worker.join(this.waitForWorkersTime + 2000L); + // create resource which is to be updated + try (PersistenceTransaction tx = this.persistenceManager.openTx()) { + Resource resource = createResource(resourceId); + tx.getObjectDao().add(resource); + } + + int nrOfSuccess = runWorkers(workers); + + assertEquals("Only one thread should be able to perform the TX!", 1, nrOfSuccess); //$NON-NLS-1$ + } + + private int runWorkers(List workers) throws InterruptedException { + + this.setRun(true); + + for (AbstractWorker worker : workers) { + worker.join(this.getWaitForWorkersTime() + 2000L); } int nrOfSuccess = 0; - for (Worker worker : workers) { + for (AbstractWorker worker : workers) { if (worker.isSuccess()) nrOfSuccess++; } @@ -117,22 +148,34 @@ public class LockingTest extends AbstractPersistenceTest { return nrOfSuccess; } - public class Worker extends Thread { + public long getWaitForWorkersTime() { + return this.waitForWorkersTime; + } - private boolean success; - private String resourceId; + public boolean isRun() { + return this.run; + } - public Worker(String name, String resourceId) { + public void setRun(boolean run) { + this.run = run; + } + + public abstract class AbstractWorker extends Thread { + + protected boolean success; + protected String resourceId; + + public AbstractWorker(String name, String resourceId) { super(name); this.resourceId = resourceId; } public void run() { - synchronized (LockingTest.this) { + logger.info("Waiting for ok to work..."); //$NON-NLS-1$ + while (!LockingTest.this.isRun()) { try { - logger.info("Waiting for ok to work..."); //$NON-NLS-1$ - LockingTest.this.wait(); + Thread.sleep(10L); } catch (InterruptedException e) { throw new RuntimeException(e); } @@ -140,23 +183,55 @@ public class LockingTest extends AbstractPersistenceTest { logger.info("Starting work..."); //$NON-NLS-1$ try (PersistenceTransaction tx = LockingTest.this.persistenceManager.openTx()) { + doWork(tx); - Resource resource = createResource(this.resourceId); - tx.getObjectDao().add(resource); - } - this.success = true; + try { + Thread.sleep(getWaitForWorkersTime()); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } - try { - Thread.sleep(LockingTest.this.waitForWorkersTime); - } catch (InterruptedException e) { - throw new RuntimeException(e); + this.success = true; } logger.info("Work completed."); //$NON-NLS-1$ } + protected abstract void doWork(PersistenceTransaction tx); + public boolean isSuccess() { return this.success; } } + + public class CreateResourceWorker extends AbstractWorker { + + public CreateResourceWorker(String name, String resourceId) { + super(name, resourceId); + } + + @Override + protected void doWork(PersistenceTransaction tx) { + Resource resource = createResource(this.resourceId); + tx.getObjectDao().add(resource); + } + } + + public class UpdateResourceWorker extends AbstractWorker { + + public UpdateResourceWorker(String name, String resourceId) { + super(name, resourceId); + } + + @Override + protected void doWork(PersistenceTransaction tx) { + + IdOfSubTypeRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, RES_TYPE, this.resourceId); + Resource resource = tx.getObjectDao().queryById(objectRef); + assertNotNull(resource); + updateResource(resource); + + tx.getObjectDao().update(resource); + } + } } From 59635eddf195875361102180495d1d31939f7a4e Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 24 Oct 2013 21:45:11 +0200 Subject: [PATCH 43/87] [Minor] modified how objects are added to the ObjectFilter Now objects are not added by their class names, but the type is retrieved from the object reference --- src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java | 12 ++++++------ .../api/PersistenceContextFactoryDelegator.java | 2 -- .../ch/eitchnet/xmlpers/test/impl/TestConstants.java | 7 ++----- 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index c884db65f..aba2fc7b5 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -58,7 +58,7 @@ public class ObjectDao { PersistenceContext ctx = createCtx(object); ctx.setObject(object); ctx.getObjectRef().lock(); - this.objectFilter.add(object.getClass().getName(), ctx); + this.objectFilter.add(ctx.getObjectRef().getType(), ctx); } public void addAll(List objects) { @@ -69,7 +69,7 @@ public class ObjectDao { PersistenceContext ctx = createCtx(object); ctx.setObject(object); ctx.getObjectRef().lock(); - this.objectFilter.add(object.getClass().getName(), ctx); + this.objectFilter.add(ctx.getObjectRef().getType(), ctx); } } } @@ -80,7 +80,7 @@ public class ObjectDao { PersistenceContext ctx = createCtx(object); ctx.setObject(object); ctx.getObjectRef().lock(); - this.objectFilter.update(object.getClass().getName(), ctx); + this.objectFilter.update(ctx.getObjectRef().getType(), ctx); } public void updateAll(List objects) { @@ -91,7 +91,7 @@ public class ObjectDao { PersistenceContext ctx = createCtx(object); ctx.setObject(object); ctx.getObjectRef().lock(); - this.objectFilter.update(object.getClass().getName(), ctx); + this.objectFilter.update(ctx.getObjectRef().getType(), ctx); } } } @@ -102,7 +102,7 @@ public class ObjectDao { PersistenceContext ctx = createCtx(object); ctx.setObject(object); ctx.getObjectRef().lock(); - this.objectFilter.remove(object.getClass().getName(), ctx); + this.objectFilter.remove(ctx.getObjectRef().getType(), ctx); } public void removeAll(List objects) { @@ -113,7 +113,7 @@ public class ObjectDao { PersistenceContext ctx = createCtx(object); ctx.setObject(object); ctx.getObjectRef().lock(); - this.objectFilter.remove(object.getClass().getName(), ctx); + this.objectFilter.remove(ctx.getObjectRef().getType(), ctx); } } } diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java index bddabd33c..da0a8056e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java @@ -44,8 +44,6 @@ public class PersistenceContextFactoryDelegator { this.contextFactoryCacheByClass.put(classType, ctxFactory); this.contextFactoryCacheByType.put(type, ctxFactory); - if (!classType.getName().equals(type)) - this.contextFactoryCacheByType.put(classType.getName(), ctxFactory); } public PersistenceContextFactory getCtxFactory(Class classType) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java index 1ac98b08c..18ec8cafd 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java @@ -21,15 +21,12 @@ */ package ch.eitchnet.xmlpers.test.impl; -import ch.eitchnet.xmlpers.test.model.Book; -import ch.eitchnet.xmlpers.test.model.Resource; - /** * @author Robert von Burg * */ public class TestConstants { - public static final String TYPE_RES = Resource.class.getSimpleName(); - public static final String TYPE_BOOK = Book.class.getSimpleName(); + public static final String TYPE_RES = "Resource"; //$NON-NLS-1$ + public static final String TYPE_BOOK = "Book"; //$NON-NLS-1$ } From 9ea4929497e51f93dd2e67c81c045b382377fef0 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 27 Oct 2013 23:06:35 +0100 Subject: [PATCH 44/87] [Minor] set parent to 0.1.0-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a865ef0ea..cb6be517c 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ ch.eitchnet ch.eitchnet.parent - 0.0.1-SNAPSHOT + 0.1.0-SNAPSHOT ../ch.eitchnet.parent/pom.xml From 549d8fb8a7ca84aad0ac2795ec4dca8bf02d46a3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 28 Oct 2013 15:40:21 +0100 Subject: [PATCH 45/87] Update LockableObject.java --- src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java index 2de5447e6..af499f317 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -35,12 +35,12 @@ public class LockableObject { public void lock() { try { - logger.info("locking " + this.toString()); //$NON-NLS-1$ if (!this.lock.tryLock(tryLockTime, TimeUnit.MILLISECONDS)) { String msg = "Failed to acquire lock after {0} for {1}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, StringHelper.formatMillisecondsDuration(tryLockTime), this.toString()); throw new XmlPersistenceException(msg); } + logger.info("locked " + this.toString()); //$NON-NLS-1$ } catch (InterruptedException e) { throw new XmlPersistenceException("Thread interrupted: " + e.getMessage(), e); //$NON-NLS-1$ } From ff5304a1a025631e92e7dbdadb41d9040e878146 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 28 Oct 2013 15:46:08 +0100 Subject: [PATCH 46/87] Update LockingTest.java --- src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index f70ab8a21..69ee0d3f7 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -95,7 +95,8 @@ public class LockingTest extends AbstractPersistenceTest { String resourceId = "createWorkerRes"; //$NON-NLS-1$ for (int i = 0; i < 5; i++) { - CreateResourceWorker worker = new CreateResourceWorker(resourceId, resourceId); + String workerName = resourceId + "_" + i; + CreateResourceWorker worker = new CreateResourceWorker(workerName, resourceId); worker.start(); workers.add(worker); logger.info("Setup thread " + worker.getName()); //$NON-NLS-1$ From c69ebe8e245f61fdc2575b7f4c6121abb17c4532 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 28 Oct 2013 15:49:48 +0100 Subject: [PATCH 47/87] Update LockingTest.java --- src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index 69ee0d3f7..4351a7c47 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -66,7 +66,7 @@ public class LockingTest extends AbstractPersistenceTest { properties.setProperty(PersistenceConstants.PROP_LOCK_TIME_MILLIS, Long.toString(500L)); setup(properties); - this.waitForWorkersTime = LockableObject.getLockTime() + (long) ((double) this.getWaitForWorkersTime() * .2); + this.waitForWorkersTime = LockableObject.getLockTime() + this.getWaitForWorkersTime() + 300L; } @Test From a5914793791347ba44c733d80c64cae7477daab9 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 28 Oct 2013 18:56:51 +0100 Subject: [PATCH 48/87] [Minor] cleaned up .gitignore --- .gitignore | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/.gitignore b/.gitignore index 3487fb9f8..18d2ca6cd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,4 @@ -*.class - -# Maven target target/ - -# Project files -tmp/ -logs/ - -# Eclipse settings .classpath .project .settings/ - -# External libraries -lib/ From 2665aa31b6f41c8fab1fc9d5ca56336b9c60cb4c Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 14 Nov 2013 19:21:49 +0100 Subject: [PATCH 49/87] [New] implemented a TransactionResult This allows reflecting on actual changes performed by the transaction if this is needed by the caller. One use case would be to perform observer updates after a transaction was completed. --- .../xmlpers/api/ModificationResult.java | 37 ++++ .../xmlpers/api/PersistenceTransaction.java | 16 ++ .../xmlpers/api/TransactionResult.java | 194 ++++++++++++++++++ .../xmlpers/api/TransactionState.java | 8 + .../impl/DefaultPersistenceTransaction.java | 126 ++++++++++-- .../ch/eitchnet/xmlpers/test/LockingTest.java | 2 +- .../xmlpers/test/TransactionResultTest.java | 141 +++++++++++++ 7 files changed, 509 insertions(+), 15 deletions(-) create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java create mode 100644 src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java create mode 100644 src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java b/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java new file mode 100644 index 000000000..c6e947365 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java @@ -0,0 +1,37 @@ +package ch.eitchnet.xmlpers.api; + +import java.util.List; + +public class ModificationResult { + + private final String key; + private final List created; + private final List updated; + private final List deleted; + + public ModificationResult(String key, List created, List updated, List deleted) { + this.key = key; + this.created = created; + this.updated = updated; + this.deleted = deleted; + } + + public String getKey() { + return this.key; + } + + @SuppressWarnings("unchecked") + public List getCreated() { + return (List) this.created; + } + + @SuppressWarnings("unchecked") + public List getUpdated() { + return (List) this.updated; + } + + @SuppressWarnings("unchecked") + public List getDeleted() { + return (List) this.deleted; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java index 0600aa2cf..a507a5204 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java @@ -29,6 +29,22 @@ import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; */ public interface PersistenceTransaction extends AutoCloseable { + /** + * Returns the {@link TransactionResult} for this transaction + * + * @return the {@link TransactionResult} + * + * @throws IllegalStateException + * if the transaction has not yet been closed + */ + public TransactionResult getTransactionResult() throws IllegalStateException; + + /** + * @throws IllegalStateException + * if a result is already set + */ + public void setTransactionResult(TransactionResult txResult) throws IllegalStateException; + public void setCloseStrategy(TransactionCloseStrategy closeStrategy); public void autoCloseableCommit(); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java new file mode 100644 index 000000000..489b69c40 --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java @@ -0,0 +1,194 @@ +package ch.eitchnet.xmlpers.api; + +import java.util.Date; +import java.util.Map; +import java.util.Set; + +import ch.eitchnet.utils.helper.StringHelper; + +public class TransactionResult { + + private String realm; + private TransactionState state; + private Exception failCause; + + private Date startTime; + private long txDuration; + private long closeDuration; + + private Map modificationByKey; + + /** + * @return the realm + */ + public String getRealm() { + return this.realm; + } + + /** + * @param realm + * the realm to set + */ + public void setRealm(String realm) { + this.realm = realm; + } + + /** + * @return the state + */ + public TransactionState getState() { + return this.state; + } + + /** + * @param state + * the state to set + */ + public void setState(TransactionState state) { + this.state = state; + } + + /** + * @return the failCause + */ + public Exception getFailCause() { + return this.failCause; + } + + /** + * @param failCause + * the failCause to set + */ + public void setFailCause(Exception failCause) { + this.failCause = failCause; + } + + /** + * @return the startTime + */ + public Date getStartTime() { + return this.startTime; + } + + /** + * @param startTime + * the startTime to set + */ + public void setStartTime(Date startTime) { + this.startTime = startTime; + } + + /** + * @return the txDuration + */ + public long getTxDuration() { + return this.txDuration; + } + + /** + * @param txDuration + * the txDuration to set + */ + public void setTxDuration(long txDuration) { + this.txDuration = txDuration; + } + + /** + * @return the closeDuration + */ + public long getCloseDuration() { + return this.closeDuration; + } + + /** + * @param closeDuration + * the closeDuration to set + */ + public void setCloseDuration(long closeDuration) { + this.closeDuration = closeDuration; + } + + /** + * @return the modificationByKey + */ + public Map getModificationByKey() { + return this.modificationByKey; + } + + /** + * @param modificationByKey + * the modificationByKey to set + */ + public void setModificationByKey(Map modificationByKey) { + this.modificationByKey = modificationByKey; + } + + /** + * @return + */ + public Set getKeys() { + return this.modificationByKey.keySet(); + } + + /** + * @param key + * @return + */ + public ModificationResult getModificationResult(String key) { + return this.modificationByKey.get(key); + } + + @SuppressWarnings("nls") + public String getLogMessage() { + + int nrOfObjects = 0; + for (ModificationResult result : this.modificationByKey.values()) { + nrOfObjects += result.getCreated().size(); + nrOfObjects += result.getUpdated().size(); + nrOfObjects += result.getDeleted().size(); + } + + StringBuilder sb = new StringBuilder(); + switch (this.state) { + case OPEN: + sb.append("TX is still open after "); + break; + case COMMITTED: + sb.append("TX was completed after "); + break; + case ROLLED_BACK: + sb.append("TX was rolled back after "); + break; + case FAILED: + sb.append("TX has failed after "); + break; + default: + sb.append("TX is in unhandled state "); + sb.append(this.state); + sb.append(" after "); + } + + sb.append(StringHelper.formatNanoDuration(this.txDuration)); + sb.append(" with close operation taking "); + sb.append(StringHelper.formatNanoDuration(this.closeDuration)); + sb.append(". "); + sb.append(nrOfObjects); + sb.append(" objects in "); + sb.append(this.modificationByKey.size()); + sb.append(" types were modified."); + + return sb.toString(); + } + + /** + * Clears all fields of this result, allowing it to be reused + */ + public void clear() { + this.realm = null; + this.state = null; + this.failCause = null; + this.startTime = null; + this.txDuration = 0L; + this.closeDuration = 0L; + } +} diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java new file mode 100644 index 000000000..15b6a3ced --- /dev/null +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java @@ -0,0 +1,8 @@ +package ch.eitchnet.xmlpers.api; + +public enum TransactionState { + OPEN, // + COMMITTED, // + ROLLED_BACK, // + FAILED; +} diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index 225085423..c74ce27d1 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -22,7 +22,11 @@ package ch.eitchnet.xmlpers.impl; import java.text.MessageFormat; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Set; import org.slf4j.Logger; @@ -33,11 +37,14 @@ import ch.eitchnet.utils.objectfilter.ObjectFilter; import ch.eitchnet.xmlpers.api.FileDao; import ch.eitchnet.xmlpers.api.IoMode; import ch.eitchnet.xmlpers.api.MetadataDao; +import ch.eitchnet.xmlpers.api.ModificationResult; import ch.eitchnet.xmlpers.api.ObjectDao; import ch.eitchnet.xmlpers.api.PersistenceContext; import ch.eitchnet.xmlpers.api.PersistenceRealm; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.api.TransactionCloseStrategy; +import ch.eitchnet.xmlpers.api.TransactionResult; +import ch.eitchnet.xmlpers.api.TransactionState; import ch.eitchnet.xmlpers.api.XmlPersistenceException; import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; @@ -57,15 +64,18 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { private final MetadataDao metadataDao; private FileDao fileDao; - - private boolean committed; - private boolean closed; - private IoMode ioMode; private TransactionCloseStrategy closeStrategy; + private TransactionState state; + private long startTime; + private Date startTimeDate; + private TransactionResult txResult; + public DefaultPersistenceTransaction(DefaultPersistenceRealm realm, boolean verbose) { + this.startTime = System.nanoTime(); + this.startTimeDate = new Date(); this.realm = realm; this.verbose = verbose; this.objectFilter = new ObjectFilter(); @@ -74,6 +84,25 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { this.metadataDao = new MetadataDao(realm.getPathBuilder(), this, verbose); this.closeStrategy = TransactionCloseStrategy.COMMIT; + this.state = TransactionState.OPEN; + } + + @Override + public void setTransactionResult(TransactionResult txResult) throws IllegalStateException { + if (this.txResult != null) { + String msg = "The transaction already has a result set!"; //$NON-NLS-1$ + throw new IllegalStateException(msg); + } + this.txResult = txResult; + } + + @Override + public TransactionResult getTransactionResult() throws IllegalStateException { + if (isOpen()) { + String msg = "The transaction is still open thus has no result yet! Either commit or rollback before calling this method"; //$NON-NLS-1$ + throw new IllegalStateException(msg); + } + return this.txResult; } @Override @@ -108,13 +137,26 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { @Override public void autoCloseableRollback() { - if (this.committed) + long start = System.nanoTime(); + if (this.state == TransactionState.COMMITTED) throw new IllegalStateException("Transaction has already been committed!"); //$NON-NLS-1$ - if (!this.closed) { + if (this.state != TransactionState.ROLLED_BACK) { unlockObjectRefs(); - this.closed = true; + this.state = TransactionState.ROLLED_BACK; this.objectFilter.clearCache(); + + long end = System.nanoTime(); + long txDuration = end - this.startTime; + long closeDuration = end - start; + + this.txResult.clear(); + this.txResult.setState(this.state); + this.txResult.setStartTime(this.startTimeDate); + this.txResult.setTxDuration(txDuration); + this.txResult.setCloseDuration(closeDuration); + this.txResult.setRealm(this.realm.getRealmName()); + this.txResult.setModificationByKey(Collections. emptyMap()); } } @@ -131,6 +173,12 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { } Set keySet = this.objectFilter.keySet(); + Map modifications; + if (this.txResult == null) + modifications = null; + else + modifications = new HashMap<>(keySet.size()); + for (String key : keySet) { List removed = this.objectFilter.getRemoved(key); @@ -177,23 +225,73 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { this.fileDao.performCreate(ctx); } } + + if (modifications != null) { + ModificationResult result = new ModificationResult(key, added, updated, removed); + modifications.put(key, result); + } } - long end = System.nanoTime(); - logger.info("TX completed in " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ + if (this.txResult != null) { + this.txResult.clear(); + this.txResult.setState(TransactionState.COMMITTED); + this.txResult.setModificationByKey(modifications); + } } catch (Exception e) { - long end = System.nanoTime(); - logger.info("TX failed after " + StringHelper.formatNanoDuration(end - start)); //$NON-NLS-1$ + if (this.txResult == null) { - throw e; + long end = System.nanoTime(); + long txDuration = end - this.startTime; + long closeDuration = end - start; + + StringBuilder sb = new StringBuilder(); + sb.append("TX has failed after "); //$NON-NLS-1$ + sb.append(StringHelper.formatNanoDuration(txDuration)); + sb.append(" with close operation taking "); //$NON-NLS-1$ + sb.append(StringHelper.formatNanoDuration(closeDuration)); + logger.info(sb.toString()); + + throw e; + } + + this.txResult.clear(); + this.txResult.setState(TransactionState.FAILED); + this.txResult.setModificationByKey(Collections. emptyMap()); } finally { + // clean up unlockObjectRefs(); this.objectFilter.clearCache(); - this.committed = true; + } + + long end = System.nanoTime(); + long txDuration = end - this.startTime; + long closeDuration = end - start; + + if (this.txResult == null) { + + StringBuilder sb = new StringBuilder(); + sb.append("TX was completed after "); //$NON-NLS-1$ + sb.append(StringHelper.formatNanoDuration(txDuration)); + sb.append(" with close operation taking "); //$NON-NLS-1$ + sb.append(StringHelper.formatNanoDuration(closeDuration)); + logger.info(sb.toString()); + + } else { + + this.txResult.setStartTime(this.startTimeDate); + this.txResult.setTxDuration(txDuration); + this.txResult.setCloseDuration(closeDuration); + this.txResult.setRealm(this.realm.getRealmName()); + + if (this.txResult.getState() == TransactionState.FAILED) { + String msg = "Failed to commit TX due to underlying exception: {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, this.txResult.getFailCause().getMessage()); + throw new XmlPersistenceException(msg, this.txResult.getFailCause()); + } } } @@ -207,7 +305,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { @Override public boolean isOpen() { - return !this.closed && !this.committed; + return this.state == TransactionState.OPEN; } @Override diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index 4351a7c47..61b366b5f 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -95,7 +95,7 @@ public class LockingTest extends AbstractPersistenceTest { String resourceId = "createWorkerRes"; //$NON-NLS-1$ for (int i = 0; i < 5; i++) { - String workerName = resourceId + "_" + i; + String workerName = resourceId + "_" + i; //$NON-NLS-1$ CreateResourceWorker worker = new CreateResourceWorker(workerName, resourceId); worker.start(); workers.add(worker); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java new file mode 100644 index 000000000..8aa381dc7 --- /dev/null +++ b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2012, Robert von Burg + * + * All rights reserved. + * + * This file is part of the XXX. + * + * XXX is free software: you can redistribute + * it and/or modify it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the License, + * or (at your option) any later version. + * + * XXX is distributed in the hope that it will + * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with XXX. If not, see + * . + */ +package ch.eitchnet.xmlpers.test; + +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.RES_ID; +import static ch.eitchnet.xmlpers.test.model.ModelBuilder.createResource; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import ch.eitchnet.xmlpers.api.IoMode; +import ch.eitchnet.xmlpers.api.ModificationResult; +import ch.eitchnet.xmlpers.api.ObjectDao; +import ch.eitchnet.xmlpers.api.PersistenceConstants; +import ch.eitchnet.xmlpers.api.PersistenceTransaction; +import ch.eitchnet.xmlpers.api.TransactionResult; +import ch.eitchnet.xmlpers.test.model.Book; +import ch.eitchnet.xmlpers.test.model.Resource; + +/** + * @author Robert von Burg + * + */ +public class TransactionResultTest extends AbstractPersistenceTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String BASEPATH = "target/db/TxResultTest/"; //$NON-NLS-1$ + + @Before + public void setup() { + cleanPath(BASEPATH); + Properties properties = new Properties(); + properties.setProperty(PersistenceConstants.PROP_BASEPATH, BASEPATH); + setup(properties); + } + + private PersistenceTransaction freshTx() { + PersistenceTransaction tx = this.persistenceManager.openTx(); + tx.setIoMode(IoMode.SAX); + return tx; + } + + @Test + public void testWithTxResult() { + + TransactionResult txResult = new TransactionResult(); + performChanges(txResult); + String logMessage = txResult.getLogMessage(); + logger.info(logMessage); + assertThat(logMessage, containsString("TX was completed after")); //$NON-NLS-1$ + assertThat(logMessage, containsString("30 objects in 2 types were modified")); //$NON-NLS-1$ + assertThat(txResult.getKeys(), containsInAnyOrder("Resource", "Book")); //$NON-NLS-1$ //$NON-NLS-2$ + + ModificationResult resourceModificationResult = txResult.getModificationResult("Resource"); //$NON-NLS-1$ + assertEquals(20, resourceModificationResult.getCreated().size()); + assertEquals(0, resourceModificationResult.getUpdated().size()); + assertEquals(0, resourceModificationResult.getDeleted().size()); + + ModificationResult bookModificationResult = txResult.getModificationResult("Book"); //$NON-NLS-1$ + assertEquals(10, bookModificationResult.getCreated().size()); + assertEquals(0, bookModificationResult.getUpdated().size()); + assertEquals(0, bookModificationResult.getDeleted().size()); + } + + @Test + public void testWithoutTxResult() { + performChanges(null); + } + + private void performChanges(TransactionResult txResult) { + + // create a list of resources + List resources = new ArrayList<>(10); + int i = 0; + for (; i < 10; i++) { + String id = RES_ID + "_" + i; //$NON-NLS-1$ + String name = "Tx Result Test 1 Object. " + i; //$NON-NLS-1$ + String type = "testTxResult1"; //$NON-NLS-1$ + + Resource resource = createResource(id, name, type); + resources.add(resource); + } + for (; i < 20; i++) { + String id = RES_ID + "_" + i; //$NON-NLS-1$ + String name = "Tx Result Test 2 Object. " + i; //$NON-NLS-1$ + String type = "testTxResult2"; //$NON-NLS-1$ + + Resource resource = createResource(id, name, type); + resources.add(resource); + } + + // create a list of books + List books = new ArrayList<>(10); + i = 0; + for (; i < 10; i++) { + String title = "Tx Result Test Book " + i; //$NON-NLS-1$ + Book book = new Book((long) i, title, "Douglas Adams", "Apress", Math.random() * i); //$NON-NLS-1$ //$NON-NLS-2$ + books.add(book); + } + + // save all + try (PersistenceTransaction tx = freshTx();) { + tx.setTransactionResult(txResult); + ObjectDao objectDao = tx.getObjectDao(); + objectDao.addAll(resources); + objectDao.addAll(books); + resources.clear(); + } + } +} From 23d8a1e0ceacd35b9dbe72539435ddd0bd83218b Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 14 Nov 2013 21:29:45 +0100 Subject: [PATCH 50/87] [New] implemented a TransactionResult This allows reflecting on actual changes performed by the transaction if this is needed by the caller. One use case would be to perform observer updates after a transaction was completed. --- .../java/ch/eitchnet/xmlpers/api/ModificationResult.java | 8 ++++++++ .../java/ch/eitchnet/xmlpers/api/TransactionResult.java | 7 ------- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java b/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java index c6e947365..a67ad0b65 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java @@ -1,5 +1,6 @@ package ch.eitchnet.xmlpers.api; +import java.util.ArrayList; import java.util.List; public class ModificationResult { @@ -9,6 +10,13 @@ public class ModificationResult { private final List updated; private final List deleted; + public ModificationResult(String key) { + this.key = key; + this.created = new ArrayList<>(); + this.updated = new ArrayList<>(); + this.deleted = new ArrayList<>(); + } + public ModificationResult(String key, List created, List updated, List deleted) { this.key = key; this.created = created; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java index 489b69c40..02dc986cf 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java @@ -108,13 +108,6 @@ public class TransactionResult { this.closeDuration = closeDuration; } - /** - * @return the modificationByKey - */ - public Map getModificationByKey() { - return this.modificationByKey; - } - /** * @param modificationByKey * the modificationByKey to set From f3a9f55007dbbfafd5ea0a1cc33b01b69dcf5e3f Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 15 Dec 2013 12:29:05 +0100 Subject: [PATCH 51/87] [Minor] Removed unused method --- src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java index af499f317..e810af235 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -24,10 +24,6 @@ public class LockableObject { public static long getLockTime() { return tryLockTime; } - - public boolean isLockedByCurrentThread() { - return this.lock.isHeldByCurrentThread(); - } /** * @see java.util.concurrent.locks.ReentrantLock#tryLock(long, TimeUnit) From 6bff06669f617b85cb3a110cfdc2ed0ea4e18acb Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 15 Dec 2013 13:38:36 +0100 Subject: [PATCH 52/87] [Project] Changed all licence references to Apache License 2.0 --- COPYING | 674 ------------------ COPYING.LESSER | 165 ----- LICENSE | 202 ++++++ .../ch/eitchnet/xmlpers/api/DomParser.java | 32 +- .../java/ch/eitchnet/xmlpers/api/FileDao.java | 32 +- .../java/ch/eitchnet/xmlpers/api/FileIo.java | 32 +- .../java/ch/eitchnet/xmlpers/api/IoMode.java | 32 +- .../ch/eitchnet/xmlpers/api/IoOperation.java | 15 + .../ch/eitchnet/xmlpers/api/MetadataDao.java | 32 +- .../xmlpers/api/ModificationResult.java | 15 + .../ch/eitchnet/xmlpers/api/ObjectDao.java | 32 +- .../eitchnet/xmlpers/api/ParserFactory.java | 32 +- .../xmlpers/api/PersistenceConstants.java | 32 +- .../xmlpers/api/PersistenceContext.java | 32 +- .../api/PersistenceContextFactory.java | 15 + .../PersistenceContextFactoryDelegator.java | 32 +- .../xmlpers/api/PersistenceManager.java | 32 +- .../xmlpers/api/PersistenceManagerLoader.java | 32 +- .../xmlpers/api/PersistenceRealm.java | 15 + .../xmlpers/api/PersistenceTransaction.java | 32 +- .../ch/eitchnet/xmlpers/api/SaxParser.java | 32 +- .../xmlpers/api/TransactionCloseStrategy.java | 15 + .../xmlpers/api/TransactionResult.java | 15 + .../xmlpers/api/TransactionState.java | 15 + .../xmlpers/api/XmlPersistenceException.java | 26 +- .../api/XmlPersistenceStreamWriter.java | 32 +- .../impl/DefaultPersistenceManager.java | 32 +- .../xmlpers/impl/DefaultPersistenceRealm.java | 15 + .../impl/DefaultPersistenceTransaction.java | 32 +- .../ch/eitchnet/xmlpers/impl/PathBuilder.java | 26 +- .../xmlpers/objref/IdOfSubTypeRef.java | 15 + .../eitchnet/xmlpers/objref/IdOfTypeRef.java | 15 + .../xmlpers/objref/LockableObject.java | 15 + .../ch/eitchnet/xmlpers/objref/ObjectRef.java | 15 + .../xmlpers/objref/ObjectReferenceCache.java | 15 + .../xmlpers/objref/RefNameCreator.java | 15 + .../ch/eitchnet/xmlpers/objref/RootRef.java | 15 + .../eitchnet/xmlpers/objref/SubTypeRef.java | 15 + .../ch/eitchnet/xmlpers/objref/TypeRef.java | 15 + .../eitchnet/xmlpers/util/AssertionUtil.java | 15 + .../ch/eitchnet/xmlpers/util/DomUtil.java | 32 +- .../xmlpers/util/FilenameUtility.java | 15 + .../xmlpers/test/AbstractPersistenceTest.java | 15 + .../ch/eitchnet/xmlpers/test/FileDaoTest.java | 32 +- .../ch/eitchnet/xmlpers/test/LockingTest.java | 32 +- .../xmlpers/test/ObjectDaoBookTest.java | 32 +- .../xmlpers/test/ObjectDaoResourceTest.java | 32 +- .../ch/eitchnet/xmlpers/test/RealmTest.java | 15 + .../xmlpers/test/TransactionResultTest.java | 32 +- .../ch/eitchnet/xmlpers/test/XmlTestMain.java | 32 +- .../xmlpers/test/impl/BookContextFactory.java | 15 + .../xmlpers/test/impl/BookDomParser.java | 32 +- .../xmlpers/test/impl/BookParserFactory.java | 32 +- .../xmlpers/test/impl/BookSaxParser.java | 32 +- .../test/impl/ResourceContextFactory.java | 15 + .../xmlpers/test/impl/ResourceDomParser.java | 32 +- .../test/impl/ResourceParserFactory.java | 32 +- .../xmlpers/test/impl/ResourceSaxParser.java | 32 +- .../xmlpers/test/impl/TestConstants.java | 32 +- .../ch/eitchnet/xmlpers/test/model/Book.java | 32 +- .../xmlpers/test/model/ModelBuilder.java | 32 +- .../xmlpers/test/model/Parameter.java | 32 +- .../eitchnet/xmlpers/test/model/Resource.java | 32 +- 63 files changed, 1024 insertions(+), 1534 deletions(-) delete mode 100644 COPYING delete mode 100644 COPYING.LESSER create mode 100644 LICENSE diff --git a/COPYING b/COPYING deleted file mode 100644 index 94a9ed024..000000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/COPYING.LESSER b/COPYING.LESSER deleted file mode 100644 index 65c5ca88a..000000000 --- a/COPYING.LESSER +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java b/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java index 1c78ff5d3..3168364cd 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java index ffd55b2e9..2a4eeb3aa 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java index 0623b1ef5..f05aac811 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java b/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java index 2b80e64b0..7e5c7ee52 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java b/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java index f60211abe..ff4fd47ed 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; public enum IoOperation { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java index c2f80da0d..5459532dd 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java b/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java index a67ad0b65..761513488 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; import java.util.ArrayList; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index aba2fc7b5..a7c27d40b 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java index 5a4d8a2ec..b1ba612cf 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java index 482389e60..40fd39738 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java index 9655d5e35..0faa8688b 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java index 2735d4aeb..3feb45dd9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; import ch.eitchnet.xmlpers.objref.ObjectRef; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java index da0a8056e..8be71335d 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java index 1d4d93fab..2790a394c 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java index 16fb0d667..ecbf0ba6d 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java index a83eeb014..4cc3e82fa 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java index a507a5204..cd3c50de8 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java index f6e660175..82ea59631 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java index 7f93e02a9..987a8ffbc 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; public enum TransactionCloseStrategy { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java index 02dc986cf..6ecddc843 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; import java.util.Date; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java index 15b6a3ced..42900e5a4 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.api; public enum TransactionState { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java index d56835be8..258118918 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java @@ -1,21 +1,17 @@ /* - * Copyright (c) 2012 + * Copyright 2013 Robert von Burg * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java index 7a758c901..182ad89c9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.api; diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java index 21f2ee04b..32eff87f7 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.impl; diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java index b072576aa..547ffc262 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.impl; import ch.eitchnet.xmlpers.api.PersistenceContextFactoryDelegator; diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index c74ce27d1..90e5fdd6a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.impl; diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java index a0f593c07..0dd3c231a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java @@ -1,21 +1,17 @@ /* - * Copyright (c) 2012 + * Copyright 2013 Robert von Burg * - * This file is part of ch.eitchnet.java.xmlpers - * - * ch.eitchnet.java.xmlpers is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * ch.eitchnet.java.xmlpers is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with ch.eitchnet.java.xmlpers. If not, see . + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.impl; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java index 7c7060e8a..bb4d206c1 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.io.File; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java index dec93808e..a110df9b1 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.io.File; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java index e810af235..caa0316ee 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.text.MessageFormat; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java index 356bdff4e..bc6810914 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.io.File; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java index 7a2a64412..67fd55562 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.util.HashMap; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java b/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java index b47e87d2a..d408c758d 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import ch.eitchnet.utils.helper.StringHelper; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java index 65640ab24..3776544c9 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.io.File; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java index fefcba6ef..f77e274ef 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.io.File; diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java index be34fff63..738a2cff7 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.objref; import java.io.File; diff --git a/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java b/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java index cdd7d24be..0a0fe4a9e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java +++ b/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.util; import java.text.MessageFormat; diff --git a/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java b/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java index f3e06cf60..fa2e9c9bf 100644 --- a/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java +++ b/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.util; diff --git a/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java b/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java index 2632531c9..bd67391b5 100644 --- a/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java +++ b/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.util; import java.text.MessageFormat; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java index 9b6086e84..eaea56e6a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.test; import java.io.File; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java index 150b18f36..c50e125cc 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index 61b366b5f..ce8574cb6 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java index 591dcc542..840d95e63 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java index 69b1f2edf..7923a8ff1 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java index aeef634ca..534e18183 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.test; import static org.junit.Assert.assertNotNull; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java index 8aa381dc7..537dc5746 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index decef2036..8ea42fa45 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java index c092b735d..ccb808507 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.api.PersistenceContext; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java index 291a09250..a07e19be8 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java index 8ca161052..9de53c54e 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java index 37acd83a0..2a9338683 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java index 977ca09f3..03d67d7fc 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java @@ -1,3 +1,18 @@ +/* + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.api.PersistenceContext; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java index 9b86472e8..f9b4ecea4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java index 002b83ad8..72787b11a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java index f3cdf82d4..7a87057f7 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java index 18ec8cafd..cfa62b831 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.impl; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java index 21318298c..536be946c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.model; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index 1f6dfc432..8d9576b40 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.model; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java index 1f6ee3b25..d3b422ec0 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.model; diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java index b647b9d7c..5567f3e47 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java @@ -1,23 +1,17 @@ /* - * Copyright (c) 2012, Robert von Burg - * - * All rights reserved. - * - * This file is part of the XXX. - * - * XXX is free software: you can redistribute - * it and/or modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the License, - * or (at your option) any later version. - * - * XXX is distributed in the hope that it will - * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with XXX. If not, see - * . + * Copyright 2013 Robert von Burg + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ package ch.eitchnet.xmlpers.test.model; From 6305bdc69fec99a60d58592e795ecffecf88e44e Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 22 Dec 2013 23:03:14 +0100 Subject: [PATCH 53/87] [Minor] caught an NPE when the Transaction fails but no cause is set --- .../eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index 90e5fdd6a..650df2614 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -283,7 +283,9 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { if (this.txResult.getState() == TransactionState.FAILED) { String msg = "Failed to commit TX due to underlying exception: {0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, this.txResult.getFailCause().getMessage()); + String causeMsg = this.txResult.getFailCause() == null ? null : this.txResult.getFailCause() + .getMessage(); + msg = MessageFormat.format(msg, causeMsg); throw new XmlPersistenceException(msg, this.txResult.getFailCause()); } } From 5820265d1ef3706514bcf72b09db4d5b9aee64b3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 23 Dec 2013 01:21:42 +0100 Subject: [PATCH 54/87] [Minor] minor code cleanup --- .../java/ch/eitchnet/xmlpers/api/TransactionResult.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java index 6ecddc843..68d05d6ec 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java @@ -16,6 +16,7 @@ package ch.eitchnet.xmlpers.api; import java.util.Date; +import java.util.HashMap; import java.util.Map; import java.util.Set; @@ -32,6 +33,11 @@ public class TransactionResult { private long closeDuration; private Map modificationByKey; + + public TransactionResult() { + this.state = TransactionState.OPEN; + this.modificationByKey = new HashMap<>(); + } /** * @return the realm From 24a62bb01dec38ce76bdd2e2261ebf321b7fcbe6 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Tue, 24 Dec 2013 01:47:11 +0100 Subject: [PATCH 55/87] [Bugfix] fixed a bug where queryTypeSet() failed on MetadataDao --- src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java index 5459532dd..fd6f117b4 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java @@ -152,10 +152,9 @@ public class MetadataDao { Set keySet = new HashSet(); File[] subTypeFiles = queryPath.listFiles(); for (File subTypeFile : subTypeFiles) { - if (subTypeFile.isFile()) { - String filename = subTypeFile.getName(); - String id = FilenameUtility.getId(filename); - keySet.add(id); + if (subTypeFile.isDirectory()) { + String type = subTypeFile.getName(); + keySet.add(type); } } From d35baa5a48c03f7a0f00cdfc08c8d0d6ed7e5455 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Tue, 24 Dec 2013 02:42:49 +0100 Subject: [PATCH 56/87] [Minor] set some loggers to debug --- .../java/ch/eitchnet/xmlpers/api/FileIo.java | 26 ++++++++++++------- .../xmlpers/objref/LockableObject.java | 6 +++-- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java index f05aac811..23f917e4f 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java @@ -95,8 +95,10 @@ public class FileIo { throw new XmlException(msg, e); } - String msg = "Wrote SAX to {0}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); + if (logger.isDebugEnabled()) { + String msg = "Wrote SAX to {0}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); + } } public void readSax(PersistenceContext ctx) { @@ -110,8 +112,10 @@ public class FileIo { DefaultHandler defaultHandler = saxParser.getDefaultHandler(); sp.parse(this.path, defaultHandler); - String msg = "SAX parsed file {0}"; //$NON-NLS-1$ - logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); + if (logger.isDebugEnabled()) { + String msg = "SAX parsed file {0}"; //$NON-NLS-1$ + logger.info(MessageFormat.format(msg, this.path.getAbsolutePath())); + } ctx.setObject(saxParser.getObject()); @@ -157,8 +161,10 @@ public class FileIo { Source xmlSource = new DOMSource(document); transformer.transform(xmlSource, result); - String msg = MessageFormat.format("Wrote DOM to {0}", this.path.getAbsolutePath()); //$NON-NLS-1$ - logger.info(msg); + if (logger.isDebugEnabled()) { + String msg = MessageFormat.format("Wrote DOM to {0}", this.path.getAbsolutePath()); //$NON-NLS-1$ + logger.info(msg); + } } catch (TransformerFactoryConfigurationError | TransformerException e) { @@ -183,9 +189,11 @@ public class FileIo { DomParser domParser = ctx.getParserFactor().getDomParser(); domParser.fromDom(document); - String msg = "DOM parsed file {0}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, this.path.getAbsolutePath()); - logger.info(msg); + if (logger.isDebugEnabled()) { + String msg = "DOM parsed file {0}"; //$NON-NLS-1$ + msg = MessageFormat.format(msg, this.path.getAbsolutePath()); + logger.info(msg); + } ctx.setObject(domParser.getObject()); diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java index caa0316ee..760b8234f 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -51,7 +51,8 @@ public class LockableObject { msg = MessageFormat.format(msg, StringHelper.formatMillisecondsDuration(tryLockTime), this.toString()); throw new XmlPersistenceException(msg); } - logger.info("locked " + this.toString()); //$NON-NLS-1$ + if (logger.isDebugEnabled()) + logger.debug("locked " + this.toString()); //$NON-NLS-1$ } catch (InterruptedException e) { throw new XmlPersistenceException("Thread interrupted: " + e.getMessage(), e); //$NON-NLS-1$ } @@ -62,6 +63,7 @@ public class LockableObject { */ public void unlock() { this.lock.unlock(); - logger.info("unlocking " + this.toString()); //$NON-NLS-1$ + if (logger.isDebugEnabled()) + logger.debug("unlocking " + this.toString()); //$NON-NLS-1$ } } From 54fd73942b166437a9925e46d72b515c8cbb3005 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 25 Dec 2013 11:56:02 +0100 Subject: [PATCH 57/87] [Minor] fixed issue where eclipse couldn't validate log4j.xml --- src/test/resources/log4j.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/test/resources/log4j.xml b/src/test/resources/log4j.xml index 2f49b0dca..f223bc5cb 100644 --- a/src/test/resources/log4j.xml +++ b/src/test/resources/log4j.xml @@ -1,5 +1,6 @@ - + From 40eec73bb197d3ab46a09a3b47156cb53cc37db0 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 10 Jan 2014 23:14:17 +0100 Subject: [PATCH 58/87] [Bugfix] fixed missing exception on transaction result on error case --- .../ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index 650df2614..7d6bc8fe4 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -253,6 +253,7 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { this.txResult.clear(); this.txResult.setState(TransactionState.FAILED); this.txResult.setModificationByKey(Collections. emptyMap()); + this.txResult.setFailCause(e); } finally { From aad2b447b96aed6525e6fdb88c081bdec3d3d68d Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 11 Jan 2014 17:35:19 +0100 Subject: [PATCH 59/87] [Minor] added some JavaDoc to TransactionResult --- .../ch/eitchnet/xmlpers/api/TransactionResult.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java index 68d05d6ec..11267944b 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java @@ -33,7 +33,7 @@ public class TransactionResult { private long closeDuration; private Map modificationByKey; - + public TransactionResult() { this.state = TransactionState.OPEN; this.modificationByKey = new HashMap<>(); @@ -70,6 +70,8 @@ public class TransactionResult { } /** + * The internal exception why the transaction failed + * * @return the failCause */ public Exception getFailCause() { @@ -85,6 +87,8 @@ public class TransactionResult { } /** + * Start time of the transaction + * * @return the startTime */ public Date getStartTime() { @@ -100,6 +104,8 @@ public class TransactionResult { } /** + * The duration the transaction was open in nanoseconds + * * @return the txDuration */ public long getTxDuration() { @@ -115,6 +121,8 @@ public class TransactionResult { } /** + * The duration the transaction took to close in nanoseconds + * * @return the closeDuration */ public long getCloseDuration() { From e6e184c16cdfbd2fb76f6d2622a490dfe11b590d Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 23 Jan 2014 22:52:28 +0100 Subject: [PATCH 60/87] [Project] added Jenkins build badge to README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 2496f583d..ec5c13c8c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,8 @@ ch.eitchnet.java.xmlpers ======================== + +[![Build Status](http://jenkins.eitchnet.ch/buildStatus/icon?job=ch.eitchnet.xmlpers)](http://jenkins.eitchnet.ch/view/ch.eitchnet/job/ch.eitchnet.xmlpers/) + Generic Java XML persistence layer. Implemented to be light-weight and simple to use Dependencies From da45d3238e842e57bf5eab4570ae9e5365c13f11 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 31 Jan 2014 18:59:34 +0100 Subject: [PATCH 61/87] [Minor] switched to StringHelper.isNotEmpty() --- src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java b/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java index 0dd3c231a..8b0d582a3 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java @@ -80,15 +80,15 @@ public class PathBuilder { String getPathAsString(String type, String subType, String id) { StringBuilder sb = new StringBuilder(this.basePath); - if (!StringHelper.isEmpty(type)) { + if (StringHelper.isNotEmpty(type)) { sb.append(File.separatorChar); sb.append(type); } - if (!StringHelper.isEmpty(subType)) { + if (StringHelper.isNotEmpty(subType)) { sb.append(File.separatorChar); sb.append(subType); } - if (!StringHelper.isEmpty(id)) { + if (StringHelper.isNotEmpty(id)) { sb.append(File.separatorChar); sb.append(getFilename(id)); } From 2647115f6f5e9bf39b44bf8284d7295d1186c232 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 19 Feb 2014 00:07:55 +0100 Subject: [PATCH 62/87] [Minor] added realm name to log message on TX commit --- .../ch/eitchnet/xmlpers/api/TransactionResult.java | 12 +++++++----- .../eitchnet/xmlpers/test/TransactionResultTest.java | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java index 11267944b..dbd72c324 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java @@ -171,21 +171,23 @@ public class TransactionResult { } StringBuilder sb = new StringBuilder(); + sb.append("TX for realm "); + sb.append(getRealm()); switch (this.state) { case OPEN: - sb.append("TX is still open after "); + sb.append(" is still open after "); break; case COMMITTED: - sb.append("TX was completed after "); + sb.append(" was completed after "); break; case ROLLED_BACK: - sb.append("TX was rolled back after "); + sb.append(" was rolled back after "); break; case FAILED: - sb.append("TX has failed after "); + sb.append(" has failed after "); break; default: - sb.append("TX is in unhandled state "); + sb.append(" is in unhandled state "); sb.append(this.state); sb.append(" after "); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java index 537dc5746..576cc1486 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java @@ -72,7 +72,7 @@ public class TransactionResultTest extends AbstractPersistenceTest { performChanges(txResult); String logMessage = txResult.getLogMessage(); logger.info(logMessage); - assertThat(logMessage, containsString("TX was completed after")); //$NON-NLS-1$ + assertThat(logMessage, containsString("TX for realm defaultRealm was completed after")); //$NON-NLS-1$ assertThat(logMessage, containsString("30 objects in 2 types were modified")); //$NON-NLS-1$ assertThat(txResult.getKeys(), containsInAnyOrder("Resource", "Book")); //$NON-NLS-1$ //$NON-NLS-2$ From 44613163cb2feab14b418619e4af8d09cebf0272 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 14 Mar 2014 14:36:16 +0100 Subject: [PATCH 63/87] [Project] fixed urls of projects --- pom.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pom.xml b/pom.xml index cb6be517c..5bd34d729 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ jar 0.3.0-SNAPSHOT ch.eitchnet.xmlpers - https://github.com/eitch/ch.eitchnet.xmlpers + https://github.com/eitchnet/ch.eitchnet.xmlpers UTF-8 @@ -25,13 +25,13 @@ Github Issues - https://github.com/eitch/ch.eitchnet.xmlpers/issues + https://github.com/eitchnet/ch.eitchnet.xmlpers/issues - scm:git:https://github.com/eitch/ch.eitchnet.xmlpers.git - scm:git:git@github.com:eitch/ch.eitchnet.xmlpers.git - https://github.com/eitch/ch.eitchnet.xmlpers + scm:git:https://github.com/eitchnet/ch.eitchnet.xmlpers.git + scm:git:git@github.com:eitchnet/ch.eitchnet.xmlpers.git + https://github.com/eitchnet/ch.eitchnet.xmlpers From 2adf809515f0219f9a5f3ad838ab7a3547813d72 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 27 Mar 2014 18:50:14 +0100 Subject: [PATCH 64/87] [Minor] code formatting --- .../ch/eitchnet/xmlpers/test/model/Resource.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java index 5567f3e47..a9dd1cca7 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java @@ -28,7 +28,7 @@ public class Resource { private Map parameters = new HashMap(); /** - * + * */ public Resource() { // empty constructor @@ -73,8 +73,7 @@ public class Resource { } /** - * @param id - * the id to set + * @param id the id to set */ public void setId(String id) { this.id = id; @@ -88,8 +87,7 @@ public class Resource { } /** - * @param name - * the name to set + * @param name the name to set */ public void setName(String name) { this.name = name; @@ -103,8 +101,7 @@ public class Resource { } /** - * @param type - * the type to set + * @param type the type to set */ public void setType(String type) { this.type = type; @@ -121,4 +118,4 @@ public class Resource { public Parameter getParameterBy(String id) { return this.parameters.get(id); } -} \ No newline at end of file +} From ec5ff685a31e946a1d7ae42eab94b35e2686a193 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 31 Jul 2014 16:09:10 +0200 Subject: [PATCH 65/87] [New] Added new ObjectDao.removeAllBy() methods --- .../ch/eitchnet/xmlpers/api/ObjectDao.java | 69 ++++++++++++++++++- .../eitchnet/xmlpers/util/AssertionUtil.java | 2 +- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index a7c27d40b..9f5ab34cb 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -22,11 +22,14 @@ import static ch.eitchnet.xmlpers.util.AssertionUtil.assertNotNull; import static ch.eitchnet.xmlpers.util.AssertionUtil.assertObjectRead; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; import java.util.Set; import ch.eitchnet.utils.objectfilter.ObjectFilter; import ch.eitchnet.xmlpers.objref.ObjectRef; +import ch.eitchnet.xmlpers.objref.SubTypeRef; +import ch.eitchnet.xmlpers.objref.TypeRef; /** * @author Robert von Burg @@ -112,6 +115,68 @@ public class ObjectDao { } } + public long removeAllBy(TypeRef typeRef) { + assertNotClosed(); + + long removed = 0; + + Set refs = new HashSet(); + typeRef.lock(); + refs.add(typeRef); + try { + + Set types = tx.getMetadataDao().queryTypeSet(typeRef); + for (String type : types) { + ObjectRef childTypeRef = typeRef.getChildTypeRef(tx, type); + childTypeRef.lock(); + refs.add(childTypeRef); + + Set ids = queryKeySet(childTypeRef); + for (String id : ids) { + + ObjectRef idRef = childTypeRef.getChildIdRef(tx, id); + + PersistenceContext ctx = createCtx(idRef); + ctx.getObjectRef().lock(); + this.objectFilter.remove(ctx.getObjectRef().getType(), ctx); + removed++; + } + } + } finally { + for (ObjectRef ref : refs) { + ref.unlock(); + } + } + + return removed; + } + + public long removeAllBy(SubTypeRef subTypeRef) { + assertNotClosed(); + assertIsNotRootRef(subTypeRef); + assertIsNotIdRef(subTypeRef); + + long removed = 0; + + subTypeRef.lock(); + try { + Set ids = queryKeySet(subTypeRef); + for (String id : ids) { + + ObjectRef idRef = subTypeRef.getChildIdRef(tx, id); + + PersistenceContext ctx = createCtx(idRef); + ctx.getObjectRef().lock(); + this.objectFilter.remove(ctx.getObjectRef().getType(), ctx); + removed++; + } + } finally { + subTypeRef.unlock(); + } + + return removed; + } + public void removeById(ObjectRef objectRef) { assertNotClosed(); assertIsIdRef(objectRef); @@ -192,7 +257,7 @@ public class ObjectDao { } } - public Set queryKeySet(ObjectRef parentRef) { + public Set queryKeySet(ObjectRef parentRef) { assertNotClosed(); assertIsNotIdRef(parentRef); @@ -206,7 +271,7 @@ public class ObjectDao { } } - public long querySize(ObjectRef parentRef) { + public long querySize(ObjectRef parentRef) { assertNotClosed(); assertIsNotIdRef(parentRef); diff --git a/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java b/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java index 0a0fe4a9e..6a3c9535a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java +++ b/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java @@ -53,7 +53,7 @@ public class AssertionUtil { } public static void assertIsNotRootRef(ObjectRef objectRef) { - if (!objectRef.isRoot()) { + if (objectRef.isRoot()) { String msg = "RootRef not expected {0}"; //$NON-NLS-1$ msg = MessageFormat.format(msg, objectRef.getName()); throw new IllegalArgumentException(msg); From 8b1af0667b313bfb2396f0c3eef5049e3fb06631 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 4 Aug 2014 11:47:01 +0200 Subject: [PATCH 66/87] [New] Added method ObjectDao.hasElement() --- .../java/ch/eitchnet/xmlpers/api/FileDao.java | 7 +++++ .../ch/eitchnet/xmlpers/api/ObjectDao.java | 30 ++++++++++++------- .../ch/eitchnet/xmlpers/test/LockingTest.java | 1 + 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java index 2a4eeb3aa..8a7e54af4 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java @@ -46,6 +46,13 @@ public class FileDao { } } + public boolean exists(PersistenceContext ctx) { + ObjectRef objectRef = ctx.getObjectRef(); + assertIsIdRef(IoOperation.READ, objectRef); + File path = objectRef.getPath(this.pathBuilder); + return path.exists(); + } + public void performCreate(PersistenceContext ctx) { ObjectRef objectRef = ctx.getObjectRef(); assertIsIdRef(IoOperation.CREATE, objectRef); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index 9f5ab34cb..c2a492ed5 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -125,16 +125,16 @@ public class ObjectDao { refs.add(typeRef); try { - Set types = tx.getMetadataDao().queryTypeSet(typeRef); + Set types = this.tx.getMetadataDao().queryTypeSet(typeRef); for (String type : types) { - ObjectRef childTypeRef = typeRef.getChildTypeRef(tx, type); + ObjectRef childTypeRef = typeRef.getChildTypeRef(this.tx, type); childTypeRef.lock(); refs.add(childTypeRef); Set ids = queryKeySet(childTypeRef); for (String id : ids) { - ObjectRef idRef = childTypeRef.getChildIdRef(tx, id); + ObjectRef idRef = childTypeRef.getChildIdRef(this.tx, id); PersistenceContext ctx = createCtx(idRef); ctx.getObjectRef().lock(); @@ -163,7 +163,7 @@ public class ObjectDao { Set ids = queryKeySet(subTypeRef); for (String id : ids) { - ObjectRef idRef = subTypeRef.getChildIdRef(tx, id); + ObjectRef idRef = subTypeRef.getChildIdRef(this.tx, id); PersistenceContext ctx = createCtx(idRef); ctx.getObjectRef().lock(); @@ -206,6 +206,19 @@ public class ObjectDao { } } + public boolean hasElement(ObjectRef objectRef) { + assertNotClosed(); + assertIsIdRef(objectRef); + + objectRef.lock(); + try { + PersistenceContext ctx = objectRef. createPersistenceContext(this.tx); + return this.fileDao.exists(ctx); + } finally { + objectRef.unlock(); + } + } + public T queryById(ObjectRef objectRef) { assertNotClosed(); assertIsIdRef(objectRef); @@ -213,13 +226,8 @@ public class ObjectDao { objectRef.lock(); try { PersistenceContext ctx = objectRef. createPersistenceContext(this.tx); - ctx.getObjectRef().lock(); - try { - this.fileDao.performRead(ctx); - return ctx.getObject(); - } finally { - ctx.getObjectRef().unlock(); - } + this.fileDao.performRead(ctx); + return ctx.getObject(); } finally { objectRef.unlock(); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index ce8574cb6..473be20d4 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -165,6 +165,7 @@ public class LockingTest extends AbstractPersistenceTest { this.resourceId = resourceId; } + @Override public void run() { logger.info("Waiting for ok to work..."); //$NON-NLS-1$ From d236d8589bb9a087a26e24c88e4ca7f7a8b0fa62 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 14 Aug 2014 16:23:30 +0200 Subject: [PATCH 67/87] [Project] using parent version 1.1.0-SNAPSHOT --- pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5bd34d729..b90e5dea4 100644 --- a/pom.xml +++ b/pom.xml @@ -5,13 +5,13 @@ ch.eitchnet ch.eitchnet.parent - 0.1.0-SNAPSHOT + 1.1.0-SNAPSHOT ../ch.eitchnet.parent/pom.xml ch.eitchnet.xmlpers - jar 0.3.0-SNAPSHOT + jar ch.eitchnet.xmlpers https://github.com/eitchnet/ch.eitchnet.xmlpers @@ -32,6 +32,7 @@ scm:git:https://github.com/eitchnet/ch.eitchnet.xmlpers.git scm:git:git@github.com:eitchnet/ch.eitchnet.xmlpers.git https://github.com/eitchnet/ch.eitchnet.xmlpers + HEAD From b38c57e424c049fb6d7bdcd446d78d6fc75b7b05 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 17 Aug 2014 14:02:00 +0200 Subject: [PATCH 68/87] [Minor] renamed test classes --- .../xmlpers/test/AbstractPersistenceTest.java | 8 ++--- .../ch/eitchnet/xmlpers/test/FileDaoTest.java | 10 +++--- .../ch/eitchnet/xmlpers/test/LockingTest.java | 8 ++--- .../xmlpers/test/ObjectDaoResourceTest.java | 28 +++++++-------- .../ch/eitchnet/xmlpers/test/RealmTest.java | 16 ++++----- .../xmlpers/test/TransactionResultTest.java | 8 ++--- .../ch/eitchnet/xmlpers/test/XmlTestMain.java | 36 +++++++++---------- ...actory.java => MyModelContextFactory.java} | 12 +++---- ...ceDomParser.java => MyModelDomParser.java} | 18 +++++----- ...Factory.java => MyModelParserFactory.java} | 12 +++---- ...ceSaxParser.java => MyModelSaxParser.java} | 18 +++++----- .../xmlpers/test/model/ModelBuilder.java | 20 +++++------ .../model/{Resource.java => MyModel.java} | 14 ++++---- .../{Parameter.java => MyParameter.java} | 6 ++-- 14 files changed, 107 insertions(+), 107 deletions(-) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{ResourceContextFactory.java => MyModelContextFactory.java} (72%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{ResourceDomParser.java => MyModelDomParser.java} (85%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{ResourceParserFactory.java => MyModelParserFactory.java} (74%) rename src/test/java/ch/eitchnet/xmlpers/test/impl/{ResourceSaxParser.java => MyModelSaxParser.java} (84%) rename src/test/java/ch/eitchnet/xmlpers/test/model/{Resource.java => MyModel.java} (86%) rename src/test/java/ch/eitchnet/xmlpers/test/model/{Parameter.java => MyParameter.java} (94%) diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java index eaea56e6a..312a9f19e 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java @@ -27,10 +27,10 @@ import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceManager; import ch.eitchnet.xmlpers.api.PersistenceManagerLoader; import ch.eitchnet.xmlpers.test.impl.BookContextFactory; -import ch.eitchnet.xmlpers.test.impl.ResourceContextFactory; +import ch.eitchnet.xmlpers.test.impl.MyModelContextFactory; import ch.eitchnet.xmlpers.test.impl.TestConstants; import ch.eitchnet.xmlpers.test.model.Book; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; public abstract class AbstractPersistenceTest { @@ -67,8 +67,8 @@ public abstract class AbstractPersistenceTest { protected void setup(Properties properties) { properties.setProperty(PersistenceConstants.PROP_VERBOSE, "true"); //$NON-NLS-1$ this.persistenceManager = PersistenceManagerLoader.load(properties); - this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Resource.class, - TestConstants.TYPE_RES, new ResourceContextFactory()); + this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(MyModel.class, + TestConstants.TYPE_RES, new MyModelContextFactory()); this.persistenceManager.getCtxFactory().registerPersistenceContextFactory(Book.class, TestConstants.TYPE_BOOK, new BookContextFactory()); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java index c50e125cc..31f19d4d1 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java @@ -38,7 +38,7 @@ import ch.eitchnet.xmlpers.impl.DefaultPersistenceRealm; import ch.eitchnet.xmlpers.impl.DefaultPersistenceTransaction; import ch.eitchnet.xmlpers.impl.PathBuilder; import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; /** * @author Robert von Burg @@ -90,12 +90,12 @@ public class FileDaoTest extends AbstractPersistenceTest { private void testCrud(PersistenceContextFactoryDelegator ctxFactoryDelegator, FileDao fileDao) { - Resource resource = createResource(); + MyModel resource = createResource(); assertResource(resource); - Class classType = resource.getClass(); - PersistenceContextFactory ctxFactory = ctxFactoryDelegator.getCtxFactory(classType); + Class classType = resource.getClass(); + PersistenceContextFactory ctxFactory = ctxFactoryDelegator.getCtxFactory(classType); ObjectReferenceCache objectRefCache = this.realm.getObjectRefCache(); - PersistenceContext context = ctxFactory.createCtx(objectRefCache, resource); + PersistenceContext context = ctxFactory.createCtx(objectRefCache, resource); context.setObject(resource); fileDao.performCreate(context); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index 473be20d4..68de2d5a9 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -35,7 +35,7 @@ import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; import ch.eitchnet.xmlpers.objref.LockableObject; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; /** * @author Robert von Burg @@ -117,7 +117,7 @@ public class LockingTest extends AbstractPersistenceTest { // create resource which is to be updated try (PersistenceTransaction tx = this.persistenceManager.openTx()) { - Resource resource = createResource(resourceId); + MyModel resource = createResource(resourceId); tx.getObjectDao().add(resource); } @@ -208,7 +208,7 @@ public class LockingTest extends AbstractPersistenceTest { @Override protected void doWork(PersistenceTransaction tx) { - Resource resource = createResource(this.resourceId); + MyModel resource = createResource(this.resourceId); tx.getObjectDao().add(resource); } } @@ -223,7 +223,7 @@ public class LockingTest extends AbstractPersistenceTest { protected void doWork(PersistenceTransaction tx) { IdOfSubTypeRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(TYPE_RES, RES_TYPE, this.resourceId); - Resource resource = tx.getObjectDao().queryById(objectRef); + MyModel resource = tx.getObjectDao().queryById(objectRef); assertNotNull(resource); updateResource(resource); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java index 7923a8ff1..72e40c3ae 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java @@ -46,7 +46,7 @@ import ch.eitchnet.xmlpers.objref.ObjectRef; import ch.eitchnet.xmlpers.objref.SubTypeRef; import ch.eitchnet.xmlpers.test.impl.TestConstants; import ch.eitchnet.xmlpers.test.model.ModelBuilder; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; /** * @author Robert von Burg @@ -93,7 +93,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { ObjectDao objectDao; // create new resource - Resource resource = createResource(); + MyModel resource = createResource(); try (PersistenceTransaction tx = freshTx(ioMode);) { objectDao = tx.getObjectDao(); objectDao.add(resource); @@ -157,12 +157,12 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { String type = "testBulk" + ioMode.name(); //$NON-NLS-1$ // create a list of resources - List resources = new ArrayList<>(10); + List resources = new ArrayList<>(10); for (int i = 0; i < 10; i++) { String id = RES_ID + "_" + i; //$NON-NLS-1$ String name = "Bulk Test Object. " + i; //$NON-NLS-1$ - Resource resource = createResource(id, name, type); + MyModel resource = createResource(id, name, type); resources.add(resource); } @@ -204,14 +204,14 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { // create a resource try (PersistenceTransaction tx = this.persistenceManager.openTx()) { - Resource resource = createResource(id, name, subType); + MyModel resource = createResource(id, name, subType); tx.getObjectDao().add(resource); } // read by id try (PersistenceTransaction tx = this.persistenceManager.openTx()) { ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(classType, subType, id); - Resource resource = tx.getObjectDao().queryById(objectRef); + MyModel resource = tx.getObjectDao().queryById(objectRef); assertNotNull("Expected to read resource by ID", resource); //$NON-NLS-1$ } @@ -224,7 +224,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { // fail to read by id try (PersistenceTransaction tx = this.persistenceManager.openTx()) { ObjectRef objectRef = tx.getObjectRefCache().getIdOfSubTypeRef(classType, subType, id); - Resource resource = tx.getObjectDao().queryById(objectRef); + MyModel resource = tx.getObjectDao().queryById(objectRef); assertNull("Expected that resource was deleted by ID, thus can not be read anymore", resource); //$NON-NLS-1$ } } @@ -239,7 +239,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { // update try (PersistenceTransaction tx = this.persistenceManager.openTx()) { - Resource resource = createResource(); + MyModel resource = createResource(); tx.getObjectDao().update(resource); } } @@ -254,7 +254,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { // delete try (PersistenceTransaction tx = this.persistenceManager.openTx()) { - Resource resource = createResource(); + MyModel resource = createResource(); tx.getObjectDao().remove(resource); } } @@ -270,7 +270,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { try (PersistenceTransaction tx = this.persistenceManager.openTx()) { String id = "shouldAllowAllOperationsInSameTx_create"; //$NON-NLS-1$ - Resource resource = createResource(id, name, subType); + MyModel resource = createResource(id, name, subType); tx.getObjectDao().add(resource); } @@ -279,7 +279,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { try (PersistenceTransaction tx = this.persistenceManager.openTx()) { String id = "shouldAllowAllOperationsInSameTx_create_modify"; //$NON-NLS-1$ - Resource resource = createResource(id, name, subType); + MyModel resource = createResource(id, name, subType); tx.getObjectDao().add(resource); tx.getObjectDao().update(resource); @@ -289,7 +289,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { try (PersistenceTransaction tx = this.persistenceManager.openTx()) { String id = "shouldAllowAllOperationsInSameTx_create_delete"; //$NON-NLS-1$ - Resource resource = createResource(id, name, subType); + MyModel resource = createResource(id, name, subType); tx.getObjectDao().add(resource); tx.getObjectDao().remove(resource); @@ -299,7 +299,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { try (PersistenceTransaction tx = this.persistenceManager.openTx()) { String id = "shouldAllowAllOperationsInSameTx_create_modify_delete"; //$NON-NLS-1$ - Resource resource = createResource(id, name, subType); + MyModel resource = createResource(id, name, subType); tx.getObjectDao().add(resource); tx.getObjectDao().update(resource); @@ -310,7 +310,7 @@ public class ObjectDaoResourceTest extends AbstractPersistenceTest { // prepare for read/modify try (PersistenceTransaction tx = this.persistenceManager.openTx()) { - Resource resource = createResource(id, name, subType); + MyModel resource = createResource(id, name, subType); tx.getObjectDao().add(resource); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java index 534e18183..d3f91e337 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java @@ -30,7 +30,7 @@ import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.objref.ObjectRef; import ch.eitchnet.xmlpers.test.impl.TestConstants; import ch.eitchnet.xmlpers.test.model.ModelBuilder; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; @SuppressWarnings("nls") public class RealmTest extends AbstractPersistenceTest { @@ -62,21 +62,21 @@ public class RealmTest extends AbstractPersistenceTest { // create in first realm try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { - Resource resource1 = ModelBuilder.createResource(id, name, type); + MyModel resource1 = ModelBuilder.createResource(id, name, type); txRealm1.getObjectDao().add(resource1); } // find in first realm try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { ObjectRef objectRef = txRealm1.getObjectRefCache().getIdOfSubTypeRef(objType, type, id); - Resource resource = txRealm1.getObjectDao().queryById(objectRef); + MyModel resource = txRealm1.getObjectDao().queryById(objectRef); assertNotNull("Resource was not found in first realm!", resource); } // fail to find in second realm try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { ObjectRef objectRef = txRealm2.getObjectRefCache().getIdOfSubTypeRef(objType, type, id); - Resource resource = txRealm2.getObjectDao().queryById(objectRef); + MyModel resource = txRealm2.getObjectDao().queryById(objectRef); assertNull("Resource was not created in second realm, thus not expected to be found there!", resource); } } @@ -92,13 +92,13 @@ public class RealmTest extends AbstractPersistenceTest { // create in first realm try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { - Resource resource1 = ModelBuilder.createResource(id, name, subType); + MyModel resource1 = ModelBuilder.createResource(id, name, subType); txRealm1.getObjectDao().add(resource1); } // create in second realm try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { - Resource resource1 = ModelBuilder.createResource(id, name, subType); + MyModel resource1 = ModelBuilder.createResource(id, name, subType); txRealm2.getObjectDao().add(resource1); } @@ -111,14 +111,14 @@ public class RealmTest extends AbstractPersistenceTest { // fail to find in second realm try (PersistenceTransaction txRealm2 = this.persistenceManager.openTx(REALM_2);) { ObjectRef objectRef = txRealm2.getObjectRefCache().getIdOfSubTypeRef(objType, subType, id); - Resource resource = txRealm2.getObjectDao().queryById(objectRef); + MyModel resource = txRealm2.getObjectDao().queryById(objectRef); assertNull("Resource was not deleted from second realm, thus not expected to be found there!", resource); } // find in first realm try (PersistenceTransaction txRealm1 = this.persistenceManager.openTx(REALM_1);) { ObjectRef objectRef = txRealm1.getObjectRefCache().getIdOfSubTypeRef(objType, subType, id); - Resource resource = txRealm1.getObjectDao().queryById(objectRef); + MyModel resource = txRealm1.getObjectDao().queryById(objectRef); assertNotNull("Resource was not found in first realm!", resource); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java index 576cc1486..8aa5e5a53 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java @@ -38,7 +38,7 @@ import ch.eitchnet.xmlpers.api.PersistenceConstants; import ch.eitchnet.xmlpers.api.PersistenceTransaction; import ch.eitchnet.xmlpers.api.TransactionResult; import ch.eitchnet.xmlpers.test.model.Book; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; /** * @author Robert von Burg @@ -95,14 +95,14 @@ public class TransactionResultTest extends AbstractPersistenceTest { private void performChanges(TransactionResult txResult) { // create a list of resources - List resources = new ArrayList<>(10); + List resources = new ArrayList<>(10); int i = 0; for (; i < 10; i++) { String id = RES_ID + "_" + i; //$NON-NLS-1$ String name = "Tx Result Test 1 Object. " + i; //$NON-NLS-1$ String type = "testTxResult1"; //$NON-NLS-1$ - Resource resource = createResource(id, name, type); + MyModel resource = createResource(id, name, type); resources.add(resource); } for (; i < 20; i++) { @@ -110,7 +110,7 @@ public class TransactionResultTest extends AbstractPersistenceTest { String name = "Tx Result Test 2 Object. " + i; //$NON-NLS-1$ String type = "testTxResult2"; //$NON-NLS-1$ - Resource resource = createResource(id, name, type); + MyModel resource = createResource(id, name, type); resources.add(resource); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index 8ea42fa45..f05e83215 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -47,8 +47,8 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.XmlHelper; import ch.eitchnet.xmlpers.test.model.ModelBuilder; -import ch.eitchnet.xmlpers.test.model.Parameter; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyParameter; +import ch.eitchnet.xmlpers.test.model.MyModel; /** * @author Robert von Burg @@ -59,7 +59,7 @@ public class XmlTestMain { private static final Logger logger = LoggerFactory.getLogger(XmlTestMain.class); - private static Resource res; + private static MyModel res; public static void main(String[] args) throws Exception { @@ -70,7 +70,7 @@ public class XmlTestMain { writeSax(res); writeDom(res); - List resoures; + List resoures; resoures = readDom(); logger.info("Parsed Resources:\n" + resoures); resoures = readSax(); @@ -81,7 +81,7 @@ public class XmlTestMain { * @return * */ - private static List readDom() throws Exception { + private static List readDom() throws Exception { File file = new File("target/res_dom.xml"); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); @@ -89,7 +89,7 @@ public class XmlTestMain { Document document = docBuilder.parse(file); Element rootElement = document.getDocumentElement(); - List resources = new ArrayList(); + List resources = new ArrayList(); NodeList resElements = rootElement.getElementsByTagName("Resource"); for (int i = 0; i < resElements.getLength(); i++) { @@ -98,7 +98,7 @@ public class XmlTestMain { String name = resElement.getAttribute("name"); String type = resElement.getAttribute("type"); - Resource res = new Resource(); + MyModel res = new MyModel(); res.setId(id); res.setName(name); res.setType(type); @@ -114,7 +114,7 @@ public class XmlTestMain { return resources; } - private static void parseParameters(Resource res, NodeList paramElements) { + private static void parseParameters(MyModel res, NodeList paramElements) { for (int i = 0; i < paramElements.getLength(); i++) { Element paramElement = (Element) paramElements.item(i); String id = paramElement.getAttribute("id"); @@ -122,7 +122,7 @@ public class XmlTestMain { String type = paramElement.getAttribute("type"); String value = paramElement.getAttribute("value"); - Parameter param = new Parameter(); + MyParameter param = new MyParameter(); param.setId(id); param.setName(name); param.setType(type); @@ -136,10 +136,10 @@ public class XmlTestMain { * @return * */ - private static List readSax() throws Exception { + private static List readSax() throws Exception { - final List resources = new ArrayList<>(); - final Resource[] currentRes = new Resource[1]; + final List resources = new ArrayList<>(); + final MyModel[] currentRes = new MyModel[1]; DefaultHandler xmlHandler = new DefaultHandler() { @@ -149,7 +149,7 @@ public class XmlTestMain { switch (qName) { case "Resource": - Resource res = new Resource(); + MyModel res = new MyModel(); res.setId(attributes.getValue("id")); res.setName(attributes.getValue("name")); res.setType(attributes.getValue("type")); @@ -157,7 +157,7 @@ public class XmlTestMain { resources.add(res); break; case "Parameter": - Parameter param = new Parameter(); + MyParameter param = new MyParameter(); param.setId(attributes.getValue("id")); param.setName(attributes.getValue("name")); param.setType(attributes.getValue("type")); @@ -182,7 +182,7 @@ public class XmlTestMain { return resources; } - private static void writeDom(Resource res) throws Exception { + private static void writeDom(MyModel res) throws Exception { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); @@ -194,7 +194,7 @@ public class XmlTestMain { resElement.setAttribute("type", res.getType()); for (String paramId : res.getParameterKeySet()) { - Parameter param = res.getParameterBy(paramId); + MyParameter param = res.getParameterBy(paramId); Element paramElement = doc.createElement("Parameter"); paramElement.setAttribute("id", param.getId()); paramElement.setAttribute("name", param.getName()); @@ -250,7 +250,7 @@ public class XmlTestMain { } } - private static void writeSax(Resource res) throws Exception { + private static void writeSax(MyModel res) throws Exception { XMLOutputFactory factory = XMLOutputFactory.newInstance(); File file = new File("target/res_sax.xml"); @@ -268,7 +268,7 @@ public class XmlTestMain { writer.writeAttribute("type", res.getType()); for (String paramId : res.getParameterKeySet()) { - Parameter param = res.getParameterBy(paramId); + MyParameter param = res.getParameterBy(paramId); writer.writeEmptyElement("Parameter"); writer.writeAttribute("id", param.getId()); writer.writeAttribute("name", param.getName()); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java similarity index 72% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java index 03d67d7fc..218c82922 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java @@ -20,20 +20,20 @@ import ch.eitchnet.xmlpers.api.PersistenceContextFactory; import ch.eitchnet.xmlpers.objref.IdOfSubTypeRef; import ch.eitchnet.xmlpers.objref.ObjectRef; import ch.eitchnet.xmlpers.objref.ObjectReferenceCache; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; -public class ResourceContextFactory implements PersistenceContextFactory { +public class MyModelContextFactory implements PersistenceContextFactory { @Override - public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, Resource t) { + public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, MyModel t) { IdOfSubTypeRef objectRef = objectRefCache.getIdOfSubTypeRef(TestConstants.TYPE_RES, t.getType(), t.getId()); return createCtx(objectRef); } @Override - public PersistenceContext createCtx(ObjectRef objectRef) { - PersistenceContext ctx = new PersistenceContext<>(objectRef); - ctx.setParserFactory(new ResourceParserFactory()); + public PersistenceContext createCtx(ObjectRef objectRef) { + PersistenceContext ctx = new PersistenceContext<>(objectRef); + ctx.setParserFactory(new MyModelParserFactory()); return ctx; } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java similarity index 85% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java index f9b4ecea4..f7ede8f27 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java @@ -23,21 +23,21 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ch.eitchnet.xmlpers.api.DomParser; -import ch.eitchnet.xmlpers.test.model.Parameter; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyParameter; +import ch.eitchnet.xmlpers.test.model.MyModel; import ch.eitchnet.xmlpers.util.DomUtil; -public class ResourceDomParser implements DomParser { +public class MyModelDomParser implements DomParser { - private Resource resource; + private MyModel resource; @Override - public Resource getObject() { + public MyModel getObject() { return this.resource; } @Override - public void setObject(Resource resource) { + public void setObject(MyModel resource) { this.resource = resource; } @@ -56,7 +56,7 @@ public class ResourceDomParser implements DomParser { element.setAttribute("type", this.resource.getType()); for (String paramId : this.resource.getParameterKeySet()) { - Parameter param = this.resource.getParameterBy(paramId); + MyParameter param = this.resource.getParameterBy(paramId); Element paramElement = document.createElement("Parameter"); element.appendChild(paramElement); @@ -79,7 +79,7 @@ public class ResourceDomParser implements DomParser { String name = rootElement.getAttribute("name"); String type = rootElement.getAttribute("type"); - Resource resource = new Resource(id, name, type); + MyModel resource = new MyModel(id, name, type); NodeList children = rootElement.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { @@ -93,7 +93,7 @@ public class ResourceDomParser implements DomParser { String paramType = paramElement.getAttribute("type"); String paramValue = paramElement.getAttribute("value"); - Parameter param = new Parameter(paramId, paramName, paramType, paramValue); + MyParameter param = new MyParameter(paramId, paramName, paramType, paramValue); resource.addParameter(param); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java similarity index 74% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java index 72787b11a..0760861fb 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceParserFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java @@ -18,17 +18,17 @@ package ch.eitchnet.xmlpers.test.impl; import ch.eitchnet.xmlpers.api.DomParser; import ch.eitchnet.xmlpers.api.ParserFactory; import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyModel; -public class ResourceParserFactory implements ParserFactory { +public class MyModelParserFactory implements ParserFactory { @Override - public DomParser getDomParser() { - return new ResourceDomParser(); + public DomParser getDomParser() { + return new MyModelDomParser(); } @Override - public SaxParser getSaxParser() { - return new ResourceSaxParser(); + public SaxParser getSaxParser() { + return new MyModelSaxParser(); } } \ No newline at end of file diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java similarity index 84% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java rename to src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java index 7a87057f7..1e8efcc2b 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/ResourceSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java @@ -23,20 +23,20 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; -import ch.eitchnet.xmlpers.test.model.Parameter; -import ch.eitchnet.xmlpers.test.model.Resource; +import ch.eitchnet.xmlpers.test.model.MyParameter; +import ch.eitchnet.xmlpers.test.model.MyModel; -class ResourceSaxParser extends DefaultHandler implements SaxParser { +class MyModelSaxParser extends DefaultHandler implements SaxParser { - private Resource resource; + private MyModel resource; @Override - public Resource getObject() { + public MyModel getObject() { return this.resource; } @Override - public void setObject(Resource object) { + public void setObject(MyModel object) { this.resource = object; } @@ -54,7 +54,7 @@ class ResourceSaxParser extends DefaultHandler implements SaxParser { writer.writeAttribute("name", this.resource.getName()); writer.writeAttribute("type", this.resource.getType()); for (String paramId : this.resource.getParameterKeySet()) { - Parameter param = this.resource.getParameterBy(paramId); + MyParameter param = this.resource.getParameterBy(paramId); writer.writeEmptyElement("Parameter"); writer.writeAttribute("id", param.getId()); writer.writeAttribute("name", param.getName()); @@ -72,7 +72,7 @@ class ResourceSaxParser extends DefaultHandler implements SaxParser { String id = attributes.getValue("id"); String name = attributes.getValue("name"); String type = attributes.getValue("type"); - Resource resource = new Resource(id, name, type); + MyModel resource = new MyModel(id, name, type); this.resource = resource; break; case "Parameter": @@ -80,7 +80,7 @@ class ResourceSaxParser extends DefaultHandler implements SaxParser { name = attributes.getValue("name"); type = attributes.getValue("type"); String value = attributes.getValue("value"); - Parameter param = new Parameter(id, name, type, value); + MyParameter param = new MyParameter(id, name, type, value); this.resource.addParameter(param); break; default: diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index 8d9576b40..229382476 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -43,22 +43,22 @@ public class ModelBuilder { public static final String BOOK_PRESS_2 = "Another press"; public static final double BOOK_PRICE = 45.55D; - public static Resource createResource() { + public static MyModel createResource() { return createResource(RES_ID, RES_NAME, RES_TYPE); } - public static Resource createResource(String id) { + public static MyModel createResource(String id) { return createResource(id, RES_NAME, RES_TYPE); } - public static Resource createResource(String id, String name, String type) { - Resource resource = new Resource(id, name, type); - Parameter param = new Parameter(PARAM_ID, PARAM_NAME, PARAM_TYPE, PARAM_VALUE_1); + public static MyModel createResource(String id, String name, String type) { + MyModel resource = new MyModel(id, name, type); + MyParameter param = new MyParameter(PARAM_ID, PARAM_NAME, PARAM_TYPE, PARAM_VALUE_1); resource.addParameter(param); return resource; } - public static void updateResource(Resource resource) { + public static void updateResource(MyModel resource) { resource.setName(RES_NAME_MODIFIED); resource.getParameterBy(PARAM_ID).setValue(PARAM_VALUE_2); } @@ -95,12 +95,12 @@ public class ModelBuilder { Assert.assertEquals(BOOK_PRICE, book.getPrice(), 0.0); } - public static void assertResource(Resource resource) { + public static void assertResource(MyModel resource) { Assert.assertNotNull(resource); Assert.assertEquals(RES_ID, resource.getId()); Assert.assertEquals(RES_NAME, resource.getName()); Assert.assertEquals(RES_TYPE, resource.getType()); - Parameter param = resource.getParameterBy(PARAM_ID); + MyParameter param = resource.getParameterBy(PARAM_ID); Assert.assertNotNull(param); Assert.assertEquals(PARAM_ID, param.getId()); Assert.assertEquals(PARAM_NAME, param.getName()); @@ -108,12 +108,12 @@ public class ModelBuilder { Assert.assertEquals(PARAM_VALUE_1, param.getValue()); } - public static void assertResourceUpdated(Resource resource) { + public static void assertResourceUpdated(MyModel resource) { Assert.assertNotNull(resource); Assert.assertEquals(RES_ID, resource.getId()); Assert.assertEquals(RES_NAME_MODIFIED, resource.getName()); Assert.assertEquals(RES_TYPE, resource.getType()); - Parameter param = resource.getParameterBy(PARAM_ID); + MyParameter param = resource.getParameterBy(PARAM_ID); Assert.assertNotNull(param); Assert.assertEquals(PARAM_ID, param.getId()); Assert.assertEquals(PARAM_NAME, param.getName()); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java b/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java similarity index 86% rename from src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java rename to src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java index a9dd1cca7..f61a0fa62 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Resource.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java @@ -20,17 +20,17 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -public class Resource { +public class MyModel { private String id; private String name; private String type; - private Map parameters = new HashMap(); + private Map parameters = new HashMap(); /** * */ - public Resource() { + public MyModel() { // empty constructor } @@ -39,7 +39,7 @@ public class Resource { * @param name * @param type */ - public Resource(String id, String name, String type) { + public MyModel(String id, String name, String type) { super(); this.id = id; this.name = name; @@ -57,7 +57,7 @@ public class Resource { builder.append(", type="); builder.append(this.type); builder.append(", parameters="); - for (Entry param : this.parameters.entrySet()) { + for (Entry param : this.parameters.entrySet()) { builder.append("\n"); builder.append(" " + param.getKey() + " = " + param.getValue()); } @@ -107,7 +107,7 @@ public class Resource { this.type = type; } - public void addParameter(Parameter parameter) { + public void addParameter(MyParameter parameter) { this.parameters.put(parameter.getId(), parameter); } @@ -115,7 +115,7 @@ public class Resource { return this.parameters.keySet(); } - public Parameter getParameterBy(String id) { + public MyParameter getParameterBy(String id) { return this.parameters.get(id); } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java b/src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java similarity index 94% rename from src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java rename to src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java index d3b422ec0..d4ca1f189 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/Parameter.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java @@ -15,7 +15,7 @@ */ package ch.eitchnet.xmlpers.test.model; -public class Parameter { +public class MyParameter { private String id; private String name; @@ -25,7 +25,7 @@ public class Parameter { /** * */ - public Parameter() { + public MyParameter() { // empty constructor } @@ -35,7 +35,7 @@ public class Parameter { * @param type * @param value */ - public Parameter(String id, String name, String type, String value) { + public MyParameter(String id, String name, String type, String value) { super(); this.id = id; this.name = name; From 97bd4fa08968832230d8f8383f20704824534a07 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 23 Aug 2014 20:46:58 +0200 Subject: [PATCH 69/87] [Minor] removed setting of object on CTX - do by FactoryDelegator When you implement a ContextFactory, and create the PersistenceContext, then set the object as well --- src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java | 10 ++-------- .../eitchnet/xmlpers/test/impl/BookContextFactory.java | 4 +++- .../xmlpers/test/impl/MyModelContextFactory.java | 4 +++- 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index c2a492ed5..f5064db6e 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -53,7 +53,6 @@ public class ObjectDao { assertNotClosed(); assertNotNull(object); PersistenceContext ctx = createCtx(object); - ctx.setObject(object); ctx.getObjectRef().lock(); this.objectFilter.add(ctx.getObjectRef().getType(), ctx); } @@ -64,7 +63,6 @@ public class ObjectDao { if (!objects.isEmpty()) { for (T object : objects) { PersistenceContext ctx = createCtx(object); - ctx.setObject(object); ctx.getObjectRef().lock(); this.objectFilter.add(ctx.getObjectRef().getType(), ctx); } @@ -75,7 +73,6 @@ public class ObjectDao { assertNotClosed(); assertNotNull(object); PersistenceContext ctx = createCtx(object); - ctx.setObject(object); ctx.getObjectRef().lock(); this.objectFilter.update(ctx.getObjectRef().getType(), ctx); } @@ -86,7 +83,6 @@ public class ObjectDao { if (!objects.isEmpty()) { for (T object : objects) { PersistenceContext ctx = createCtx(object); - ctx.setObject(object); ctx.getObjectRef().lock(); this.objectFilter.update(ctx.getObjectRef().getType(), ctx); } @@ -97,7 +93,6 @@ public class ObjectDao { assertNotClosed(); assertNotNull(object); PersistenceContext ctx = createCtx(object); - ctx.setObject(object); ctx.getObjectRef().lock(); this.objectFilter.remove(ctx.getObjectRef().getType(), ctx); } @@ -108,7 +103,6 @@ public class ObjectDao { if (!objects.isEmpty()) { for (T object : objects) { PersistenceContext ctx = createCtx(object); - ctx.setObject(object); ctx.getObjectRef().lock(); this.objectFilter.remove(ctx.getObjectRef().getType(), ctx); } @@ -293,12 +287,12 @@ public class ObjectDao { } } - private PersistenceContext createCtx(T object) { + public PersistenceContext createCtx(T object) { return this.ctxFactoryDelegator. getCtxFactory(object.getClass()).createCtx(this.tx.getObjectRefCache(), object); } - private PersistenceContext createCtx(ObjectRef objectRef) { + public PersistenceContext createCtx(ObjectRef objectRef) { String type = objectRef.getType(); PersistenceContextFactory ctxFactory = this.ctxFactoryDelegator. getCtxFactory(type); return ctxFactory.createCtx(objectRef); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java index ccb808507..50563cb82 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java @@ -34,6 +34,8 @@ public class BookContextFactory implements PersistenceContextFactory { @Override public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, Book t) { IdOfTypeRef objectRef = objectRefCache.getIdOfTypeRef(TestConstants.TYPE_BOOK, t.getId().toString()); - return createCtx(objectRef); + PersistenceContext ctx = createCtx(objectRef); + ctx.setObject(t); + return ctx; } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java index 218c82922..718813d46 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java @@ -27,7 +27,9 @@ public class MyModelContextFactory implements PersistenceContextFactory @Override public PersistenceContext createCtx(ObjectReferenceCache objectRefCache, MyModel t) { IdOfSubTypeRef objectRef = objectRefCache.getIdOfSubTypeRef(TestConstants.TYPE_RES, t.getType(), t.getId()); - return createCtx(objectRef); + PersistenceContext ctx = createCtx(objectRef); + ctx.setObject(t); + return ctx; } @Override From 930e85fdfe251502ccc1c3aea3939ad8670a446f Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 23 Aug 2014 20:47:37 +0200 Subject: [PATCH 70/87] [New] exposing FileDao in Transaction so users can bypass tx --- .../java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java | 2 ++ .../eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java index cd3c50de8..0f2efa7e5 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java @@ -54,6 +54,8 @@ public interface PersistenceTransaction extends AutoCloseable { public MetadataDao getMetadataDao(); + public FileDao getFileDao(); + public ObjectReferenceCache getObjectRefCache(); public PersistenceRealm getRealm(); diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index 7d6bc8fe4..053337e60 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -114,6 +114,11 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { return this.metadataDao; } + @Override + public FileDao getFileDao() { + return this.fileDao; + } + @Override public ObjectReferenceCache getObjectRefCache() { return this.realm.getObjectRefCache(); From ced1848b7600b8a2372039b5e8c9e76688c237c1 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 24 Aug 2014 17:21:59 +0200 Subject: [PATCH 71/87] [Project] set version to 1.0.0-SNAPSHOT --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index b90e5dea4..5f03b1e72 100644 --- a/pom.xml +++ b/pom.xml @@ -5,12 +5,12 @@ ch.eitchnet ch.eitchnet.parent - 1.1.0-SNAPSHOT + 1.0.0 ../ch.eitchnet.parent/pom.xml ch.eitchnet.xmlpers - 0.3.0-SNAPSHOT + 1.0.0-SNAPSHOT jar ch.eitchnet.xmlpers https://github.com/eitchnet/ch.eitchnet.xmlpers From 75199bc6b74a3ee5c5ae964457f396adbba09d27 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 24 Aug 2014 18:17:41 +0200 Subject: [PATCH 72/87] [Project] set version to 1.0.0-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 5f03b1e72..5cddc9a21 100644 --- a/pom.xml +++ b/pom.xml @@ -39,7 +39,7 @@ ch.eitchnet ch.eitchnet.utils - 0.2.0-SNAPSHOT + 1.0.0-SNAPSHOT From 3fbf73fd15f0d93406160f10990f4761ceacba5d Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 14 Sep 2014 12:19:49 +0200 Subject: [PATCH 73/87] [Minor] code cleanup --- .../eitchnet/xmlpers/api/ParserFactory.java | 1 - .../xmlpers/api/PersistenceManager.java | 7 +- .../xmlpers/objref/LockableObject.java | 6 +- .../eitchnet/xmlpers/objref/SubTypeRef.java | 2 +- .../java/javanet/staxutils/Indentation.java | 45 +- .../staxutils/IndentingXMLStreamWriter.java | 500 +++++++++--------- .../helpers/StreamWriterDelegate.java | 216 ++++---- .../ch/eitchnet/xmlpers/test/LockingTest.java | 8 +- .../ch/eitchnet/xmlpers/test/XmlTestMain.java | 2 +- .../xmlpers/test/impl/MyModelDomParser.java | 2 +- .../xmlpers/test/impl/MyModelSaxParser.java | 2 +- .../xmlpers/test/model/ModelBuilder.java | 2 +- .../eitchnet/xmlpers/test/model/MyModel.java | 9 +- 13 files changed, 394 insertions(+), 408 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java b/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java index b1ba612cf..003b1236d 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java @@ -15,7 +15,6 @@ */ package ch.eitchnet.xmlpers.api; - public interface ParserFactory { public DomParser getDomParser(); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java index 2790a394c..e19b71521 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java @@ -15,7 +15,6 @@ */ package ch.eitchnet.xmlpers.api; - /** * @author Robert von Burg * @@ -23,10 +22,10 @@ package ch.eitchnet.xmlpers.api; public interface PersistenceManager { public static final String DEFAULT_REALM = "defaultRealm"; //$NON-NLS-1$ - + public PersistenceContextFactoryDelegator getCtxFactory(); - + public PersistenceTransaction openTx(); - + public PersistenceTransaction openTx(String realm); } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java index 760b8234f..545de62d7 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java @@ -48,11 +48,11 @@ public class LockableObject { if (!this.lock.tryLock(tryLockTime, TimeUnit.MILLISECONDS)) { String msg = "Failed to acquire lock after {0} for {1}"; //$NON-NLS-1$ - msg = MessageFormat.format(msg, StringHelper.formatMillisecondsDuration(tryLockTime), this.toString()); + msg = MessageFormat.format(msg, StringHelper.formatMillisecondsDuration(tryLockTime), toString()); throw new XmlPersistenceException(msg); } if (logger.isDebugEnabled()) - logger.debug("locked " + this.toString()); //$NON-NLS-1$ + logger.debug("locked " + toString()); //$NON-NLS-1$ } catch (InterruptedException e) { throw new XmlPersistenceException("Thread interrupted: " + e.getMessage(), e); //$NON-NLS-1$ } @@ -64,6 +64,6 @@ public class LockableObject { public void unlock() { this.lock.unlock(); if (logger.isDebugEnabled()) - logger.debug("unlocking " + this.toString()); //$NON-NLS-1$ + logger.debug("unlocking " + toString()); //$NON-NLS-1$ } } diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java index f77e274ef..ed792d5f5 100644 --- a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java +++ b/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java @@ -72,7 +72,7 @@ public class SubTypeRef extends ObjectRef { public File getPath(PathBuilder pathBuilder) { return pathBuilder.getSubTypePath(this.type, this.subType); } - + @Override public PersistenceContext createPersistenceContext(PersistenceTransaction tx) { String msg = MessageFormat.format("{0} is not a leaf and can thus not have a Persistence Context", getName()); //$NON-NLS-1$ diff --git a/src/main/java/javanet/staxutils/Indentation.java b/src/main/java/javanet/staxutils/Indentation.java index e7f554b92..844513789 100644 --- a/src/main/java/javanet/staxutils/Indentation.java +++ b/src/main/java/javanet/staxutils/Indentation.java @@ -1,39 +1,36 @@ package javanet.staxutils; /** - * Characters that represent line breaks and indentation. These are represented - * as String-valued JavaBean properties. + * Characters that represent line breaks and indentation. These are represented as String-valued JavaBean properties. */ @SuppressWarnings("nls") public interface Indentation { - /** Two spaces; the default indentation. */ + /** Two spaces; the default indentation. */ public static final String DEFAULT_INDENT = " "; - /** - * Set the characters used for one level of indentation. The default is - * {@link #DEFAULT_INDENT}. "\t" is a popular alternative. - */ - void setIndent(String indent); + /** + * Set the characters used for one level of indentation. The default is {@link #DEFAULT_INDENT}. "\t" is a popular + * alternative. + */ + void setIndent(String indent); - /** The characters used for one level of indentation. */ - String getIndent(); + /** The characters used for one level of indentation. */ + String getIndent(); - /** - * "\n"; the normalized representation of end-of-line in XML. - */ - public static final String NORMAL_END_OF_LINE = "\n"; + /** + * "\n"; the normalized representation of end-of-line in XML. + */ + public static final String NORMAL_END_OF_LINE = "\n"; - /** - * Set the characters that introduce a new line. The default is - * {@link #NORMAL_END_OF_LINE}. - * {@link IndentingXMLStreamWriter#getLineSeparator}() is a popular - * alternative. - */ - public void setNewLine(String newLine); + /** + * Set the characters that introduce a new line. The default is {@link #NORMAL_END_OF_LINE}. + * {@link IndentingXMLStreamWriter#getLineSeparator}() is a popular alternative. + */ + public void setNewLine(String newLine); - /** The characters that introduce a new line. */ - String getNewLine(); + /** The characters that introduce a new line. */ + String getNewLine(); } diff --git a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java index aa9ffc3b6..f4af62c62 100644 --- a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java +++ b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java @@ -37,9 +37,8 @@ import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** - * A filter that indents an XML stream. To apply it, construct a filter that - * contains another {@link XMLStreamWriter}, which you pass to the constructor. - * Then call methods of the filter instead of the contained stream. For example: + * A filter that indents an XML stream. To apply it, construct a filter that contains another {@link XMLStreamWriter}, + * which you pass to the constructor. Then call methods of the filter instead of the contained stream. For example: * *
  * {@link XMLStreamWriter} stream = ...
@@ -49,22 +48,19 @@ import javax.xml.stream.XMLStreamWriter;
  * 
* *

- * The filter inserts characters to format the document as an outline, with - * nested elements indented. Basically, it inserts a line break and whitespace - * before: + * The filter inserts characters to format the document as an outline, with nested elements indented. Basically, it + * inserts a line break and whitespace before: *

    *
  • each DTD, processing instruction or comment that's not preceded by data
  • *
  • each starting tag that's not preceded by data
  • *
  • each ending tag that's preceded by nested elements but not data
  • *
- * This works well with 'data-oriented' XML, wherein each element contains - * either data or nested elements but not both. It can work badly with other - * styles of XML. For example, the data in a 'mixed content' document are apt to - * be polluted with indentation characters. + * This works well with 'data-oriented' XML, wherein each element contains either data or nested elements but not both. + * It can work badly with other styles of XML. For example, the data in a 'mixed content' document are apt to be + * polluted with indentation characters. *

- * Indentation can be adjusted by setting the newLine and indent properties. But - * set them to whitespace only, for best results. Non-whitespace is apt to cause - * problems, for example when this class attempts to insert newLine before the + * Indentation can be adjusted by setting the newLine and indent properties. But set them to whitespace only, for best + * results. Non-whitespace is apt to cause problems, for example when this class attempts to insert newLine before the * root element. * * @author John Kristian @@ -72,307 +68,303 @@ import javax.xml.stream.XMLStreamWriter; @SuppressWarnings("nls") public class IndentingXMLStreamWriter extends StreamWriterDelegate implements Indentation { - public IndentingXMLStreamWriter(XMLStreamWriter out) { - this(out, DEFAULT_INDENT, NORMAL_END_OF_LINE); - } - - public IndentingXMLStreamWriter(XMLStreamWriter out, String indent) { - this(out, indent, NORMAL_END_OF_LINE); - } - - public IndentingXMLStreamWriter(XMLStreamWriter out, String indent, String newLine) { - super(out); - setIndent(indent); - setNewLine(newLine); - } + public IndentingXMLStreamWriter(XMLStreamWriter out) { + this(out, DEFAULT_INDENT, NORMAL_END_OF_LINE); + } - /** How deeply nested the current scope is. The root element is depth 1. */ - private int depth = 0; // document scope + public IndentingXMLStreamWriter(XMLStreamWriter out, String indent) { + this(out, indent, NORMAL_END_OF_LINE); + } - /** stack[depth] indicates what's been written into the current scope. */ - private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet + public IndentingXMLStreamWriter(XMLStreamWriter out, String indent, String newLine) { + super(out); + setIndent(indent); + setNewLine(newLine); + } - private static final int WROTE_MARKUP = 1; + /** How deeply nested the current scope is. The root element is depth 1. */ + private int depth = 0; // document scope - private static final int WROTE_DATA = 2; + /** stack[depth] indicates what's been written into the current scope. */ + private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet - private String indent = DEFAULT_INDENT; + private static final int WROTE_MARKUP = 1; - private String newLine = NORMAL_END_OF_LINE; + private static final int WROTE_DATA = 2; - /** newLine followed by copies of indent. */ - private char[] linePrefix = null; + private String indent = DEFAULT_INDENT; - @Override + private String newLine = NORMAL_END_OF_LINE; + + /** newLine followed by copies of indent. */ + private char[] linePrefix = null; + + @Override public void setIndent(String indent) { - if (!indent.equals(this.indent)) { - this.indent = indent; - this.linePrefix = null; - } - } + if (!indent.equals(this.indent)) { + this.indent = indent; + this.linePrefix = null; + } + } - @Override + @Override public String getIndent() { - return this.indent; - } + return this.indent; + } - @Override + @Override public void setNewLine(String newLine) { - if (!newLine.equals(this.newLine)) { - this.newLine = newLine; - this.linePrefix = null; - } - } + if (!newLine.equals(this.newLine)) { + this.newLine = newLine; + this.linePrefix = null; + } + } - /** - * @return System.getProperty("line.separator"); or - * {@link #NORMAL_END_OF_LINE} if that fails. - */ - public static String getLineSeparator() { - try { - return System.getProperty("line.separator"); - } catch (SecurityException ignored) { - // - } - return NORMAL_END_OF_LINE; - } + /** + * @return System.getProperty("line.separator"); or {@link #NORMAL_END_OF_LINE} if that fails. + */ + public static String getLineSeparator() { + try { + return System.getProperty("line.separator"); + } catch (SecurityException ignored) { + // + } + return NORMAL_END_OF_LINE; + } - @Override + @Override public String getNewLine() { - return this.newLine; - } + return this.newLine; + } - @Override + @Override public void writeStartDocument() throws XMLStreamException { - beforeMarkup(); - this.out.writeStartDocument(); - afterMarkup(); - } + beforeMarkup(); + this.out.writeStartDocument(); + afterMarkup(); + } - @Override + @Override public void writeStartDocument(String version) throws XMLStreamException { - beforeMarkup(); - this.out.writeStartDocument(version); - afterMarkup(); - } + beforeMarkup(); + this.out.writeStartDocument(version); + afterMarkup(); + } - @Override + @Override public void writeStartDocument(String encoding, String version) throws XMLStreamException { - beforeMarkup(); - this.out.writeStartDocument(encoding, version); - afterMarkup(); - } + beforeMarkup(); + this.out.writeStartDocument(encoding, version); + afterMarkup(); + } - @Override + @Override public void writeDTD(String dtd) throws XMLStreamException { - beforeMarkup(); - this.out.writeDTD(dtd); - afterMarkup(); - } + beforeMarkup(); + this.out.writeDTD(dtd); + afterMarkup(); + } - @Override + @Override public void writeProcessingInstruction(String target) throws XMLStreamException { - beforeMarkup(); - this.out.writeProcessingInstruction(target); - afterMarkup(); - } + beforeMarkup(); + this.out.writeProcessingInstruction(target); + afterMarkup(); + } - @Override + @Override public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - beforeMarkup(); - this.out.writeProcessingInstruction(target, data); - afterMarkup(); - } + beforeMarkup(); + this.out.writeProcessingInstruction(target, data); + afterMarkup(); + } - @Override + @Override public void writeComment(String data) throws XMLStreamException { - beforeMarkup(); - this.out.writeComment(data); - afterMarkup(); - } + beforeMarkup(); + this.out.writeComment(data); + afterMarkup(); + } - @Override + @Override public void writeEmptyElement(String localName) throws XMLStreamException { - beforeMarkup(); - this.out.writeEmptyElement(localName); - afterMarkup(); - } + beforeMarkup(); + this.out.writeEmptyElement(localName); + afterMarkup(); + } - @Override + @Override public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - beforeMarkup(); - this.out.writeEmptyElement(namespaceURI, localName); - afterMarkup(); - } + beforeMarkup(); + this.out.writeEmptyElement(namespaceURI, localName); + afterMarkup(); + } - @Override - public void writeEmptyElement(String prefix, String localName, String namespaceURI) - throws XMLStreamException { - beforeMarkup(); - this.out.writeEmptyElement(prefix, localName, namespaceURI); - afterMarkup(); - } + @Override + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + beforeMarkup(); + this.out.writeEmptyElement(prefix, localName, namespaceURI); + afterMarkup(); + } - @Override + @Override public void writeStartElement(String localName) throws XMLStreamException { - beforeStartElement(); - this.out.writeStartElement(localName); - afterStartElement(); - } + beforeStartElement(); + this.out.writeStartElement(localName); + afterStartElement(); + } - @Override + @Override public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - beforeStartElement(); - this.out.writeStartElement(namespaceURI, localName); - afterStartElement(); - } + beforeStartElement(); + this.out.writeStartElement(namespaceURI, localName); + afterStartElement(); + } - @Override - public void writeStartElement(String prefix, String localName, String namespaceURI) - throws XMLStreamException { - beforeStartElement(); - this.out.writeStartElement(prefix, localName, namespaceURI); - afterStartElement(); - } + @Override + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + beforeStartElement(); + this.out.writeStartElement(prefix, localName, namespaceURI); + afterStartElement(); + } - @Override + @Override public void writeCharacters(String text) throws XMLStreamException { - this.out.writeCharacters(text); - afterData(); - } + this.out.writeCharacters(text); + afterData(); + } - @Override + @Override public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - this.out.writeCharacters(text, start, len); - afterData(); - } + this.out.writeCharacters(text, start, len); + afterData(); + } - @Override + @Override public void writeCData(String data) throws XMLStreamException { - this.out.writeCData(data); - afterData(); - } + this.out.writeCData(data); + afterData(); + } - @Override + @Override public void writeEntityRef(String name) throws XMLStreamException { - this.out.writeEntityRef(name); - afterData(); - } + this.out.writeEntityRef(name); + afterData(); + } - @Override + @Override public void writeEndElement() throws XMLStreamException { - beforeEndElement(); - this.out.writeEndElement(); - afterEndElement(); - } + beforeEndElement(); + this.out.writeEndElement(); + afterEndElement(); + } - @Override + @Override public void writeEndDocument() throws XMLStreamException { - try { - while (this.depth > 0) { - writeEndElement(); // indented - } - } catch (Exception ignored) { - ignored.printStackTrace(); - } - this.out.writeEndDocument(); - afterEndDocument(); - } + try { + while (this.depth > 0) { + writeEndElement(); // indented + } + } catch (Exception ignored) { + ignored.printStackTrace(); + } + this.out.writeEndDocument(); + afterEndDocument(); + } - /** Prepare to write markup, by writing a new line and indentation. */ - protected void beforeMarkup() { - int soFar = this.stack[this.depth]; - if ((soFar & WROTE_DATA) == 0 // no data in this scope - && (this.depth > 0 || soFar != 0)) // not the first line - { - try { - writeNewLine(this.depth); - if (this.depth > 0 && getIndent().length() > 0) { - afterMarkup(); // indentation was written - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } + /** Prepare to write markup, by writing a new line and indentation. */ + protected void beforeMarkup() { + int soFar = this.stack[this.depth]; + if ((soFar & WROTE_DATA) == 0 // no data in this scope + && (this.depth > 0 || soFar != 0)) // not the first line + { + try { + writeNewLine(this.depth); + if (this.depth > 0 && getIndent().length() > 0) { + afterMarkup(); // indentation was written + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } - /** Note that markup or indentation was written. */ - protected void afterMarkup() { - this.stack[this.depth] |= WROTE_MARKUP; - } + /** Note that markup or indentation was written. */ + protected void afterMarkup() { + this.stack[this.depth] |= WROTE_MARKUP; + } - /** Note that data were written. */ - protected void afterData() { - this.stack[this.depth] |= WROTE_DATA; - } + /** Note that data were written. */ + protected void afterData() { + this.stack[this.depth] |= WROTE_DATA; + } - /** Prepare to start an element, by allocating stack space. */ - protected void beforeStartElement() { - beforeMarkup(); - if (this.stack.length <= this.depth + 1) { - // Allocate more space for the stack: - int[] newStack = new int[this.stack.length * 2]; - System.arraycopy(this.stack, 0, newStack, 0, this.stack.length); - this.stack = newStack; - } - this.stack[this.depth + 1] = 0; // nothing written yet - } + /** Prepare to start an element, by allocating stack space. */ + protected void beforeStartElement() { + beforeMarkup(); + if (this.stack.length <= this.depth + 1) { + // Allocate more space for the stack: + int[] newStack = new int[this.stack.length * 2]; + System.arraycopy(this.stack, 0, newStack, 0, this.stack.length); + this.stack = newStack; + } + this.stack[this.depth + 1] = 0; // nothing written yet + } - /** Note that an element was started. */ - protected void afterStartElement() { - afterMarkup(); - ++this.depth; - } + /** Note that an element was started. */ + protected void afterStartElement() { + afterMarkup(); + ++this.depth; + } - /** Prepare to end an element, by writing a new line and indentation. */ - protected void beforeEndElement() { - if (this.depth > 0 && this.stack[this.depth] == WROTE_MARKUP) { // but not data - try { - writeNewLine(this.depth - 1); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - } - } + /** Prepare to end an element, by writing a new line and indentation. */ + protected void beforeEndElement() { + if (this.depth > 0 && this.stack[this.depth] == WROTE_MARKUP) { // but not data + try { + writeNewLine(this.depth - 1); + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } + } - /** Note that an element was ended. */ - protected void afterEndElement() { - if (this.depth > 0) { - --this.depth; - } - } + /** Note that an element was ended. */ + protected void afterEndElement() { + if (this.depth > 0) { + --this.depth; + } + } - /** Note that a document was ended. */ - protected void afterEndDocument() { - if (this.stack[this.depth = 0] == WROTE_MARKUP) { // but not data - try { - writeNewLine(0); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - } - this.stack[this.depth] = 0; // start fresh - } + /** Note that a document was ended. */ + protected void afterEndDocument() { + if (this.stack[this.depth = 0] == WROTE_MARKUP) { // but not data + try { + writeNewLine(0); + } catch (Exception ignored) { + ignored.printStackTrace(); + } + } + this.stack[this.depth] = 0; // start fresh + } - /** Write a line separator followed by indentation. */ - protected void writeNewLine(int indentation) throws XMLStreamException { - final int newLineLength = getNewLine().length(); - final int prefixLength = newLineLength + (getIndent().length() * indentation); - if (prefixLength > 0) { - if (this.linePrefix == null) { - this.linePrefix = (getNewLine() + getIndent()).toCharArray(); - } - while (prefixLength > this.linePrefix.length) { - // make linePrefix longer: - char[] newPrefix = new char[newLineLength - + ((this.linePrefix.length - newLineLength) * 2)]; - System.arraycopy(this.linePrefix, 0, newPrefix, 0, this.linePrefix.length); - System.arraycopy(this.linePrefix, newLineLength, newPrefix, this.linePrefix.length, - this.linePrefix.length - newLineLength); - this.linePrefix = newPrefix; - } - this.out.writeCharacters(this.linePrefix, 0, prefixLength); - } - } + /** Write a line separator followed by indentation. */ + protected void writeNewLine(int indentation) throws XMLStreamException { + final int newLineLength = getNewLine().length(); + final int prefixLength = newLineLength + (getIndent().length() * indentation); + if (prefixLength > 0) { + if (this.linePrefix == null) { + this.linePrefix = (getNewLine() + getIndent()).toCharArray(); + } + while (prefixLength > this.linePrefix.length) { + // make linePrefix longer: + char[] newPrefix = new char[newLineLength + ((this.linePrefix.length - newLineLength) * 2)]; + System.arraycopy(this.linePrefix, 0, newPrefix, 0, this.linePrefix.length); + System.arraycopy(this.linePrefix, newLineLength, newPrefix, this.linePrefix.length, + this.linePrefix.length - newLineLength); + this.linePrefix = newPrefix; + } + this.out.writeCharacters(this.linePrefix, 0, prefixLength); + } + } } diff --git a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java index 49e70d88e..9922aafa7 100644 --- a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java +++ b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java @@ -36,182 +36,178 @@ import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** - * Abstract class for writing filtered XML streams. This class provides methods - * that merely delegate to the contained stream. Subclasses should override some - * of these methods, and may also provide additional methods and fields. + * Abstract class for writing filtered XML streams. This class provides methods that merely delegate to the contained + * stream. Subclasses should override some of these methods, and may also provide additional methods and fields. * * @author John Kristian */ public abstract class StreamWriterDelegate implements XMLStreamWriter { - protected StreamWriterDelegate(XMLStreamWriter out) { - this.out = out; - } + protected StreamWriterDelegate(XMLStreamWriter out) { + this.out = out; + } - protected XMLStreamWriter out; + protected XMLStreamWriter out; - @Override + @Override public Object getProperty(String name) throws IllegalArgumentException { - return this.out.getProperty(name); - } + return this.out.getProperty(name); + } - @Override + @Override public NamespaceContext getNamespaceContext() { - return this.out.getNamespaceContext(); - } + return this.out.getNamespaceContext(); + } - @Override + @Override public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { - this.out.setNamespaceContext(context); - } + this.out.setNamespaceContext(context); + } - @Override + @Override public void setDefaultNamespace(String uri) throws XMLStreamException { - this.out.setDefaultNamespace(uri); - } + this.out.setDefaultNamespace(uri); + } - @Override + @Override public void writeStartDocument() throws XMLStreamException { - this.out.writeStartDocument(); - } + this.out.writeStartDocument(); + } - @Override + @Override public void writeStartDocument(String version) throws XMLStreamException { - this.out.writeStartDocument(version); - } + this.out.writeStartDocument(version); + } - @Override + @Override public void writeStartDocument(String encoding, String version) throws XMLStreamException { - this.out.writeStartDocument(encoding, version); - } + this.out.writeStartDocument(encoding, version); + } - @Override + @Override public void writeDTD(String dtd) throws XMLStreamException { - this.out.writeDTD(dtd); - } + this.out.writeDTD(dtd); + } - @Override + @Override public void writeProcessingInstruction(String target) throws XMLStreamException { - this.out.writeProcessingInstruction(target); - } + this.out.writeProcessingInstruction(target); + } - @Override + @Override public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - this.out.writeProcessingInstruction(target, data); - } + this.out.writeProcessingInstruction(target, data); + } - @Override + @Override public void writeComment(String data) throws XMLStreamException { - this.out.writeComment(data); - } + this.out.writeComment(data); + } - @Override + @Override public void writeEmptyElement(String localName) throws XMLStreamException { - this.out.writeEmptyElement(localName); - } + this.out.writeEmptyElement(localName); + } - @Override + @Override public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - this.out.writeEmptyElement(namespaceURI, localName); - } + this.out.writeEmptyElement(namespaceURI, localName); + } - @Override - public void writeEmptyElement(String prefix, String localName, String namespaceURI) - throws XMLStreamException { - this.out.writeEmptyElement(prefix, localName, namespaceURI); - } + @Override + public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + this.out.writeEmptyElement(prefix, localName, namespaceURI); + } - @Override + @Override public void writeStartElement(String localName) throws XMLStreamException { - this.out.writeStartElement(localName); - } + this.out.writeStartElement(localName); + } - @Override + @Override public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - this.out.writeStartElement(namespaceURI, localName); - } + this.out.writeStartElement(namespaceURI, localName); + } - @Override - public void writeStartElement(String prefix, String localName, String namespaceURI) - throws XMLStreamException { - this.out.writeStartElement(prefix, localName, namespaceURI); - } + @Override + public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { + this.out.writeStartElement(prefix, localName, namespaceURI); + } - @Override + @Override public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { - this.out.writeDefaultNamespace(namespaceURI); - } + this.out.writeDefaultNamespace(namespaceURI); + } - @Override + @Override public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { - this.out.writeNamespace(prefix, namespaceURI); - } + this.out.writeNamespace(prefix, namespaceURI); + } - @Override + @Override public String getPrefix(String uri) throws XMLStreamException { - return this.out.getPrefix(uri); - } + return this.out.getPrefix(uri); + } - @Override + @Override public void setPrefix(String prefix, String uri) throws XMLStreamException { - this.out.setPrefix(prefix, uri); - } + this.out.setPrefix(prefix, uri); + } - @Override + @Override public void writeAttribute(String localName, String value) throws XMLStreamException { - this.out.writeAttribute(localName, value); - } + this.out.writeAttribute(localName, value); + } - @Override - public void writeAttribute(String namespaceURI, String localName, String value) - throws XMLStreamException { - this.out.writeAttribute(namespaceURI, localName, value); - } + @Override + public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { + this.out.writeAttribute(namespaceURI, localName, value); + } - @Override + @Override public void writeAttribute(String prefix, String namespaceURI, String localName, String value) - throws XMLStreamException { - this.out.writeAttribute(prefix, namespaceURI, localName, value); - } + throws XMLStreamException { + this.out.writeAttribute(prefix, namespaceURI, localName, value); + } - @Override + @Override public void writeCharacters(String text) throws XMLStreamException { - this.out.writeCharacters(text); - } + this.out.writeCharacters(text); + } - @Override + @Override public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - this.out.writeCharacters(text, start, len); - } + this.out.writeCharacters(text, start, len); + } - @Override + @Override public void writeCData(String data) throws XMLStreamException { - this.out.writeCData(data); - } + this.out.writeCData(data); + } - @Override + @Override public void writeEntityRef(String name) throws XMLStreamException { - this.out.writeEntityRef(name); - } + this.out.writeEntityRef(name); + } - @Override + @Override public void writeEndElement() throws XMLStreamException { - this.out.writeEndElement(); - } + this.out.writeEndElement(); + } - @Override + @Override public void writeEndDocument() throws XMLStreamException { - this.out.writeEndDocument(); - } + this.out.writeEndDocument(); + } - @Override + @Override public void flush() throws XMLStreamException { - this.out.flush(); - } + this.out.flush(); + } - @Override + @Override public void close() throws XMLStreamException { - this.out.close(); - } + this.out.close(); + } } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java index 68de2d5a9..906d61a4c 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java @@ -60,7 +60,7 @@ public class LockingTest extends AbstractPersistenceTest { properties.setProperty(PersistenceConstants.PROP_LOCK_TIME_MILLIS, Long.toString(500L)); setup(properties); - this.waitForWorkersTime = LockableObject.getLockTime() + this.getWaitForWorkersTime() + 300L; + this.waitForWorkersTime = LockableObject.getLockTime() + getWaitForWorkersTime() + 300L; } @Test @@ -128,10 +128,10 @@ public class LockingTest extends AbstractPersistenceTest { private int runWorkers(List workers) throws InterruptedException { - this.setRun(true); + setRun(true); for (AbstractWorker worker : workers) { - worker.join(this.getWaitForWorkersTime() + 2000L); + worker.join(getWaitForWorkersTime() + 2000L); } int nrOfSuccess = 0; @@ -169,7 +169,7 @@ public class LockingTest extends AbstractPersistenceTest { public void run() { logger.info("Waiting for ok to work..."); //$NON-NLS-1$ - while (!LockingTest.this.isRun()) { + while (!isRun()) { try { Thread.sleep(10L); } catch (InterruptedException e) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index f05e83215..690cf4e6f 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -47,8 +47,8 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.utils.exceptions.XmlException; import ch.eitchnet.utils.helper.XmlHelper; import ch.eitchnet.xmlpers.test.model.ModelBuilder; -import ch.eitchnet.xmlpers.test.model.MyParameter; import ch.eitchnet.xmlpers.test.model.MyModel; +import ch.eitchnet.xmlpers.test.model.MyParameter; /** * @author Robert von Burg diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java index f7ede8f27..30859879e 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java @@ -23,8 +23,8 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ch.eitchnet.xmlpers.api.DomParser; -import ch.eitchnet.xmlpers.test.model.MyParameter; import ch.eitchnet.xmlpers.test.model.MyModel; +import ch.eitchnet.xmlpers.test.model.MyParameter; import ch.eitchnet.xmlpers.util.DomUtil; public class MyModelDomParser implements DomParser { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java index 1e8efcc2b..858be533a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java @@ -23,8 +23,8 @@ import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; -import ch.eitchnet.xmlpers.test.model.MyParameter; import ch.eitchnet.xmlpers.test.model.MyModel; +import ch.eitchnet.xmlpers.test.model.MyParameter; class MyModelSaxParser extends DefaultHandler implements SaxParser { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java index 229382476..be4d9ff78 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java @@ -46,7 +46,7 @@ public class ModelBuilder { public static MyModel createResource() { return createResource(RES_ID, RES_NAME, RES_TYPE); } - + public static MyModel createResource(String id) { return createResource(id, RES_NAME, RES_TYPE); } diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java b/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java index f61a0fa62..2bac6fdf5 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java @@ -73,7 +73,8 @@ public class MyModel { } /** - * @param id the id to set + * @param id + * the id to set */ public void setId(String id) { this.id = id; @@ -87,7 +88,8 @@ public class MyModel { } /** - * @param name the name to set + * @param name + * the name to set */ public void setName(String name) { this.name = name; @@ -101,7 +103,8 @@ public class MyModel { } /** - * @param type the type to set + * @param type + * the type to set */ public void setType(String type) { this.type = type; From 9d87fded75a2789b88bce8ee102174b1150c5959 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 19 Sep 2014 21:12:10 +0200 Subject: [PATCH 74/87] [Minor] set parent version to 1.0.0-SNAPSHOT --- pom.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5cddc9a21..34082d1d2 100644 --- a/pom.xml +++ b/pom.xml @@ -5,12 +5,11 @@ ch.eitchnet ch.eitchnet.parent - 1.0.0 + 1.0.0-SNAPSHOT ../ch.eitchnet.parent/pom.xml ch.eitchnet.xmlpers - 1.0.0-SNAPSHOT jar ch.eitchnet.xmlpers https://github.com/eitchnet/ch.eitchnet.xmlpers From cf1a6135350c6097aad14bfc98a93fdfe5f4d697 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 19 Sep 2014 21:53:09 +0200 Subject: [PATCH 75/87] [Minor] cleanup --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 34082d1d2..613eb07f3 100644 --- a/pom.xml +++ b/pom.xml @@ -44,7 +44,6 @@ - org.apache.maven.plugins maven-eclipse-plugin From c3fe4bdec64d1eb56c28f9df0e19a7c7bbc570c7 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sat, 20 Sep 2014 00:35:00 +0200 Subject: [PATCH 76/87] [Project] clean up --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 613eb07f3..1c3042f59 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,5 @@ - + + 4.0.0 From e1a3a4fca8458e5aa1c4cd57db26bb0a2852f26b Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 6 Feb 2015 22:26:03 +0100 Subject: [PATCH 77/87] [Minor] catch NPE in rollback --- .../impl/DefaultPersistenceTransaction.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java index 053337e60..1590aedba 100644 --- a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java +++ b/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java @@ -149,13 +149,15 @@ public class DefaultPersistenceTransaction implements PersistenceTransaction { long txDuration = end - this.startTime; long closeDuration = end - start; - this.txResult.clear(); - this.txResult.setState(this.state); - this.txResult.setStartTime(this.startTimeDate); - this.txResult.setTxDuration(txDuration); - this.txResult.setCloseDuration(closeDuration); - this.txResult.setRealm(this.realm.getRealmName()); - this.txResult.setModificationByKey(Collections. emptyMap()); + if (this.txResult != null) { + this.txResult.clear(); + this.txResult.setState(this.state); + this.txResult.setStartTime(this.startTimeDate); + this.txResult.setTxDuration(txDuration); + this.txResult.setCloseDuration(closeDuration); + this.txResult.setRealm(this.realm.getRealmName()); + this.txResult.setModificationByKey(Collections. emptyMap()); + } } } From 10554b53d38a8c11bb26f4fd8131776909093b3f Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Mon, 2 Mar 2015 13:43:06 +0100 Subject: [PATCH 78/87] [Project] Bumped version to 1.1.0-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 1c3042f59..1f768c0e9 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ ch.eitchnet ch.eitchnet.parent - 1.0.0-SNAPSHOT + 1.1.0-SNAPSHOT ../ch.eitchnet.parent/pom.xml From c1d77fee38c825158d3094d009b782cc9b31dfa9 Mon Sep 17 00:00:00 2001 From: Reto Breitenmoser Date: Mon, 2 Mar 2015 20:30:40 +0100 Subject: [PATCH 79/87] [Project] fixed version of utils --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 1f768c0e9..de63a547e 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ ch.eitchnet ch.eitchnet.parent - 1.1.0-SNAPSHOT + 1.0.0 ../ch.eitchnet.parent/pom.xml @@ -38,7 +38,7 @@ ch.eitchnet ch.eitchnet.utils - 1.0.0-SNAPSHOT + 1.0.0 From 7b6282dd2395ddc760ac89f7ebf33fc9ea4c1d88 Mon Sep 17 00:00:00 2001 From: Reto Breitenmoser Date: Mon, 2 Mar 2015 20:37:43 +0100 Subject: [PATCH 80/87] [Project] updated utils version --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index de63a547e..f5dd19ec4 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ ch.eitchnet ch.eitchnet.parent - 1.0.0 + 1.1.0-SNAPSHOT ../ch.eitchnet.parent/pom.xml @@ -38,7 +38,7 @@ ch.eitchnet ch.eitchnet.utils - 1.0.0 + 1.1.0-SNAPSHOT From dc7ff5582011c9188085db441a4ce75520747299 Mon Sep 17 00:00:00 2001 From: Reto Breitenmoser Date: Mon, 2 Mar 2015 20:42:41 +0100 Subject: [PATCH 81/87] [Project] updated to 1.0.0 utils --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index f5dd19ec4..de63a547e 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ ch.eitchnet ch.eitchnet.parent - 1.1.0-SNAPSHOT + 1.0.0 ../ch.eitchnet.parent/pom.xml @@ -38,7 +38,7 @@ ch.eitchnet ch.eitchnet.utils - 1.1.0-SNAPSHOT + 1.0.0 From 34c85825bfe16aa91ff319a5abe0feb11350a58b Mon Sep 17 00:00:00 2001 From: Reto Breitenmoser Date: Mon, 2 Mar 2015 21:36:33 +0100 Subject: [PATCH 82/87] [Project] updated version to 1.1.0-SNAPSHOT --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index de63a547e..f5dd19ec4 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ ch.eitchnet ch.eitchnet.parent - 1.0.0 + 1.1.0-SNAPSHOT ../ch.eitchnet.parent/pom.xml @@ -38,7 +38,7 @@ ch.eitchnet ch.eitchnet.utils - 1.0.0 + 1.1.0-SNAPSHOT From 2371cd78533b34484b050fd01fbfe2044bd0c94c Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Thu, 5 Mar 2015 22:42:49 +0100 Subject: [PATCH 83/87] [Minor] ch.eitchnet.utils version is a propery for easier versioning --- pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index f5dd19ec4..4374bde4f 100644 --- a/pom.xml +++ b/pom.xml @@ -16,6 +16,7 @@ UTF-8 + 1.1.0-SNAPSHOT @@ -38,7 +39,7 @@ ch.eitchnet ch.eitchnet.utils - 1.1.0-SNAPSHOT + ${eitchnet.utils.version} From f72ff76b406f2675cf194174aa35872d0c969ab6 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Sun, 19 Apr 2015 16:12:55 +0200 Subject: [PATCH 84/87] [Major] moved javanet.staxutils to ch.eitchnet.utils --- .../java/javanet/staxutils/Indentation.java | 36 -- .../staxutils/IndentingXMLStreamWriter.java | 370 ------------------ .../helpers/StreamWriterDelegate.java | 213 ---------- 3 files changed, 619 deletions(-) delete mode 100644 src/main/java/javanet/staxutils/Indentation.java delete mode 100644 src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java delete mode 100644 src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java diff --git a/src/main/java/javanet/staxutils/Indentation.java b/src/main/java/javanet/staxutils/Indentation.java deleted file mode 100644 index 844513789..000000000 --- a/src/main/java/javanet/staxutils/Indentation.java +++ /dev/null @@ -1,36 +0,0 @@ -package javanet.staxutils; - -/** - * Characters that represent line breaks and indentation. These are represented as String-valued JavaBean properties. - */ -@SuppressWarnings("nls") -public interface Indentation { - - /** Two spaces; the default indentation. */ - public static final String DEFAULT_INDENT = " "; - - /** - * Set the characters used for one level of indentation. The default is {@link #DEFAULT_INDENT}. "\t" is a popular - * alternative. - */ - void setIndent(String indent); - - /** The characters used for one level of indentation. */ - String getIndent(); - - /** - * "\n"; the normalized representation of end-of-line in XML. - */ - public static final String NORMAL_END_OF_LINE = "\n"; - - /** - * Set the characters that introduce a new line. The default is {@link #NORMAL_END_OF_LINE}. - * {@link IndentingXMLStreamWriter#getLineSeparator}() is a popular alternative. - */ - public void setNewLine(String newLine); - - /** The characters that introduce a new line. */ - String getNewLine(); - -} diff --git a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java b/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java deleted file mode 100644 index f4af62c62..000000000 --- a/src/main/java/javanet/staxutils/IndentingXMLStreamWriter.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright (c) 2006, John Kristian - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of StAX-Utils nor the names of its contributors - * may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - */ -package javanet.staxutils; - -import javanet.staxutils.helpers.StreamWriterDelegate; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -/** - * A filter that indents an XML stream. To apply it, construct a filter that contains another {@link XMLStreamWriter}, - * which you pass to the constructor. Then call methods of the filter instead of the contained stream. For example: - * - *

- * {@link XMLStreamWriter} stream = ...
- * stream = new {@link IndentingXMLStreamWriter}(stream);
- * stream.writeStartDocument();
- * ...
- * 
- * - *

- * The filter inserts characters to format the document as an outline, with nested elements indented. Basically, it - * inserts a line break and whitespace before: - *

    - *
  • each DTD, processing instruction or comment that's not preceded by data
  • - *
  • each starting tag that's not preceded by data
  • - *
  • each ending tag that's preceded by nested elements but not data
  • - *
- * This works well with 'data-oriented' XML, wherein each element contains either data or nested elements but not both. - * It can work badly with other styles of XML. For example, the data in a 'mixed content' document are apt to be - * polluted with indentation characters. - *

- * Indentation can be adjusted by setting the newLine and indent properties. But set them to whitespace only, for best - * results. Non-whitespace is apt to cause problems, for example when this class attempts to insert newLine before the - * root element. - * - * @author John Kristian - */ -@SuppressWarnings("nls") -public class IndentingXMLStreamWriter extends StreamWriterDelegate implements Indentation { - - public IndentingXMLStreamWriter(XMLStreamWriter out) { - this(out, DEFAULT_INDENT, NORMAL_END_OF_LINE); - } - - public IndentingXMLStreamWriter(XMLStreamWriter out, String indent) { - this(out, indent, NORMAL_END_OF_LINE); - } - - public IndentingXMLStreamWriter(XMLStreamWriter out, String indent, String newLine) { - super(out); - setIndent(indent); - setNewLine(newLine); - } - - /** How deeply nested the current scope is. The root element is depth 1. */ - private int depth = 0; // document scope - - /** stack[depth] indicates what's been written into the current scope. */ - private int[] stack = new int[] { 0, 0, 0, 0 }; // nothing written yet - - private static final int WROTE_MARKUP = 1; - - private static final int WROTE_DATA = 2; - - private String indent = DEFAULT_INDENT; - - private String newLine = NORMAL_END_OF_LINE; - - /** newLine followed by copies of indent. */ - private char[] linePrefix = null; - - @Override - public void setIndent(String indent) { - if (!indent.equals(this.indent)) { - this.indent = indent; - this.linePrefix = null; - } - } - - @Override - public String getIndent() { - return this.indent; - } - - @Override - public void setNewLine(String newLine) { - if (!newLine.equals(this.newLine)) { - this.newLine = newLine; - this.linePrefix = null; - } - } - - /** - * @return System.getProperty("line.separator"); or {@link #NORMAL_END_OF_LINE} if that fails. - */ - public static String getLineSeparator() { - try { - return System.getProperty("line.separator"); - } catch (SecurityException ignored) { - // - } - return NORMAL_END_OF_LINE; - } - - @Override - public String getNewLine() { - return this.newLine; - } - - @Override - public void writeStartDocument() throws XMLStreamException { - beforeMarkup(); - this.out.writeStartDocument(); - afterMarkup(); - } - - @Override - public void writeStartDocument(String version) throws XMLStreamException { - beforeMarkup(); - this.out.writeStartDocument(version); - afterMarkup(); - } - - @Override - public void writeStartDocument(String encoding, String version) throws XMLStreamException { - beforeMarkup(); - this.out.writeStartDocument(encoding, version); - afterMarkup(); - } - - @Override - public void writeDTD(String dtd) throws XMLStreamException { - beforeMarkup(); - this.out.writeDTD(dtd); - afterMarkup(); - } - - @Override - public void writeProcessingInstruction(String target) throws XMLStreamException { - beforeMarkup(); - this.out.writeProcessingInstruction(target); - afterMarkup(); - } - - @Override - public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - beforeMarkup(); - this.out.writeProcessingInstruction(target, data); - afterMarkup(); - } - - @Override - public void writeComment(String data) throws XMLStreamException { - beforeMarkup(); - this.out.writeComment(data); - afterMarkup(); - } - - @Override - public void writeEmptyElement(String localName) throws XMLStreamException { - beforeMarkup(); - this.out.writeEmptyElement(localName); - afterMarkup(); - } - - @Override - public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - beforeMarkup(); - this.out.writeEmptyElement(namespaceURI, localName); - afterMarkup(); - } - - @Override - public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - beforeMarkup(); - this.out.writeEmptyElement(prefix, localName, namespaceURI); - afterMarkup(); - } - - @Override - public void writeStartElement(String localName) throws XMLStreamException { - beforeStartElement(); - this.out.writeStartElement(localName); - afterStartElement(); - } - - @Override - public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - beforeStartElement(); - this.out.writeStartElement(namespaceURI, localName); - afterStartElement(); - } - - @Override - public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - beforeStartElement(); - this.out.writeStartElement(prefix, localName, namespaceURI); - afterStartElement(); - } - - @Override - public void writeCharacters(String text) throws XMLStreamException { - this.out.writeCharacters(text); - afterData(); - } - - @Override - public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - this.out.writeCharacters(text, start, len); - afterData(); - } - - @Override - public void writeCData(String data) throws XMLStreamException { - this.out.writeCData(data); - afterData(); - } - - @Override - public void writeEntityRef(String name) throws XMLStreamException { - this.out.writeEntityRef(name); - afterData(); - } - - @Override - public void writeEndElement() throws XMLStreamException { - beforeEndElement(); - this.out.writeEndElement(); - afterEndElement(); - } - - @Override - public void writeEndDocument() throws XMLStreamException { - try { - while (this.depth > 0) { - writeEndElement(); // indented - } - } catch (Exception ignored) { - ignored.printStackTrace(); - } - this.out.writeEndDocument(); - afterEndDocument(); - } - - /** Prepare to write markup, by writing a new line and indentation. */ - protected void beforeMarkup() { - int soFar = this.stack[this.depth]; - if ((soFar & WROTE_DATA) == 0 // no data in this scope - && (this.depth > 0 || soFar != 0)) // not the first line - { - try { - writeNewLine(this.depth); - if (this.depth > 0 && getIndent().length() > 0) { - afterMarkup(); // indentation was written - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** Note that markup or indentation was written. */ - protected void afterMarkup() { - this.stack[this.depth] |= WROTE_MARKUP; - } - - /** Note that data were written. */ - protected void afterData() { - this.stack[this.depth] |= WROTE_DATA; - } - - /** Prepare to start an element, by allocating stack space. */ - protected void beforeStartElement() { - beforeMarkup(); - if (this.stack.length <= this.depth + 1) { - // Allocate more space for the stack: - int[] newStack = new int[this.stack.length * 2]; - System.arraycopy(this.stack, 0, newStack, 0, this.stack.length); - this.stack = newStack; - } - this.stack[this.depth + 1] = 0; // nothing written yet - } - - /** Note that an element was started. */ - protected void afterStartElement() { - afterMarkup(); - ++this.depth; - } - - /** Prepare to end an element, by writing a new line and indentation. */ - protected void beforeEndElement() { - if (this.depth > 0 && this.stack[this.depth] == WROTE_MARKUP) { // but not data - try { - writeNewLine(this.depth - 1); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - } - } - - /** Note that an element was ended. */ - protected void afterEndElement() { - if (this.depth > 0) { - --this.depth; - } - } - - /** Note that a document was ended. */ - protected void afterEndDocument() { - if (this.stack[this.depth = 0] == WROTE_MARKUP) { // but not data - try { - writeNewLine(0); - } catch (Exception ignored) { - ignored.printStackTrace(); - } - } - this.stack[this.depth] = 0; // start fresh - } - - /** Write a line separator followed by indentation. */ - protected void writeNewLine(int indentation) throws XMLStreamException { - final int newLineLength = getNewLine().length(); - final int prefixLength = newLineLength + (getIndent().length() * indentation); - if (prefixLength > 0) { - if (this.linePrefix == null) { - this.linePrefix = (getNewLine() + getIndent()).toCharArray(); - } - while (prefixLength > this.linePrefix.length) { - // make linePrefix longer: - char[] newPrefix = new char[newLineLength + ((this.linePrefix.length - newLineLength) * 2)]; - System.arraycopy(this.linePrefix, 0, newPrefix, 0, this.linePrefix.length); - System.arraycopy(this.linePrefix, newLineLength, newPrefix, this.linePrefix.length, - this.linePrefix.length - newLineLength); - this.linePrefix = newPrefix; - } - this.out.writeCharacters(this.linePrefix, 0, prefixLength); - } - } - -} diff --git a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java b/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java deleted file mode 100644 index 9922aafa7..000000000 --- a/src/main/java/javanet/staxutils/helpers/StreamWriterDelegate.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2006, John Kristian - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * * Neither the name of StAX-Utils nor the names of its contributors - * may be used to endorse or promote products derived from this - * software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - * - */ -package javanet.staxutils.helpers; - -import javax.xml.namespace.NamespaceContext; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -/** - * Abstract class for writing filtered XML streams. This class provides methods that merely delegate to the contained - * stream. Subclasses should override some of these methods, and may also provide additional methods and fields. - * - * @author John Kristian - */ -public abstract class StreamWriterDelegate implements XMLStreamWriter { - - protected StreamWriterDelegate(XMLStreamWriter out) { - this.out = out; - } - - protected XMLStreamWriter out; - - @Override - public Object getProperty(String name) throws IllegalArgumentException { - return this.out.getProperty(name); - } - - @Override - public NamespaceContext getNamespaceContext() { - return this.out.getNamespaceContext(); - } - - @Override - public void setNamespaceContext(NamespaceContext context) throws XMLStreamException { - this.out.setNamespaceContext(context); - } - - @Override - public void setDefaultNamespace(String uri) throws XMLStreamException { - this.out.setDefaultNamespace(uri); - } - - @Override - public void writeStartDocument() throws XMLStreamException { - this.out.writeStartDocument(); - } - - @Override - public void writeStartDocument(String version) throws XMLStreamException { - this.out.writeStartDocument(version); - } - - @Override - public void writeStartDocument(String encoding, String version) throws XMLStreamException { - this.out.writeStartDocument(encoding, version); - } - - @Override - public void writeDTD(String dtd) throws XMLStreamException { - this.out.writeDTD(dtd); - } - - @Override - public void writeProcessingInstruction(String target) throws XMLStreamException { - this.out.writeProcessingInstruction(target); - } - - @Override - public void writeProcessingInstruction(String target, String data) throws XMLStreamException { - this.out.writeProcessingInstruction(target, data); - } - - @Override - public void writeComment(String data) throws XMLStreamException { - this.out.writeComment(data); - } - - @Override - public void writeEmptyElement(String localName) throws XMLStreamException { - this.out.writeEmptyElement(localName); - } - - @Override - public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException { - this.out.writeEmptyElement(namespaceURI, localName); - } - - @Override - public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - this.out.writeEmptyElement(prefix, localName, namespaceURI); - } - - @Override - public void writeStartElement(String localName) throws XMLStreamException { - this.out.writeStartElement(localName); - } - - @Override - public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException { - this.out.writeStartElement(namespaceURI, localName); - } - - @Override - public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException { - this.out.writeStartElement(prefix, localName, namespaceURI); - } - - @Override - public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException { - this.out.writeDefaultNamespace(namespaceURI); - } - - @Override - public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException { - this.out.writeNamespace(prefix, namespaceURI); - } - - @Override - public String getPrefix(String uri) throws XMLStreamException { - return this.out.getPrefix(uri); - } - - @Override - public void setPrefix(String prefix, String uri) throws XMLStreamException { - this.out.setPrefix(prefix, uri); - } - - @Override - public void writeAttribute(String localName, String value) throws XMLStreamException { - this.out.writeAttribute(localName, value); - } - - @Override - public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException { - this.out.writeAttribute(namespaceURI, localName, value); - } - - @Override - public void writeAttribute(String prefix, String namespaceURI, String localName, String value) - throws XMLStreamException { - this.out.writeAttribute(prefix, namespaceURI, localName, value); - } - - @Override - public void writeCharacters(String text) throws XMLStreamException { - this.out.writeCharacters(text); - } - - @Override - public void writeCharacters(char[] text, int start, int len) throws XMLStreamException { - this.out.writeCharacters(text, start, len); - } - - @Override - public void writeCData(String data) throws XMLStreamException { - this.out.writeCData(data); - } - - @Override - public void writeEntityRef(String name) throws XMLStreamException { - this.out.writeEntityRef(name); - } - - @Override - public void writeEndElement() throws XMLStreamException { - this.out.writeEndElement(); - } - - @Override - public void writeEndDocument() throws XMLStreamException { - this.out.writeEndDocument(); - } - - @Override - public void flush() throws XMLStreamException { - this.out.flush(); - } - - @Override - public void close() throws XMLStreamException { - this.out.close(); - } - -} From 6659b90b83aa253e79e9a705c42e9c0e3b3fd63c Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 8 Jul 2015 08:00:14 +0200 Subject: [PATCH 85/87] [Major] Removed redundant XmlPersistenceStreamWriter - Now SaxParser simply writes to XMLStreamWriter --- .../java/ch/eitchnet/xmlpers/api/FileIo.java | 3 +- .../ch/eitchnet/xmlpers/api/SaxParser.java | 3 +- .../api/XmlPersistenceStreamWriter.java | 88 ------------------- .../xmlpers/test/impl/BookSaxParser.java | 4 +- .../xmlpers/test/impl/MyModelSaxParser.java | 7 +- 5 files changed, 9 insertions(+), 96 deletions(-) delete mode 100644 src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java index 23f917e4f..9aaa97e45 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java @@ -77,10 +77,9 @@ public class FileIo { writer.writeStartDocument(DEFAULT_ENCODING, DEFAULT_XML_VERSION); // then delegate object writing to caller - XmlPersistenceStreamWriter xmlWriter = new XmlPersistenceStreamWriter(writer); SaxParser saxParser = ctx.getParserFactor().getSaxParser(); saxParser.setObject(ctx.getObject()); - saxParser.write(xmlWriter); + saxParser.write(writer); // and now end writer.writeEndDocument(); diff --git a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java index 82ea59631..352b43f33 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java +++ b/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java @@ -16,6 +16,7 @@ package ch.eitchnet.xmlpers.api; import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; import org.xml.sax.helpers.DefaultHandler; @@ -27,5 +28,5 @@ public interface SaxParser { public DefaultHandler getDefaultHandler(); - public void write(XmlPersistenceStreamWriter xmlWriter) throws XMLStreamException; + public void write(XMLStreamWriter xmlWriter) throws XMLStreamException; } \ No newline at end of file diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java b/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java deleted file mode 100644 index 182ad89c9..000000000 --- a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceStreamWriter.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2013 Robert von Burg - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package ch.eitchnet.xmlpers.api; - -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; - -/** - * @author Robert von Burg - * - */ -public class XmlPersistenceStreamWriter { - - private XMLStreamWriter writer; - - public XmlPersistenceStreamWriter(XMLStreamWriter writer) { - this.writer = writer; - } - - /** - * @param localName - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEmptyElement(java.lang.String) - */ - public void writeEmptyElement(String localName) throws XMLStreamException { - this.writer.writeEmptyElement(localName); - } - - /** - * @param localName - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeStartElement(java.lang.String) - */ - public void writeElement(String localName) throws XMLStreamException { - this.writer.writeStartElement(localName); - } - - /** - * Note: Don't call this method to close an element written by {@link #writeEmptyElement(String)} - * - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeEndElement() - */ - public void endElement() throws XMLStreamException { - this.writer.writeEndElement(); - } - - /** - * @param localName - * @param value - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeAttribute(java.lang.String, java.lang.String) - */ - public void writeAttribute(String localName, String value) throws XMLStreamException { - this.writer.writeAttribute(localName, value); - } - - /** - * @param data - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeCData(java.lang.String) - */ - public void writeCData(String data) throws XMLStreamException { - this.writer.writeCData(data); - } - - /** - * @param text - * @throws XMLStreamException - * @see javax.xml.stream.XMLStreamWriter#writeCharacters(java.lang.String) - */ - public void writeCharacters(String text) throws XMLStreamException { - this.writer.writeCharacters(text); - } -} diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java index 2a9338683..154df1afa 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java @@ -16,13 +16,13 @@ package ch.eitchnet.xmlpers.test.impl; import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; import ch.eitchnet.xmlpers.test.model.Book; /** @@ -51,7 +51,7 @@ public class BookSaxParser extends DefaultHandler implements SaxParser { @SuppressWarnings("nls") @Override - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + public void write(XMLStreamWriter writer) throws XMLStreamException { writer.writeEmptyElement("Book"); writer.writeAttribute("id", Long.toString(this.book.getId())); diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java index 858be533a..0cb2f0780 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java +++ b/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java @@ -16,13 +16,13 @@ package ch.eitchnet.xmlpers.test.impl; import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import ch.eitchnet.xmlpers.api.SaxParser; -import ch.eitchnet.xmlpers.api.XmlPersistenceStreamWriter; import ch.eitchnet.xmlpers.test.model.MyModel; import ch.eitchnet.xmlpers.test.model.MyParameter; @@ -47,9 +47,9 @@ class MyModelSaxParser extends DefaultHandler implements SaxParser { @SuppressWarnings("nls") @Override - public void write(XmlPersistenceStreamWriter writer) throws XMLStreamException { + public void write(XMLStreamWriter writer) throws XMLStreamException { - writer.writeElement("Resource"); + writer.writeStartElement("Resource"); writer.writeAttribute("id", this.resource.getId()); writer.writeAttribute("name", this.resource.getName()); writer.writeAttribute("type", this.resource.getType()); @@ -61,6 +61,7 @@ class MyModelSaxParser extends DefaultHandler implements SaxParser { writer.writeAttribute("type", param.getType()); writer.writeAttribute("value", param.getValue()); } + writer.writeEndElement(); } @SuppressWarnings("nls") From cc10f6f402c2bb43be768fa02b3a41eb16f9307a Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Wed, 10 Feb 2016 20:33:37 +0100 Subject: [PATCH 86/87] [Project] Moved everything to a sub directory --- LICENSE => ch.eitchnet.xmlpers/LICENSE | 0 README.md => ch.eitchnet.xmlpers/README.md | 0 pom.xml => ch.eitchnet.xmlpers/pom.xml | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/DomParser.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/FileDao.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/FileIo.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/IoMode.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/IoOperation.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java | 4 ++-- .../main/java/ch/eitchnet/xmlpers/api/ModificationResult.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java | 2 +- .../src}/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java | 0 .../java/ch/eitchnet/xmlpers/api/PersistenceConstants.java | 0 .../main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java | 0 .../ch/eitchnet/xmlpers/api/PersistenceContextFactory.java | 0 .../xmlpers/api/PersistenceContextFactoryDelegator.java | 0 .../main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java | 0 .../ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java | 0 .../main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java | 0 .../java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/api/SaxParser.java | 0 .../ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java | 0 .../main/java/ch/eitchnet/xmlpers/api/TransactionResult.java | 0 .../main/java/ch/eitchnet/xmlpers/api/TransactionState.java | 0 .../java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java | 0 .../ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java | 0 .../ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java | 0 .../eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java | 0 .../main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java | 0 .../main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java | 0 .../main/java/ch/eitchnet/xmlpers/objref/LockableObject.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java | 0 .../java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java | 0 .../main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/objref/RootRef.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java | 0 .../main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java | 0 .../src}/main/java/ch/eitchnet/xmlpers/util/DomUtil.java | 0 .../main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java | 0 .../ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java | 0 .../src}/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java | 0 .../src}/test/java/ch/eitchnet/xmlpers/test/LockingTest.java | 0 .../test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java | 0 .../java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java | 0 .../src}/test/java/ch/eitchnet/xmlpers/test/RealmTest.java | 0 .../java/ch/eitchnet/xmlpers/test/TransactionResultTest.java | 0 .../src}/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java | 2 +- .../ch/eitchnet/xmlpers/test/impl/BookContextFactory.java | 0 .../java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java | 0 .../java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java | 0 .../java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java | 0 .../ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java | 0 .../java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java | 0 .../ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java | 0 .../java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java | 0 .../java/ch/eitchnet/xmlpers/test/impl/TestConstants.java | 0 .../src}/test/java/ch/eitchnet/xmlpers/test/model/Book.java | 0 .../java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java | 0 .../test/java/ch/eitchnet/xmlpers/test/model/MyModel.java | 2 +- .../test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java | 0 {src => ch.eitchnet.xmlpers/src}/test/resources/log4j.xml | 0 63 files changed, 5 insertions(+), 5 deletions(-) rename LICENSE => ch.eitchnet.xmlpers/LICENSE (100%) rename README.md => ch.eitchnet.xmlpers/README.md (100%) rename pom.xml => ch.eitchnet.xmlpers/pom.xml (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/DomParser.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/FileDao.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/FileIo.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/IoMode.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/IoOperation.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java (98%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java (99%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/SaxParser.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/TransactionState.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/RootRef.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/util/DomUtil.java (100%) rename {src => ch.eitchnet.xmlpers/src}/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/LockingTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/RealmTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java (99%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/model/Book.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java (96%) rename {src => ch.eitchnet.xmlpers/src}/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java (100%) rename {src => ch.eitchnet.xmlpers/src}/test/resources/log4j.xml (100%) diff --git a/LICENSE b/ch.eitchnet.xmlpers/LICENSE similarity index 100% rename from LICENSE rename to ch.eitchnet.xmlpers/LICENSE diff --git a/README.md b/ch.eitchnet.xmlpers/README.md similarity index 100% rename from README.md rename to ch.eitchnet.xmlpers/README.md diff --git a/pom.xml b/ch.eitchnet.xmlpers/pom.xml similarity index 100% rename from pom.xml rename to ch.eitchnet.xmlpers/pom.xml diff --git a/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/DomParser.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/DomParser.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/FileDao.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/FileDao.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/FileIo.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/FileIo.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/IoMode.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/IoMode.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/IoOperation.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java similarity index 98% rename from src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java index fd6f117b4..7a114bb7a 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java +++ b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/MetadataDao.java @@ -149,7 +149,7 @@ public class MetadataDao { throw new IllegalArgumentException(msg); } - Set keySet = new HashSet(); + Set keySet = new HashSet<>(); File[] subTypeFiles = queryPath.listFiles(); for (File subTypeFile : subTypeFiles) { if (subTypeFile.isDirectory()) { @@ -179,7 +179,7 @@ public class MetadataDao { throw new IllegalArgumentException(msg); } - Set keySet = new HashSet(); + Set keySet = new HashSet<>(); File[] subTypeFiles = queryPath.listFiles(); for (File subTypeFile : subTypeFiles) { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ModificationResult.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java similarity index 99% rename from src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java index f5064db6e..493a749c8 100644 --- a/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java +++ b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ObjectDao.java @@ -114,7 +114,7 @@ public class ObjectDao { long removed = 0; - Set refs = new HashSet(); + Set refs = new HashSet<>(); typeRef.lock(); refs.add(typeRef); try { diff --git a/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/ParserFactory.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceConstants.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContext.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactory.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceContextFactoryDelegator.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManager.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceManagerLoader.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceRealm.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/PersistenceTransaction.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/SaxParser.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/TransactionCloseStrategy.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/TransactionResult.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/TransactionState.java diff --git a/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/api/XmlPersistenceException.java diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceManager.java diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceRealm.java diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/DefaultPersistenceTransaction.java diff --git a/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/impl/PathBuilder.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/IdOfSubTypeRef.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/IdOfTypeRef.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/LockableObject.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/ObjectRef.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/ObjectReferenceCache.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/RefNameCreator.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/RootRef.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/SubTypeRef.java diff --git a/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/objref/TypeRef.java diff --git a/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/util/AssertionUtil.java diff --git a/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/util/DomUtil.java diff --git a/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java b/ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java similarity index 100% rename from src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java rename to ch.eitchnet.xmlpers/src/main/java/ch/eitchnet/xmlpers/util/FilenameUtility.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/AbstractPersistenceTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/FileDaoTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/LockingTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoBookTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/ObjectDaoResourceTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/RealmTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/TransactionResultTest.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java similarity index 99% rename from src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java index 690cf4e6f..32af884e2 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java +++ b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/XmlTestMain.java @@ -89,7 +89,7 @@ public class XmlTestMain { Document document = docBuilder.parse(file); Element rootElement = document.getDocumentElement(); - List resources = new ArrayList(); + List resources = new ArrayList<>(); NodeList resElements = rootElement.getElementsByTagName("Resource"); for (int i = 0; i < resElements.getLength(); i++) { diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookContextFactory.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookDomParser.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookParserFactory.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/BookSaxParser.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelContextFactory.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelDomParser.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelParserFactory.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/MyModelSaxParser.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/impl/TestConstants.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/model/Book.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/Book.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/ModelBuilder.java diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java similarity index 96% rename from src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java index 2bac6fdf5..f8f90058a 100644 --- a/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java +++ b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/MyModel.java @@ -25,7 +25,7 @@ public class MyModel { private String id; private String name; private String type; - private Map parameters = new HashMap(); + private Map parameters = new HashMap<>(); /** * diff --git a/src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java b/ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java similarity index 100% rename from src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java rename to ch.eitchnet.xmlpers/src/test/java/ch/eitchnet/xmlpers/test/model/MyParameter.java diff --git a/src/test/resources/log4j.xml b/ch.eitchnet.xmlpers/src/test/resources/log4j.xml similarity index 100% rename from src/test/resources/log4j.xml rename to ch.eitchnet.xmlpers/src/test/resources/log4j.xml From 9d022dcd6fb9e91df981ddcae20b53f4785fdfb3 Mon Sep 17 00:00:00 2001 From: Robert von Burg Date: Fri, 24 Jun 2016 10:22:39 +0200 Subject: [PATCH 87/87] [Project] Removed .gitignore in prep for merge --- .gitignore | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 18d2ca6cd..000000000 --- a/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -target/ -.classpath -.project -.settings/