From fa3f73a46151d06c4f80eb0c43d3eda6c23c3709 Mon Sep 17 00:00:00 2001
From: Thomas Lenz <tlenz@iaik.tugraz.at>
Date: Tue, 15 Sep 2015 12:55:30 +0200
Subject: [PATCH 1/3] fix problems with OracleDB and configuration storage
 implementation

---
 .../config/ConfigurationProvider.java              |   7 +
 .../validation/oa/OAPVP2ConfigValidation.java      |   6 +-
 .../moa-id-configtool.properties                   |   1 +
 .../data/deploy/conf/moa-id/moa-id.properties      |   1 +
 .../PropertyBasedAuthConfigurationProvider.java    |  12 +-
 .../id/storage/AuthenticationSessionStoreage.java  | 569 ++++++++++++---------
 .../main/resources/moaid.configuration.beans.xml   |   2 +-
 .../config/persistence/MOAIDConfiguration.java     |  12 +
 .../config/persistence/MOAIDConfigurationImpl.java | 110 ++--
 .../moa/id/commons/db/MOASessionDBUtils.java       |  10 +-
 .../moa/id/commons/db/NewConfigurationDBRead.java  |   7 +-
 .../db/dao/config/DatabaseConfigPropertyImpl.java  |  35 +-
 .../src/main/resources/moaid.migration.beans.xml   |   2 +-
 13 files changed, 494 insertions(+), 280 deletions(-)

