diff --git a/li.strolch.persistence.postgresql/.gitignore b/li.strolch.persistence.postgresql/.gitignore
new file mode 100644
index 000000000..b284c6517
--- /dev/null
+++ b/li.strolch.persistence.postgresql/.gitignore
@@ -0,0 +1,4 @@
+target/
+.project
+.settings
+.classpath
diff --git a/li.strolch.persistence.postgresql/LICENSE b/li.strolch.persistence.postgresql/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/li.strolch.persistence.postgresql/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/li.strolch.persistence.postgresql/README.md b/li.strolch.persistence.postgresql/README.md
new file mode 100644
index 000000000..4988ce20f
--- /dev/null
+++ b/li.strolch.persistence.postgresql/README.md
@@ -0,0 +1,72 @@
+li.strolch.persistence.postgresql
+=======================================================================
+
+[![Build Status](http://jenkins.eitchnet.ch/buildStatus/icon?job=li.strolch.persistence.postgresql)](http://jenkins.eitchnet.ch/view/strolch/job/li.strolch.persistence.postgresql/)
+
+PostgreSQL Persistence Implementation for Strolch
+
+Setup
+=======================================================================
+1. Install PostgreSQL version with at least version 9.1:
+ $ sudo aptitude install postgresql postgresql-client
+2. Set a password for user 'postgres'
+ $ sudo -u postgres psql postgres
+ postgres=# \password postgres
+3. Create the user and DB:
+ $ sudo -u postgres psql
+ $ postgres=#
+ create user testUser with password 'test';
+ create database testdb;
+ GRANT ALL PRIVILEGES ON DATABASE testdb to testuser;
+ GRANT CONNECT ON DATABASE testdb TO testuser ;
+
+ # For tests:
+ create user testUser with password 'test';
+ create database testdb;
+ GRANT ALL PRIVILEGES ON DATABASE testdb to testuser;
+ GRANT CONNECT ON DATABASE testdb TO testuser ;
+
+ create user testuser1 with password 'test';
+ create database testdb1;
+ GRANT ALL PRIVILEGES ON DATABASE testdb1 to testuser1;
+ GRANT CONNECT ON DATABASE testdb1 TO testuser1 ;
+
+ create user testuser2 with password 'test';
+ create database testdb2;
+ GRANT ALL PRIVILEGES ON DATABASE testdb2 to testuser2;
+ GRANT CONNECT ON DATABASE testdb2 TO testuser2 ;
+
+4. Added new component, setting properties for PostgreSQL DB:
+
+ PersistenceHandler
+ li.strolch.persistence.api.StrolchPersistenceHandler
+ li.strolch.persistence.postgresql.PostgreSqlPersistenceHandler
+
+ false
+ jdbc:postgresql://localhost/testdb
+ testUser
+ test
+
+
+
+5. Create tables, or allow strolch to due it for you.
+
+
+Appendix
+=======================================================================
+1. To drop the user and DB:
+ postgres=# revoke ALL PRIVILEGES ON DATABASE testdb from testuser;
+ postgres=# drop user testuser;
+ postgres=# drop database testdb;
+2. Create a database:
+ $ createdb -p 5432 -O drupal -U drupal -E UTF8 testingsiteone -T template0
+3. Dropping the database
+ $ dropdb -p 5432 -U drupal testingsiteone
+4. Dumping the database
+ $ pg_dump -p 5432 -h localhost -Fc -U drupal --no-owner testingsiteone > /tmp/testingsiteone_$(date +"%Y-%m-%d_%s").pgdump
+5. Restoring the database
+ $ pg_restore -p 5432 -h localhost -Fc -d testingsiteone -U drupal --no-owner < /tmp/path-to-the-file.pgdump
+
+References
+=======================================================================
+http://www.pixelite.co.nz/article/installing-and-configuring-postgresql-91-ubuntu-1204-local-drupal-development
\ No newline at end of file
diff --git a/li.strolch.persistence.postgresql/pom.xml b/li.strolch.persistence.postgresql/pom.xml
new file mode 100644
index 000000000..558f377b0
--- /dev/null
+++ b/li.strolch.persistence.postgresql/pom.xml
@@ -0,0 +1,102 @@
+
+
+
+ li.strolch
+ li.strolch.parent
+ 1.0.0-SNAPSHOT
+ ../li.strolch.parent/pom.xml
+
+
+ 4.0.0
+
+ li.strolch.persistence.postgresql
+
+ li.strolch.persistence.postgresql
+ PostgreSQL Persistence Implementation for Strolch
+
+ https://github.com/eitchnet/li.strolch.persistence.postgresql
+
+ 2011
+
+
+ Github Issues
+ https://github.com/eitchnet/li.strolch.persistence.postgresql/issues
+
+
+
+ scm:git:https://github.com/eitchnet/li.strolch.persistence.postgresql.git
+ scm:git:git@github.com:eitch/li.strolch.persistence.postgresql.git
+ https://github.com/eitchnet/li.strolch.persistence.postgresql
+
+
+
+
+
+ li.strolch
+ li.strolch.model
+
+
+ li.strolch
+ li.strolch.agent
+
+
+ org.postgresql
+ postgresql
+ 9.3-1100-jdbc41
+
+
+
+
+ li.strolch
+ li.strolch.testbase
+ test
+
+
+
+
+
+
+
+ src/main/resources
+ true
+
+ **/componentVersion.properties
+
+
+
+ src/main/resources
+ false
+
+ **/componentVersion.properties
+
+
+
+
+
+ org.codehaus.mojo
+ buildnumber-maven-plugin
+
+
+ org.apache.maven.plugins
+ maven-eclipse-plugin
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+ org.apache.maven.plugins
+ maven-site-plugin
+
+
+
+
\ No newline at end of file
diff --git a/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DaoCommand.java b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DaoCommand.java
new file mode 100644
index 000000000..a878f50c1
--- /dev/null
+++ b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DaoCommand.java
@@ -0,0 +1,26 @@
+/*
+ * 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 li.strolch.persistence.postgresql;
+
+import li.strolch.persistence.api.TransactionResult;
+
+/**
+ * @author Robert von Burg
+ */
+public interface DaoCommand {
+
+ public void doComand(TransactionResult txResult);
+}
diff --git a/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DbConnectionCheck.java b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DbConnectionCheck.java
new file mode 100644
index 000000000..8fa034e5d
--- /dev/null
+++ b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DbConnectionCheck.java
@@ -0,0 +1,72 @@
+/*
+ * 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 li.strolch.persistence.postgresql;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.text.MessageFormat;
+import java.util.Collection;
+import java.util.Map;
+
+import li.strolch.persistence.api.DbConnectionInfo;
+import li.strolch.runtime.configuration.StrolchConfigurationException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @author Robert von Burg
+ */
+public class DbConnectionCheck {
+
+ private static final Logger logger = LoggerFactory.getLogger(DbConnectionCheck.class);
+ private Map connetionInfoMap;
+
+ /**
+ * @param connetionInfoMap
+ */
+ public DbConnectionCheck(Map connetionInfoMap) {
+ this.connetionInfoMap = connetionInfoMap;
+ }
+
+ public void checkConnections() {
+ Collection values = this.connetionInfoMap.values();
+ for (DbConnectionInfo connectionInfo : values) {
+
+ String url = connectionInfo.getUrl();
+ String username = connectionInfo.getUsername();
+ String password = connectionInfo.getPassword();
+
+ try (Connection con = DriverManager.getConnection(url, username, password);
+ Statement st = con.createStatement();) {
+
+ try (ResultSet rs = st.executeQuery("select version()")) { //$NON-NLS-1$
+ if (rs.next()) {
+ logger.info(MessageFormat.format("Connected to: {0}", rs.getString(1))); //$NON-NLS-1$
+ }
+ }
+
+ } catch (SQLException e) {
+ String msg = "Failed to open DB connection to URL {0} due to: {1}"; //$NON-NLS-1$
+ msg = MessageFormat.format(msg, url, e.getMessage());
+ throw new StrolchConfigurationException(msg, e);
+ }
+ }
+ }
+}
diff --git a/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DbSchemaVersionCheck.java b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DbSchemaVersionCheck.java
new file mode 100644
index 000000000..7ad6bc8cd
--- /dev/null
+++ b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/DbSchemaVersionCheck.java
@@ -0,0 +1,205 @@
+/*
+ * 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 li.strolch.persistence.postgresql;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.text.MessageFormat;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Properties;
+
+import li.strolch.exception.StrolchException;
+import li.strolch.persistence.api.DbConnectionInfo;
+import li.strolch.runtime.configuration.ComponentConfiguration;
+import li.strolch.runtime.configuration.StrolchConfigurationException;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import ch.eitchnet.utils.dbc.DBC;
+import ch.eitchnet.utils.helper.FileHelper;
+
+/**
+ * @author Robert von Burg
+ */
+@SuppressWarnings(value = "nls")
+public class DbSchemaVersionCheck {
+
+ private static final String RESOURCE_DB_VERSION = "/db_version.properties";
+ private static final String PROP_DB_VERSION = "db_version";
+ private static final String PROP_ALLOW_SCHEMA_CREATION = "allowSchemaCreation";
+ private static final String PROP_ALLOW_SCHEMA_DROP = "allowSchemaDrop";
+
+ private static final Logger logger = LoggerFactory.getLogger(DbSchemaVersionCheck.class);
+ private Map connetionInfoMap;
+ private boolean allowSchemaCreation;
+ private boolean allowSchemaDrop;
+
+ /**
+ * @param connetionInfoMap
+ * @param componentConfiguration
+ */
+ public DbSchemaVersionCheck(Map connetionInfoMap,
+ ComponentConfiguration componentConfiguration) {
+ this.connetionInfoMap = connetionInfoMap;
+
+ this.allowSchemaCreation = componentConfiguration.getBoolean(PROP_ALLOW_SCHEMA_CREATION, Boolean.FALSE);
+ this.allowSchemaDrop = componentConfiguration.getBoolean(PROP_ALLOW_SCHEMA_DROP, Boolean.FALSE);
+ }
+
+ public void checkSchemaVersion() {
+
+ Collection values = this.connetionInfoMap.values();
+
+ for (DbConnectionInfo connectionInfo : values) {
+ String realm = connectionInfo.getRealm();
+ String url = connectionInfo.getUrl();
+ String username = connectionInfo.getUsername();
+ String password = connectionInfo.getPassword();
+
+ logger.info(MessageFormat.format("[{0}] Checking Schema version for: {1}@{2}", realm, username, url));
+
+ try (Connection con = DriverManager.getConnection(url, username, password);
+ Statement st = con.createStatement();) {
+
+ String expectedDbVersion = getExpectedDbVersion();
+
+ // first see if we have any schema
+ String msg = "select table_schema, table_name, table_type from information_schema.tables where table_name=''{0}'';";
+ String checkSchemaExistsSql = MessageFormat.format(msg, PROP_DB_VERSION);
+ try (ResultSet rs = st.executeQuery(checkSchemaExistsSql)) {
+ if (!rs.next()) {
+ createSchema(realm, expectedDbVersion, st);
+ } else {
+ checkCurrentVersion(realm, st, expectedDbVersion);
+ }
+ }
+
+ } catch (SQLException e) {
+ String msg = "Failed to open DB connection to URL {0} due to: {1}"; //$NON-NLS-1$
+ msg = MessageFormat.format(msg, url, e.getMessage());
+ throw new StrolchConfigurationException(msg, e);
+ }
+ }
+ }
+
+ private void checkCurrentVersion(String realm, Statement st, String expectedDbVersion) throws SQLException {
+ try (ResultSet rs = st.executeQuery("select id, version from db_version order by id desc;")) {
+ if (!rs.next()) {
+ createSchema(realm, expectedDbVersion, st);
+ } else {
+ String currentVersion = rs.getString(2);
+ if (expectedDbVersion.equals(currentVersion)) {
+ String msg = "[{0}] Schema version {1} is the current version. No changes needed.";
+ msg = MessageFormat.format(msg, realm, currentVersion);
+ logger.info(msg);
+ } else {
+ String msg = "[{0}] Schema version is not current. Need to upgrade from {1} to {2}";
+ msg = MessageFormat.format(msg, realm, currentVersion, expectedDbVersion);
+ logger.warn(msg);
+ upgradeSchema(realm, expectedDbVersion, st);
+ }
+ }
+ }
+ }
+
+ public static String getExpectedDbVersion() {
+ Properties dbVersionProps = new Properties();
+ try (InputStream stream = DbSchemaVersionCheck.class.getResourceAsStream(RESOURCE_DB_VERSION);) {
+ DBC.PRE.assertNotNull(
+ MessageFormat.format("Resource file with name {0} does not exist!", RESOURCE_DB_VERSION), stream);
+ dbVersionProps.load(stream);
+ } catch (IOException e) {
+ String msg = "Expected resource file {0} does not exist or is not a valid properties file: {1}";
+ msg = MessageFormat.format(msg, RESOURCE_DB_VERSION, e.getMessage());
+ throw new StrolchException(msg, e);
+ }
+ String dbVersion = dbVersionProps.getProperty(PROP_DB_VERSION);
+ String msg = "Missing property {0} in resource file {1}";
+ DBC.PRE.assertNotEmpty(MessageFormat.format(msg, PROP_DB_VERSION, RESOURCE_DB_VERSION), dbVersion);
+ return dbVersion;
+ }
+
+ public static String getSql(String dbVersion, String type) {
+ String schemaResourceS = MessageFormat.format("/db_schema_{0}_{1}.sql", dbVersion, type);
+ try (InputStream stream = DbSchemaVersionCheck.class.getResourceAsStream(schemaResourceS);) {
+ DBC.PRE.assertNotNull(
+ MessageFormat.format("Schema Resource file with name {0} does not exist!", schemaResourceS), stream);
+ return FileHelper.readStreamToString(stream);
+ } catch (IOException e) {
+ throw new StrolchException("Schema creation resource file is missing or could not be read: "
+ + schemaResourceS, e);
+ }
+ }
+
+ /**
+ * @param realm
+ * @param st
+ */
+ private void createSchema(String realm, String dbVersion, Statement st) {
+
+ if (!this.allowSchemaCreation) {
+ String msg = "[{0}] No schema exists, or is not valid. Schema generation is disabled, thus can not continue!";
+ msg = MessageFormat.format(msg, realm);
+ throw new StrolchConfigurationException(msg);
+ }
+
+ logger.info(MessageFormat.format("[{0}] Creating initial schema...", realm));
+
+ String sql = getSql(dbVersion, "initial");
+ try {
+ st.execute(sql);
+ } catch (SQLException e) {
+ logger.error("Failed to execute schema creation SQL: \n" + sql);
+ throw new StrolchException("Failed to execute schema generation SQL: " + e.getMessage(), e);
+ }
+
+ logger.info(MessageFormat.format("[{0}] Successfully created schema for version {1}", realm, dbVersion));
+ }
+
+ private void dropSchema(String realm, String dbVersion, Statement st) {
+
+ if (!this.allowSchemaDrop) {
+ String msg = "[{0}] Dropping Schema is disabled, but is required to upgrade current schema...";
+ msg = MessageFormat.format(msg, realm);
+ throw new StrolchConfigurationException(msg);
+ }
+
+ logger.info(MessageFormat.format("[{0}] Dropping existing schema...", realm));
+
+ String sql = getSql(dbVersion, "drop");
+ try {
+ st.execute(sql);
+ } catch (SQLException e) {
+ logger.error("Failed to execute schema drop SQL: \n" + sql);
+ throw new StrolchException("Failed to execute schema drop SQL: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * @param st
+ */
+ private void upgradeSchema(String realm, String dbVersion, Statement st) {
+ dropSchema(realm, dbVersion, st);
+ createSchema(realm, dbVersion, st);
+ }
+}
diff --git a/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlAuditDao.java b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlAuditDao.java
new file mode 100644
index 000000000..ad80954b2
--- /dev/null
+++ b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlAuditDao.java
@@ -0,0 +1,346 @@
+/*
+ * 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 li.strolch.persistence.postgresql;
+
+import java.sql.Date;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import li.strolch.model.audit.AccessType;
+import li.strolch.model.audit.Audit;
+import li.strolch.model.audit.AuditQuery;
+import li.strolch.model.audit.AuditVisitor;
+import li.strolch.persistence.api.AuditDao;
+import li.strolch.persistence.api.StrolchPersistenceException;
+import ch.eitchnet.utils.collections.DateRange;
+import ch.eitchnet.utils.helper.StringHelper;
+
+/**
+ * @author Robert von Burg
+ */
+public class PostgreSqlAuditDao implements AuditDao {
+
+ public static final String ID = "id";
+ public static final String ACCESS_TYPE = "access_type";
+ public static final String ACCESS_TYPE_TYPE = "::access_type";
+ public static final String ACTION = "action";
+ public static final String NEW_VERSION = "new_version";
+ public static final String ELEMENT_ACCESSED = "element_accessed";
+ public static final String ELEMENT_TYPE = "element_type";
+ public static final String DATE = "date";
+ public static final String LASTNAME = "lastname";
+ public static final String FIRSTNAME = "firstname";
+ public static final String USERNAME = "username";
+ public static final String FIELDS = StringHelper.commaSeparated(ID, USERNAME, FIRSTNAME, LASTNAME, DATE,
+ ELEMENT_TYPE, ELEMENT_ACCESSED, NEW_VERSION, ACTION, ACCESS_TYPE);
+ public static final String TABLE_NAME = "audits";
+
+ private PostgreSqlStrolchTransaction tx;
+
+ /**
+ * @param postgreSqlStrolchTransaction
+ */
+ public PostgreSqlAuditDao(PostgreSqlStrolchTransaction postgreSqlStrolchTransaction) {
+ this.tx = postgreSqlStrolchTransaction;
+ }
+
+ @Override
+ public boolean hasElement(String type, Long id) {
+ String sql = "select count(*) from " + TABLE_NAME + " where " + ELEMENT_TYPE + " = ? and " + ID + " = ?"; //$NON-NLS-1$
+ try (PreparedStatement statement = this.tx.getConnection().prepareStatement(sql)) {
+
+ statement.setString(1, type);
+ statement.setLong(2, id);
+
+ try (ResultSet result = statement.executeQuery()) {
+ result.next();
+ long numberOfElements = result.getLong(1);
+ if (numberOfElements == 0)
+ return false;
+ if (numberOfElements == 1)
+ return true;
+
+ String msg = MessageFormat.format("Non unique number of elements with type {0} and id {1}", type, id); //$NON-NLS-1$
+ throw new StrolchPersistenceException(msg);
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException("Failed to query size due to: " + e.getMessage(), e); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public long querySize(DateRange dateRange) {
+ String sql = "select count(*) from " + TABLE_NAME + " where " + DATE + " between ? and ?"; //$NON-NLS-1$
+ try (PreparedStatement statement = this.tx.getConnection().prepareStatement(sql)) {
+
+ statement.setDate(1, new Date(dateRange.getFromDate().getTime()), Calendar.getInstance());
+ statement.setDate(2, new Date(dateRange.getToDate().getTime()), Calendar.getInstance());
+
+ try (ResultSet result = statement.executeQuery()) {
+ result.next();
+ return result.getLong(1);
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException("Failed to query size due to: " + e.getMessage(), e); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public long querySize(String type, DateRange dateRange) {
+ String sql = "select count(*) from " + TABLE_NAME + " where " + ELEMENT_TYPE + " = ? and " + DATE + " between ? and ?"; //$NON-NLS-1$
+ try (PreparedStatement statement = this.tx.getConnection().prepareStatement(sql)) {
+
+ statement.setString(1, type);
+ statement.setDate(2, new Date(dateRange.getFromDate().getTime()), Calendar.getInstance());
+ statement.setDate(3, new Date(dateRange.getToDate().getTime()), Calendar.getInstance());
+
+ try (ResultSet result = statement.executeQuery()) {
+ result.next();
+ return result.getLong(1);
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException("Failed to query size due to: " + e.getMessage(), e); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public Set queryTypes() {
+ Set keySet = new HashSet<>();
+
+ String sql = "select distinct " + ELEMENT_TYPE + " from " + TABLE_NAME; //$NON-NLS-1$
+ try (PreparedStatement statement = this.tx.getConnection().prepareStatement(sql)) {
+ try (ResultSet result = statement.executeQuery()) {
+ while (result.next()) {
+ keySet.add(result.getString(ELEMENT_TYPE));
+ }
+ }
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException("Failed to query types due to: " + e.getMessage(), e); //$NON-NLS-1$
+ }
+
+ return keySet;
+ }
+
+ @Override
+ public Audit queryBy(String type, Long id) {
+
+ String sql = "select " + FIELDS + " from " + TABLE_NAME + " where " + ELEMENT_TYPE + " = ? and " + ID + " = ?"; //$NON-NLS-1$
+ try (PreparedStatement statement = this.tx.getConnection().prepareStatement(sql)) {
+
+ statement.setString(1, type);
+ statement.setLong(2, id);
+
+ try (ResultSet result = statement.executeQuery()) {
+ if (!result.next()) {
+ return null;
+ }
+ Audit audit = auditFrom(result);
+ if (result.next())
+ throw new StrolchPersistenceException("Non unique result for query: " + sql); //$NON-NLS-1$
+ return audit;
+ }
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException("Failed to query types due to: " + e.getMessage(), e); //$NON-NLS-1$
+ }
+ }
+
+ @Override
+ public List queryAll(String type, DateRange dateRange) {
+ List list = new ArrayList<>();
+ String sql = "select " + FIELDS + " from " + TABLE_NAME + " where " + ELEMENT_TYPE + " = ? and " + DATE + " between ? and ?"; //$NON-NLS-1$
+ try (PreparedStatement statement = this.tx.getConnection().prepareStatement(sql)) {
+
+ statement.setString(1, type);
+ statement.setDate(2, new Date(dateRange.getFromDate().getTime()), Calendar.getInstance());
+ statement.setDate(3, new Date(dateRange.getToDate().getTime()), Calendar.getInstance());
+
+ try (ResultSet result = statement.executeQuery()) {
+ while (result.next()) {
+ list.add(auditFrom(result));
+ }
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException("Failed to query types due to: " + e.getMessage(), e); //$NON-NLS-1$
+ }
+
+ return list;
+ }
+
+ @Override
+ public void save(Audit audit) {
+ String sql = "insert into " + TABLE_NAME + " (" + FIELDS + ") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?::access_type)"; //$NON-NLS-1$
+ try (PreparedStatement preparedStatement = this.tx.getConnection().prepareStatement(sql)) {
+
+ setAuditFields(audit, preparedStatement);
+
+ int count = preparedStatement.executeUpdate();
+ if (count != 1) {
+ throw new StrolchPersistenceException(MessageFormat.format(
+ "Expected to create 1 record, but created {0} for audit {2}", count, audit.getId())); //$NON-NLS-1$
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException(MessageFormat.format("Failed to update Audit {0} due to {1}", audit, //$NON-NLS-1$
+ e.getLocalizedMessage()), e);
+ }
+ }
+
+ @Override
+ public void saveAll(List audits) {
+ for (Audit audit : audits) {
+ save(audit);
+ }
+ }
+
+ @Override
+ public void update(Audit audit) {
+ String sql = "update " + TABLE_NAME + " set " + ID + " = ?, " + USERNAME + " = ?, " + FIRSTNAME + " = ?, "
+ + LASTNAME + " = ?, " + DATE + " = ?, " + ELEMENT_TYPE + " = ?, " + ELEMENT_ACCESSED + " = ?, "
+ + NEW_VERSION + " = ?, " + ACTION + " = ?, " + ACCESS_TYPE + " = ?::access_type where " + ID + " = ?"; //$NON-NLS-1$
+ try (PreparedStatement preparedStatement = this.tx.getConnection().prepareStatement(sql)) {
+
+ setAuditFields(audit, preparedStatement);
+ preparedStatement.setLong(11, audit.getId());
+
+ int count = preparedStatement.executeUpdate();
+ if (count != 1) {
+ throw new StrolchPersistenceException(MessageFormat.format(
+ "Expected to update 1 record, but updated {0} for audit {2}", count, audit.getId())); //$NON-NLS-1$
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException(MessageFormat.format("Failed to update Audit {0} due to {1}", audit, //$NON-NLS-1$
+ e.getLocalizedMessage()), e);
+ }
+ }
+
+ @Override
+ public void updateAll(List audits) {
+ for (Audit audit : audits) {
+ update(audit);
+ }
+ }
+
+ @Override
+ public void remove(Audit audit) {
+ String sql = "delete from " + TABLE_NAME + " where " + ID + " = ?"; //$NON-NLS-1$
+ try (PreparedStatement preparedStatement = this.tx.getConnection().prepareStatement(sql)) {
+
+ preparedStatement.setLong(1, audit.getId());
+
+ int count = preparedStatement.executeUpdate();
+ if (count != 1) {
+ String msg = "Expected to delete 1 audit with id {0} but deleted {1} elements!"; //$NON-NLS-1$
+ msg = MessageFormat.format(msg, audit.getId(), count);
+ throw new StrolchPersistenceException(msg);
+ }
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException(MessageFormat.format("Failed to remove {0} due to {2}", //$NON-NLS-1$
+ audit.getId(), e.getLocalizedMessage()), e);
+ }
+ }
+
+ @Override
+ public void removeAll(List audits) {
+ for (Audit audit : audits) {
+ remove(audit);
+ }
+ }
+
+ @Override
+ public long removeAll(String type, DateRange dateRange) {
+ String sql = "delete from " + TABLE_NAME + " where " + ELEMENT_TYPE + " = ? and " + DATE + " between ? and ?"; //$NON-NLS-1$
+ try (PreparedStatement preparedStatement = this.tx.getConnection().prepareStatement(sql)) {
+
+ preparedStatement.setString(1, type);
+ preparedStatement.setDate(2, new Date(dateRange.getFromDate().getTime()), Calendar.getInstance());
+ preparedStatement.setDate(3, new Date(dateRange.getToDate().getTime()), Calendar.getInstance());
+
+ int modCount = preparedStatement.executeUpdate();
+ return modCount;
+
+ } catch (SQLException e) {
+ throw new StrolchPersistenceException(MessageFormat.format("Failed to remove all elements due to {0}", //$NON-NLS-1$
+ e.getLocalizedMessage()), e);
+ }
+ }
+
+ @Override
+ public List doQuery(AuditQuery query, AuditVisitor auditVisitor) {
+
+ PostgreSqlAuditQueryVisitor queryVisitor = new PostgreSqlAuditQueryVisitor(FIELDS);
+ query.accept(queryVisitor);
+ return null;
+ }
+
+ private void setAuditFields(Audit audit, PreparedStatement ps) throws SQLException {
+
+ // 1 id = ?,
+ // 2 username = ?,
+ // 3 firstname = ?,
+ // 4 lastname = ?,
+ // 5 date = ?,
+ // 6 element_type = ?,
+ // 7 element_accessed = ?,
+ // 8 new_version = ?,
+ // 9 action = ?,
+ // 10 access_type = ?::access_type
+
+ ps.setLong(1, audit.getId());
+ ps.setString(2, audit.getUsername());
+ ps.setString(3, audit.getFirstname());
+ ps.setString(4, audit.getLastname());
+ ps.setDate(5, new Date(audit.getDate().getTime()), Calendar.getInstance());
+ ps.setString(6, audit.getElementType());
+ ps.setString(7, audit.getElementAccessed());
+
+ if (audit.getNewVersion() == null)
+ ps.setDate(8, null);
+ else
+ ps.setDate(8, new Date(audit.getNewVersion().getTime()), Calendar.getInstance());
+
+ ps.setString(9, audit.getAction());
+ ps.setString(10, audit.getAccessType().name());
+ }
+
+ private Audit auditFrom(ResultSet resultSet) throws SQLException {
+
+ Audit audit = new Audit();
+ audit.setId(resultSet.getLong(1));
+ audit.setUsername(resultSet.getString(2));
+ audit.setFirstname(resultSet.getString(3));
+ audit.setLastname(resultSet.getString(4));
+ audit.setDate(resultSet.getDate(5));
+ audit.setElementType(resultSet.getString(6));
+ audit.setElementAccessed(resultSet.getString(7));
+ audit.setNewVersion(resultSet.getDate(8));
+ audit.setAction(resultSet.getString(9));
+ audit.setAccessType(AccessType.valueOf(resultSet.getString(10)));
+ return audit;
+ }
+}
diff --git a/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlAuditQueryVisitor.java b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlAuditQueryVisitor.java
new file mode 100644
index 000000000..379c40407
--- /dev/null
+++ b/li.strolch.persistence.postgresql/src/main/java/li/strolch/persistence/postgresql/PostgreSqlAuditQueryVisitor.java
@@ -0,0 +1,160 @@
+/*
+ * 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 li.strolch.persistence.postgresql;
+
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+import li.strolch.model.audit.AccessType;
+import li.strolch.model.audit.ActionSelection;
+import li.strolch.model.audit.AuditQuery;
+import li.strolch.model.audit.AuditQueryVisitor;
+import li.strolch.model.audit.ElementSelection;
+import li.strolch.model.audit.IdentitySelection;
+import li.strolch.model.query.StringSelection;
+import ch.eitchnet.utils.StringMatchMode;
+
+/**
+ * @author Robert von Burg
+ */
+public class PostgreSqlAuditQueryVisitor implements AuditQueryVisitor {
+
+ protected StringBuilder sql;
+ protected StringBuilder sb;
+ protected List