diff --git a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/config/ConfigurationProvider.java b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/config/ConfigurationProvider.java
index 849e819..e2a55db 100644
--- a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/config/ConfigurationProvider.java
+++ b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/config/ConfigurationProvider.java
@@ -188,6 +188,13 @@ public class ConfigurationProvider {
 	
 	
 	/**
+	 * @return the props
+	 */
+	public Properties getConfigurationProperties() {
+		return props;
+	}
+
+	/**
 	 * @return the deprecatedDBWrite
 	 */
 	public FileBasedUserConfiguration getUserManagement() {
diff --git a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/validation/oa/OAPVP2ConfigValidation.java b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/validation/oa/OAPVP2ConfigValidation.java
index 18452ed..35b6927 100644
--- a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/validation/oa/OAPVP2ConfigValidation.java
+++ b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/validation/oa/OAPVP2ConfigValidation.java
@@ -76,7 +76,11 @@ public class OAPVP2ConfigValidation {
 			
 			else {
 				try {
-					Map<String, String> oa = ConfigurationProvider.getInstance().getDbRead().getOnlineApplicationKeyValueWithId(oaID);
+					//OracleDB does not allow the selection of a lob in SQL where expression  
+					String dbDriver = ConfigurationProvider.getInstance().getConfigurationProperties().getProperty("hibernate.connection.driver_class");
+					boolean backupVersion = MiscUtil.isNotEmpty(dbDriver) && dbDriver.startsWith("oracle.jdbc.");
+
+					Map<String, String> oa = ConfigurationProvider.getInstance().getDbRead().getOnlineApplicationKeyValueWithId(oaID, backupVersion);
 					if (oa != null && 
 							MiscUtil.isNotEmpty(oa.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE))) {
 						certSerialized = Base64Utils.decode(oa.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE), false);
diff --git a/id/server/data/deploy/conf/moa-id-configuration/moa-id-configtool.properties b/id/server/data/deploy/conf/moa-id-configuration/moa-id-configtool.properties
index 9a3b367..825a9f1 100644
--- a/id/server/data/deploy/conf/moa-id-configuration/moa-id-configtool.properties
+++ b/id/server/data/deploy/conf/moa-id-configuration/moa-id-configtool.properties
@@ -35,6 +35,7 @@ dbcp.maxWaitMillis=-1
 dbcp.testOnBorrow=true
 dbcp.testOnReturn=false
 dbcp.testWhileIdle=false
+dbcp.validationQuery=SELECT 1
 
 ##Mail
 general.mail.host=smtp.localhost...
diff --git a/id/server/data/deploy/conf/moa-id/moa-id.properties b/id/server/data/deploy/conf/moa-id/moa-id.properties
index 66f9afa..49e69c5 100644
--- a/id/server/data/deploy/conf/moa-id/moa-id.properties
+++ b/id/server/data/deploy/conf/moa-id/moa-id.properties
@@ -107,6 +107,7 @@ configuration.dbcp.maxWaitMillis=-1
 configuration.dbcp.testOnBorrow=true
 configuration.dbcp.testOnReturn=false
 configuration.dbcp.testWhileIdle=false
+configuration.dbcp.validationQuery=SELECT 1
 
 #
 #Hibnerate configuration for MOA-ID 2.0 advanced statistic logging
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java
index 190c5f0..6458314 100644
--- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java
+++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java
@@ -980,9 +980,17 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide
 	 * @return the requested online application or {@code null}
 	 */
 	public Map<String, String> getActiveOnlineApplication(String id) {
-		Logger.trace("Get active OnlineApplication with ID " + id + " from database.");		
+		Logger.trace("Get active OnlineApplication with ID " + id + " from database.");
+		Map<String, String> oaConfig = null;
 		try {
-			Map<String, String> oaConfig = configuration.getOnlineApplication(id);
+			//OracleDB does not allow the selection of a lob in SQL where expression  
+			String dbDriver = properties.getProperty("configuration.hibernate.connection.driver_class");
+			if (MiscUtil.isNotEmpty(dbDriver) && dbDriver.startsWith("oracle.jdbc."))
+				oaConfig = configuration.getOnlineApplicationBackupVersion(id);
+			
+			else
+				oaConfig = configuration.getOnlineApplication(id);
+									
 			if (oaConfig != null) {
 				String isActiveString = oaConfig.get(MOAIDConfigurationConstants.SERVICE_ISACTIVE);
 				if (isActiveString != null && Boolean.valueOf(isActiveString))
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java
index 4b4b5dd..829383c 100644
--- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java
+++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java
@@ -206,26 +206,34 @@ public class AuthenticationSessionStoreage {
 		Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getSessionWithID");
-			  query.setParameter("sessionid", moaSessionID);
-			  result = query.list();
-
-		  
-			  Logger.trace("Found entries: " + result.size());
+		  Transaction tx = null;
+		  try {
+			  synchronized (session) {
+				  
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getSessionWithID");
+				  query.setParameter("sessionid", moaSessionID);
+				  result = query.list();
+	
 			  
-			  //Assertion requires an unique artifact
-			  if (result.size() != 1) {
-				 Logger.trace("No entries found.");
-			   	throw new MOADatabaseException("No session found with this sessionID");
+				  Logger.trace("Found entries: " + result.size());
+				  
+				  //Assertion requires an unique artifact
+				  if (result.size() != 1) {
+					 Logger.trace("No entries found.");
+				   	throw new MOADatabaseException("No session found with this sessionID");
+				  }
+				  
+				 AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0);			 
+				 tx.commit();
+				 cleanDelete(dbsession);			
 			  }
 			  
-			 AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0);			 
-			 session.getTransaction().commit();			  
-			 cleanDelete(dbsession);			
+		  } catch (Exception e) {
+			  if (tx != null && !tx.wasCommitted())
+				  tx.rollback();
+			  throw e;
+			  
 		  }
 				
 	}
@@ -290,28 +298,36 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getSessionWithSSOID");
-			  query.setParameter("sessionid", SSOSessionID);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {		  
+			  synchronized (session) {
+
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getSessionWithSSOID");
+				  query.setParameter("sessionid", SSOSessionID);
+				  result = query.list();
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
+				  //send transaction
+				  tx.commit();
+				  
+			  }
 		  
-		  Logger.trace("Found entries: " + result.size());
+			  Logger.trace("Found entries: " + result.size());
 		  
-		  //Assertion requires an unique artifact
-		  if (result.size() != 1) {
-			 Logger.trace("No entries found.");
-			 return null;
+			  //Assertion requires an unique artifact
+			  if (result.size() != 1) {
+				  Logger.trace("No entries found.");
+				  return null;
 					 
-		  } else {
-			  return result.get(0).getSessionid();
+			  } else {
+				  return result.get(0).getSessionid();
 			 
-		  }		  
+			  }
+		  } catch (Exception e) {
+			  if (tx != null && !tx.wasCommitted())
+				  tx.rollback();
+			  throw e;
+		  }
 	}
 	
 	public static boolean isSSOSession(String sessionID) throws MOADatabaseException {
@@ -331,27 +347,33 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getSessionWithSSOID");
-			  query.setParameter("sessionid", SSOId);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {	
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getSessionWithSSOID");
+				  query.setParameter("sessionid", SSOId);
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
+			  
+			  Logger.trace("Found entries: " + result.size());
 			  
-			  //send transaction
-			  session.getTransaction().commit();
+			  //Assertion requires an unique artifact
+			  if (result.size() != 1) {
+				 Logger.trace("No entries found.");
+				 return null;
+						 
+			  } else {
+				  return result.get(0);
+			  }
+		  } catch (Exception e) {
+			  if (tx != null && !tx.wasCommitted())
+				  tx.rollback();
+			  throw e;
 		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() != 1) {
-			 Logger.trace("No entries found.");
-			 return null;
-					 
-		  } else {
-			  return result.get(0);
-		  }		
 	}
 	
 	public static void addSSOInformation(String moaSessionID, String SSOSessionID, 
@@ -453,13 +475,15 @@ public class AuthenticationSessionStoreage {
 			
 		} catch(HibernateException e) {
 	  		Logger.warn("Error during database saveOrUpdate. Rollback.", e);
-	  		 tx.rollback();
-	  		 throw new AuthenticationException("SSO Session information can not be stored!  --> SSO is deactivated", null);	
-	  	 }
+	  		if (tx != null && !tx.wasCommitted())
+	  			tx.rollback();
+	  		throw new AuthenticationException("SSO Session information can not be stored!  --> SSO is deactivated", null);	
+	  	}
 	}
 
 	public static List<OASessionStore> getAllActiveOAFromMOASession(AuthenticationSession moaSession) {
 		MiscUtil.assertNotNull(moaSession, "MOASession");
+		Session session = null;
 		
 		try {
 			List<OASessionStore> oas = new ArrayList<OASessionStore>();
@@ -467,7 +491,7 @@ public class AuthenticationSessionStoreage {
 			AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false);
 			oas.addAll(dbsession.getActiveOAsessions());
 			
-			Session session = MOASessionDBUtils.getCurrentSession();
+			session = MOASessionDBUtils.getCurrentSession();
 			session.getTransaction().commit();
 			
 			return oas;
@@ -475,6 +499,14 @@ public class AuthenticationSessionStoreage {
 		} catch (MOADatabaseException e) {
 			Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e);
 			
+		} catch (Exception e) {
+			if (session != null && session.getTransaction() != null 
+					&& !session.getTransaction().wasCommitted()) {
+				session.getTransaction().rollback();
+				throw e;
+				
+			}
+			
 		}
 				
 		return null;
@@ -482,13 +514,13 @@ public class AuthenticationSessionStoreage {
 	
 	public static List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) {
 		MiscUtil.assertNotNull(moaSession, "MOASession");
-		
+		Session session = null;
 		try {
 			List<InterfederationSessionStore> idps = new ArrayList<InterfederationSessionStore>();			
 			AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false);
 			idps.addAll(dbsession.getInderfederation());
 			
-			Session session = MOASessionDBUtils.getCurrentSession();
+			session = MOASessionDBUtils.getCurrentSession();
 			session.getTransaction().commit();
 			
 			return idps;
@@ -496,6 +528,14 @@ public class AuthenticationSessionStoreage {
 		} catch (MOADatabaseException e) {
 			Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e);
 			
+		} catch (Exception e) {
+			if (session != null && session.getTransaction() != null 
+					&& !session.getTransaction().wasCommitted()) {
+				session.getTransaction().rollback();
+				throw e;
+				
+			}
+			
 		}
 				
 		return null;
@@ -507,35 +547,42 @@ public class AuthenticationSessionStoreage {
 		  Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " 
 				  + oaID + " from database.");
 		  Session session = MOASessionDBUtils.getCurrentSession();
-
-		  List<AuthenticatedSessionStore> result;
+		  Transaction tx = null;
 		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID");
-			  query.setParameter("oaID", oaID);
-			  query.setParameter("nameID", userNameID);
-			  result = query.list();
+		  List<AuthenticatedSessionStore> result = null;;
+		  try {  
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID");
+				  query.setParameter("oaID", oaID);
+				  query.setParameter("nameID", userNameID);
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() != 1) {
-			 Logger.trace("No unique entry found.");
-		   	 return null;
-		   	
-		  }
-		try {  		  
-			return  decryptSession(result.get(0));
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() != 1) {
+				 Logger.trace("No unique entry found.");
+			   	 return null;
+			   	
+			  }
+			  		  
+			  return  decryptSession(result.get(0));
 			
 		} catch (BuildException e) {
-			Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e);
+			Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e);			
 			return null;
+			
+		} catch (Exception e) {
+			if (tx != null && !tx.wasCommitted())
+				tx.rollback();
+			throw e;
 		}
+		
 	}
 	
 	public static OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID, String protocolType) {
@@ -547,29 +594,36 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol");
-			  query.setParameter("sessionID", moaSession.getSessionID());
-			  query.setParameter("oaID", oaID);
-			  query.setParameter("protocol", protocolType);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol");
+				  query.setParameter("sessionID", moaSession.getSessionID());
+				  query.setParameter("oaID", oaID);
+				  query.setParameter("protocol", protocolType);
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() == 0) {
-			 Logger.trace("No entries found.");
-		   	 return null;
-		   	
-		  }
-		  
-		  return  result.get(0).getActiveOAsessions().get(0);
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() == 0) {
+				 Logger.trace("No entries found.");
+			   	 return null;
+			   	
+			  }
+			  
+			  return  result.get(0).getActiveOAsessions().get(0);
+			  
+		  } catch (Exception e) {
+				if (tx != null && !tx.wasCommitted())
+					tx.rollback();
+				throw e;
+			}
 	}
 	
 	public static String getPendingRequestID(String sessionID) {
@@ -584,6 +638,7 @@ public class AuthenticationSessionStoreage {
 	}
 	
 	public static AuthenticationSession getSessionWithPendingRequestID(String pedingRequestID) {
+		Transaction tx = null;
 		try {
 			  MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID");	  
 			  Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database.");
@@ -592,13 +647,13 @@ public class AuthenticationSessionStoreage {
 			  List<AuthenticatedSessionStore> result;
 			  
 			  synchronized (session) {
-				  session.beginTransaction();
+				  tx  = session.beginTransaction();
 				  Query query = session.getNamedQuery("getSessionWithPendingRequestID");
 				  query.setParameter("sessionid", pedingRequestID);
 				  result = query.list();
 				  
 				  //send transaction
-				  session.getTransaction().commit();
+				  tx.commit();
 			  }
 			  
 			  Logger.trace("Found entries: " + result.size());
@@ -613,8 +668,13 @@ public class AuthenticationSessionStoreage {
 			  								
 		} catch (Throwable e) {
 			Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID);
+			
+			if (tx != null && !tx.wasCommitted())
+				tx.rollback();
+			
 			return null;
-		}
+			
+		} 
 	}
 	
 	public static boolean deleteSessionWithPendingRequestID(String id) {
@@ -623,34 +683,39 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getSessionWithPendingRequestID");
-			  query.setParameter("sessionid", id);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getSessionWithPendingRequestID");
+				  query.setParameter("sessionid", id);
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() != 1) {
-			 Logger.trace("No entries found.");
-			 return false;
-					 
-		  } else {
-			  cleanDelete(result.get(0));
-			  return true;
-		  }
-		
-		
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() != 1) {
+				 Logger.trace("No entries found.");
+				 return false;
+						 
+			  } else {
+				  cleanDelete(result.get(0));
+				  return true;
+			  }
+		  } catch (Exception e) {
+				if (tx != null && !tx.wasCommitted())
+					tx.rollback();
+				throw e;
+		  }		
 	}
 			
 	public static AuthenticationSession getSessionWithUserNameID(String nameID) {
 		
+		Transaction tx = null;
 		try {
 			  MiscUtil.assertNotNull(nameID, "nameID");	  
 			  Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database.");
@@ -659,13 +724,13 @@ public class AuthenticationSessionStoreage {
 			  List<AuthenticatedSessionStore> result;
 			  
 			  synchronized (session) {
-				  session.beginTransaction();
+				  tx  = session.beginTransaction();
 				  Query query = session.getNamedQuery("getMOAISessionWithUserNameID");
 				  query.setParameter("usernameid", StringEscapeUtils.escapeHtml(nameID));
 				  result = query.list();
 				  
 				  //send transaction
-				  session.getTransaction().commit();
+				  tx.commit();
 			  }
 			  
 			  Logger.trace("Found entries: " + result.size());
@@ -679,7 +744,9 @@ public class AuthenticationSessionStoreage {
 			  return decryptSession(result.get(0));
 											
 		} catch (Throwable e) {
-			Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID);
+			Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID);			
+			if (tx != null && !tx.wasCommitted())
+				tx.rollback();
 			return null;
 		}
 		
@@ -691,27 +758,33 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID");
-			  query.setParameter("sessionID", sessionID);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID");
+				  query.setParameter("sessionID", sessionID);
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() == 0) {
-			 Logger.trace("No entries found.");
-		   	return null;
-		   	
-		  }
-		  
-		  return result.get(0).getInderfederation().get(0);
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() == 0) {
+				 Logger.trace("No entries found.");
+			   	return null;
+			   	
+			  }
+			  
+			  return result.get(0).getInderfederation().get(0);
+		} catch (Exception e) {
+			if (tx != null && !tx.wasCommitted())
+				tx.rollback();
+			throw e;
+		}	
 	}
 	
 	public static InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID, String idpID) {
@@ -721,28 +794,34 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID");
-			  query.setParameter("sessionID", sessionID);
-			  query.setParameter("idpID", idpID);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {		  
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID");
+				  query.setParameter("sessionID", sessionID);
+				  query.setParameter("idpID", idpID);
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() == 0) {
-			 Logger.trace("No entries found.");
-		   	return null;
-		   	
-		  }
-		  
-		  return result.get(0).getInderfederation().get(0);
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() == 0) {
+				 Logger.trace("No entries found.");
+			   	return null;
+			   	
+			  }
+			  
+			  return result.get(0).getInderfederation().get(0);
+		  } catch (Exception e) {
+				if (tx != null && !tx.wasCommitted())
+					tx.rollback();
+				throw e;
+		  }	
 	}
 	
 	public static String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException {		
@@ -847,27 +926,33 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List<AuthenticatedSessionStore> result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID");
-			  query.setParameter("sessionID", moaSession.getSessionID());
-			  result = query.list();
+		  Transaction tx = null;
+		  try {
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID");
+				  query.setParameter("sessionID", moaSession.getSessionID());
+				  result = query.list();
+				  
+				  //send transaction
+				  tx.commit();
+			  }
 			  
-			  //send transaction
-			  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() == 0) {
-			 Logger.trace("No entries found.");
-		   	return null;
-		   	
-		  }
-		  
-		  return result.get(0).getInderfederation().get(0);
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() == 0) {
+				 Logger.trace("No entries found.");
+			   	return null;
+			   	
+			  }
+			  
+			  return result.get(0).getInderfederation().get(0);
+		} catch (Exception e) {
+			if (tx != null && !tx.wasCommitted())
+				tx.rollback();
+			throw e;
+		}	
 	}
 	
 	/**
@@ -930,28 +1015,34 @@ public class AuthenticationSessionStoreage {
 		
 		List<AuthenticatedSessionStore> results;
 		Session session = MOASessionDBUtils.getCurrentSession();
-		
-		synchronized (session) {			
-			session.beginTransaction();
-			Query query = session.getNamedQuery("getMOAISessionsWithTimeOut");
-			query.setTimestamp("timeoutcreate", expioredatecreate);
-			query.setTimestamp("timeoutupdate", expioredateupdate);
-			results = query.list();
-			session.getTransaction().commit();
-		}
-		
-		if (results.size() != 0) {
-			for(AuthenticatedSessionStore result : results) {
-				try { 
-					cleanDelete(result);
-					Logger.info("Authenticated session with sessionID=" + result.getSessionid() 
-							+ " after session timeout.");
-				
-				} catch (HibernateException e){
-					Logger.warn("Authenticated session with sessionID=" + result.getSessionid() 
-							+ " not removed after timeout! (Error during Database communication)", e);
-				}
-			}	
+		Transaction tx = null;
+		try {
+			synchronized (session) {			
+				tx = session.beginTransaction();
+				Query query = session.getNamedQuery("getMOAISessionsWithTimeOut");
+				query.setTimestamp("timeoutcreate", expioredatecreate);
+				query.setTimestamp("timeoutupdate", expioredateupdate);
+				results = query.list();
+				tx.commit();
+			}
+			
+			if (results.size() != 0) {
+				for(AuthenticatedSessionStore result : results) {
+					try { 
+						cleanDelete(result);
+						Logger.info("Authenticated session with sessionID=" + result.getSessionid() 
+								+ " after session timeout.");
+					
+					} catch (HibernateException e){
+						Logger.warn("Authenticated session with sessionID=" + result.getSessionid() 
+								+ " not removed after timeout! (Error during Database communication)", e);
+					}
+				}	
+			}
+		} catch (Exception e) {
+			if (tx != null && !tx.wasCommitted())
+				tx.rollback();
+			throw e;
 		}	
 	}
 	
@@ -1004,26 +1095,32 @@ public class AuthenticationSessionStoreage {
 		  Session session = MOASessionDBUtils.getCurrentSession();
 		  
 		  List result;
-		  
-		  synchronized (session) {
-			  session.beginTransaction();
-			  Query query = session.getNamedQuery("getSessionWithID");
-			  query.setParameter("sessionid", sessionID);
-			  result = query.list();
+		  Transaction tx = null;
+		  try {
+			  synchronized (session) {
+				  tx = session.beginTransaction();
+				  Query query = session.getNamedQuery("getSessionWithID");
+				  query.setParameter("sessionid", sessionID);
+				  result = query.list();
+				  
+				  //send transaction
+				  if (commit)
+					  tx.commit();
+			  }
 			  
-			  //send transaction
-			  if (commit)
-				  session.getTransaction().commit();
-		  }
-		  
-		  Logger.trace("Found entries: " + result.size());
-		  
-		  //Assertion requires an unique artifact
-		  if (result.size() != 1) {
-			 Logger.trace("No entries found.");
-		   	throw new MOADatabaseException("No session found with this sessionID");
-		  }
-		  
-		  return (AuthenticatedSessionStore) result.get(0);
+			  Logger.trace("Found entries: " + result.size());
+			  
+			  //Assertion requires an unique artifact
+			  if (result.size() != 1) {
+				 Logger.trace("No entries found.");
+			   	throw new MOADatabaseException("No session found with this sessionID");
+			  }
+			  
+			  return (AuthenticatedSessionStore) result.get(0);
+		  } catch (Exception e) {
+				if (tx != null && !tx.wasCommitted() && commit)
+					tx.rollback();
+				throw e;
+		}	
 	}
 }
diff --git a/id/server/idserverlib/src/main/resources/moaid.configuration.beans.xml b/id/server/idserverlib/src/main/resources/moaid.configuration.beans.xml
index 206fde8..7e319e2 100644
--- a/id/server/idserverlib/src/main/resources/moaid.configuration.beans.xml
+++ b/id/server/idserverlib/src/main/resources/moaid.configuration.beans.xml
@@ -29,7 +29,7 @@
 		<property name="testOnBorrow" value="${configuration.dbcp.testOnBorrow}" />
 		<property name="testOnReturn" value="${configuration.dbcp.testOnReturn}" />
 		<property name="testWhileIdle" value="${configuration.dbcp.testWhileIdle}" />
-		<property name="validationQuery" value="SELECT 1" />
+		<property name="validationQuery" value="${configuration.dbcp.validationQuery}" />
 	</bean>
 	
 	<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfiguration.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfiguration.java
index 223f29a..4bd459f 100644
--- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfiguration.java
+++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfiguration.java
@@ -61,4 +61,16 @@ public interface MOAIDConfiguration extends Configuration {
 	 * @throws ConfigurationException in case of an configuration access error
 	 */
 	public Map<String, String> getOnlineApplication(String publicURLPrefix) throws ConfigurationException;
+	
+	
+	/**
+	 * Load an OnlineApplication configuration and remove the OA key prefix
+	 * This is a backup version if direct UniqueID selection does not work
+	 * 
+	 * @param publicURLPrefix: Unique identifier of online application
+	 * @return Properties of the online application or null if no OA is found
+	 * @throws ConfigurationException in case of an configuration access error
+	 */
+	public Map<String, String> getOnlineApplicationBackupVersion(String publicURLPrefix) throws ConfigurationException;
+	
 }
\ No newline at end of file
diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfigurationImpl.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfigurationImpl.java
index 297c63d..b9b5ad6 100644
--- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfigurationImpl.java
+++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/config/persistence/MOAIDConfigurationImpl.java
@@ -1,5 +1,7 @@
 package at.gv.egovernment.moa.id.commons.config.persistence;
 
+import java.sql.SQLSyntaxErrorException;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -131,13 +133,88 @@ public class MOAIDConfigurationImpl extends DatabaseConfigPropertyImpl implement
 		String keyId = MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES
 				+ ".%."
 				+ MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER;
-				
+		
+		List<ConfigProperty> oaSearchResult = null;
 		TypedQuery<ConfigProperty> oaSearchQuery = em.createQuery("select dbconfig from ConfigProperty dbconfig where dbconfig.key like :key and dbconfig.value = SUBSTRING(:uniqueID, 1, LENGTH(dbconfig.value))", ConfigProperty.class);
 		oaSearchQuery.setParameter("key", keyId);
 		oaSearchQuery.setParameter("uniqueID", publicURLPrefix);
-		List<ConfigProperty> oaSearchResult = oaSearchQuery.getResultList();
+		oaSearchResult = oaSearchQuery.getResultList();
+			
+		return postProcessLoadOnlineApplication(em, oaSearchResult);
+
+	}
+		
+	/* (non-Javadoc)
+	 * @see at.gv.egovernment.moa.id.commons.config.persistence.MOAIDConfiguration#getOnlineApplicationBackupVersion(java.lang.String)
+	 */
+	@Override
+	public Map<String, String> getOnlineApplicationBackupVersion(
+			String publicURLPrefix) throws ConfigurationException {
+		Logger.debug("Use backup implementation to query configuration database");
+		
+		EntityManager em = this.getPersistenceContext();
+		if (null == em) {
+			Logger.error("No EntityManager set!");
+			throw new ConfigurationException("No EntityManager set!");
+			
+		}
+		
+		//search key prefix for online application with this publicURLPrefix
+		String keyId = MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES
+				+ ".%."
+				+ MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER;
 		
-        if (oaSearchResult.size() == 0) {
+		List<ConfigProperty> oaSearchResult = new ArrayList<ConfigProperty>();
+		
+		TypedQuery<ConfigProperty> oaSearchQuery = em.createQuery("select dbconfig from ConfigProperty dbconfig where dbconfig.key like :key", ConfigProperty.class);
+		oaSearchQuery.setParameter("key", keyId);
+		List<ConfigProperty> intermResult = oaSearchQuery.getResultList();
+		if (intermResult != null) {			
+			for (ConfigProperty el : intermResult) {
+				if (publicURLPrefix.startsWith(el.getValue()))
+					oaSearchResult.add(el);
+				
+			}				
+		}	
+		
+		return postProcessLoadOnlineApplication(em, oaSearchResult);
+		
+	}
+	
+	/**
+	 * Small helper method. NOTE: may return empty configuration properties, but never {@code null}.
+	 * 
+	 * @param propPrefix: the prefix of the desired property.
+	 * @param input: List of database objects with key/value information.
+	 * @param removePrefix: Indicates if the prefix should be removed from the result key
+	 * @return the {@link Map} of configuration properties
+	 */
+	private Map<String, String> getKeyValueFromDatabaseDAO(Iterator<ConfigProperty> input, final String prefix, boolean removePrefix) {
+		Map<String, String> configProp = new HashMap<String, String>();
+		 while (input.hasNext()) {
+	        ConfigProperty el = input.next();
+	        if (removePrefix) {
+	        	if (el.getKey().startsWith(prefix)) {	        	
+	        		String propertyName = KeyValueUtils.removePrefixFromKey(el.getKey(), prefix);	        		
+	        		configProp.put(propertyName, el.getValue());
+	        		
+	        	}	
+	        } else
+	        	configProp.put(el.getKey(), el.getValue());
+	        		                	
+		}
+		return configProp;
+	}
+
+	/**
+	 * Online-Application load operation post-processing
+	 * 
+	 * @param em EntityManager for Database access
+	 * @param oaSearchResult Search result of first OA selection operation
+	 * @return Map of post-processed OA configuration key/value pairs
+	 */	
+	private Map<String, String> postProcessLoadOnlineApplication(EntityManager em, List<ConfigProperty> oaSearchResult) {		
+		if (oaSearchResult == null || oaSearchResult.size() == 0) {
             Logger.debug("No entries found.");
             return null;      }
 
@@ -170,31 +247,6 @@ public class MOAIDConfigurationImpl extends DatabaseConfigPropertyImpl implement
 		result.put(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES, oaType);
 					        
 		return result;
+		
 	}
-	
-	/**
-	 * Small helper method. NOTE: may return empty configuration properties, but never {@code null}.
-	 * 
-	 * @param propPrefix: the prefix of the desired property.
-	 * @param input: List of database objects with key/value information.
-	 * @param removePrefix: Indicates if the prefix should be removed from the result key
-	 * @return the {@link Map} of configuration properties
-	 */
-	private Map<String, String> getKeyValueFromDatabaseDAO(Iterator<ConfigProperty> input, final String prefix, boolean removePrefix) {
-		Map<String, String> configProp = new HashMap<String, String>();
-		 while (input.hasNext()) {
-	        ConfigProperty el = input.next();
-	        if (removePrefix) {
-	        	if (el.getKey().startsWith(prefix)) {	        	
-	        		String propertyName = KeyValueUtils.removePrefixFromKey(el.getKey(), prefix);	        		
-	        		configProp.put(propertyName, el.getValue());
-	        		
-	        	}	
-	        } else
-	        	configProp.put(el.getKey(), el.getValue());
-	        		                	
-		}
-		return configProp;
-	}
-
 }
diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/MOASessionDBUtils.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/MOASessionDBUtils.java
index 7621552..49e0634 100644
--- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/MOASessionDBUtils.java
+++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/MOASessionDBUtils.java
@@ -163,8 +163,9 @@ public final class MOASessionDBUtils {
 		     
 	  	 } catch(HibernateException e) {
 	  		Logger.warn("Error during MOASession database saveOrUpdate. Rollback.", e);
-	  		 tx.rollback();
-	  		 throw new MOADatabaseException(e);
+	  		if (tx != null)
+	  			tx.rollback();
+	  		throw new MOADatabaseException(e);
 	  	 }
 	   }
 	   
@@ -183,8 +184,9 @@ public final class MOASessionDBUtils {
 		     
 	  	 } catch(HibernateException e) {
 	  		Logger.warn("Error during MOASession database delete. Rollback.", e);
-	  		 tx.rollback();
-	  		 return false;
+	  		if (tx != null)
+	  			tx.rollback();
+	  		return false;
 	  	 }
 	   }
    
diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java
index 0f157f1..c049eeb 100644
--- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java
+++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/NewConfigurationDBRead.java
@@ -41,9 +41,12 @@ public class NewConfigurationDBRead {
 		
 	}
 
-	public Map<String, String> getOnlineApplicationKeyValueWithId(String id) {
+	public Map<String, String> getOnlineApplicationKeyValueWithId(String id, boolean backupVersion) {
 		try {
-			return conf.getOnlineApplication(id);
+			if (backupVersion)
+				return conf.getOnlineApplicationBackupVersion(id);
+			else
+				return conf.getOnlineApplication(id);
 			
 		} catch (ConfigurationException e) {
 			Logger.warn("OnlineApplication with Id: " + id + " not found.", e);
diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/config/DatabaseConfigPropertyImpl.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/config/DatabaseConfigPropertyImpl.java
index f59e39a..aad830d 100644
--- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/config/DatabaseConfigPropertyImpl.java
+++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/config/DatabaseConfigPropertyImpl.java
@@ -1,6 +1,10 @@
 package at.gv.egovernment.moa.id.commons.db.dao.config;
 
+import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
+import java.util.Map.Entry;
+import java.util.regex.Pattern;
 
 import javax.persistence.EntityManager;
 import javax.persistence.PersistenceContext;
@@ -137,10 +141,33 @@ public class DatabaseConfigPropertyImpl extends AbstractConfigurationImpl {
 			throw new ConfigurationException("No EntityManager set!");
 		}
 		
-		TypedQuery<String> query = em.createQuery("select key from ConfigProperty dbconfig where dbconfig.value like :value", String.class);
-		query.setParameter("value", searchString.replace("*", "%"));
-		List<String> result = query.getResultList();
-		return result.toArray(new String[result.size()]);
+		TypedQuery<ConfigProperty> query = em.createQuery("select * from ConfigProperty dbconfig", ConfigProperty.class);
+		List<ConfigProperty> all = query.getResultList();
+		
+		searchString = searchString.replace(".", "\\.");
+		String regex = searchString.replace("*", ".*");
+		regex = regex.replace("%", "\\w*");
+		log.debug("Searching with regex: {}", regex);	
+		Pattern pattern = Pattern.compile(regex);
+		
+		List<String> keyList = new ArrayList<String>();	
+		Iterator<ConfigProperty> keyIt;
+		if (all != null) {
+			keyIt = all.iterator();
+			while(keyIt.hasNext()) {
+				ConfigProperty entry = keyIt.next();
+				String value = entry.getValue();
+				String key = entry.getKey();
+				
+				if(pattern.matcher(value).matches()) {
+					keyList.add(key);
+				}								
+			}
+		}
+				
+		String[] result = new String[keyList.size()];		
+		return keyList.toArray(result);
+			
 	}
 
 	/* (non-Javadoc)
diff --git a/id/server/moa-id-commons/src/main/resources/moaid.migration.beans.xml b/id/server/moa-id-commons/src/main/resources/moaid.migration.beans.xml
index 3bd1222..c758e23 100644
--- a/id/server/moa-id-commons/src/main/resources/moaid.migration.beans.xml
+++ b/id/server/moa-id-commons/src/main/resources/moaid.migration.beans.xml
@@ -31,7 +31,7 @@
 		<property name="testOnBorrow" value="${dbcp.testOnBorrow}" />
 		<property name="testOnReturn" value="${dbcp.testOnReturn}" />
 		<property name="testWhileIdle" value="${dbcp.testWhileIdle}" />
-		<property name="validationQuery" value="SELECT 1" />
+		<property name="validationQuery" value="${dbcp.validationQuery}" />
 	</bean>
 	
 
-- 
1.9.5.msysgit.0