From fa7f69cffc2c9b8d89ecc63f2dce72fffe1b671a Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Thu, 21 Apr 2016 08:30:09 +0200 Subject: Added RedisTransaction storage --- id/oa/src/main/webapp/WEB-INF/web.xml | 10 +- id/server/idserverlib/pom.xml | 30 +- .../moa/id/auth/servlet/AbstractController.java | 4 +- .../id/auth/servlet/IDPSingleLogOutServlet.java | 2 +- .../moa/id/moduls/AuthenticationManager.java | 2 +- .../egovernment/moa/id/moduls/RequestStorage.java | 3 +- .../process/dao/ProcessInstanceStoreDAOImpl.java | 2 +- .../id/protocols/pvp2x/PVPAssertionStorage.java | 2 +- .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 2 +- .../moa/id/storage/DBTransactionStorage.java | 2 +- .../moa/id/storage/ITransactionStorage.java | 3 +- .../moa/id/storage/RedisTransactionStorage.java | 355 +++++++++++++++++++++ .../main/resources/moaid.authentication.beans.xml | 28 +- .../id/commons/db/dao/session/AssertionStore.java | 15 +- .../oauth20/protocol/OAuth20AuthAction.java | 2 +- .../ssotransfer/servlet/SSOTransferServlet.java | 2 +- .../protocols/saml1/SAML1AuthenticationServer.java | 6 +- 17 files changed, 445 insertions(+), 25 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java (limited to 'id') diff --git a/id/oa/src/main/webapp/WEB-INF/web.xml b/id/oa/src/main/webapp/WEB-INF/web.xml index a42985c95..89553915a 100644 --- a/id/oa/src/main/webapp/WEB-INF/web.xml +++ b/id/oa/src/main/webapp/WEB-INF/web.xml @@ -5,8 +5,8 @@ MOA PVP2.1 Sample OA + PVP 2.1 Authentication request builder pvp2login - PVP 2.1 Authentication request builder at.gv.egovernment.moa.id.demoOA.servlet.pvp2.Authenticate @@ -16,8 +16,8 @@ - pvp2slo PVP 2.1 Single Log-Out request builder + pvp2slo at.gv.egovernment.moa.id.demoOA.servlet.pvp2.SingleLogOut @@ -27,8 +27,8 @@ + Metadata pvp2metadata - Metadata at.gv.egovernment.moa.id.demoOA.servlet.pvp2.BuildMetadata @@ -38,8 +38,8 @@ + Secure area pvp2demooa - Secure area at.gv.egovernment.moa.id.demoOA.servlet.pvp2.DemoApplication @@ -49,8 +49,8 @@ + Mainpage index - Mainpage at.gv.egovernment.moa.id.demoOA.servlet.pvp2.Index diff --git a/id/server/idserverlib/pom.xml b/id/server/idserverlib/pom.xml index c1533eeb7..127e7deec 100644 --- a/id/server/idserverlib/pom.xml +++ b/id/server/idserverlib/pom.xml @@ -385,7 +385,35 @@ spring-test test - + + + + org.springframework.data + spring-data-redis + 1.6.4.RELEASE + + + + org.apache.commons + commons-pool2 + 2.4.2 + + + redis.clients + jedis + 2.8.1 + + + + org.codehaus.jackson + jackson-core-asl + 1.9.13 + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.13 + diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index fd2e03afa..9e0eb2ed2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -139,12 +139,12 @@ public abstract class AbstractController extends MOAIDAuthConstants { revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); transactionStorage.put(key, new ExceptionContainer(pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), loggedException)); + pendingReq.getUniqueTransactionIdentifier(), loggedException),-1); } else { transactionStorage.put(key, new ExceptionContainer(null, - null, loggedException)); + null, loggedException),-1); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java index 66e8757ad..5e09380ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java @@ -179,7 +179,7 @@ public class IDPSingleLogOutServlet extends AbstractController { else statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - transactionStorage.put(artifact, statusCode); + transactionStorage.put(artifact, statusCode, -1); redirectURL = HTTPUtils.addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index a1f2c6558..3c6042b51 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -569,7 +569,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { } //put SLO process-information into transaction storage - transactionStorage.put(relayState, sloContainer); + transactionStorage.put(relayState, sloContainer, -1); if (MiscUtil.isEmpty(authURL)) authURL = pvpReq.getAuthURL(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java index 1b550881e..eec48e0f3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -68,7 +68,7 @@ public class RequestStorage implements IRequestStorage{ public void storePendingRequest(IRequest pendingRequest) throws MOAIDException { try { if (pendingRequest instanceof IRequest) { - transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); + transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest, -1); } else { throw new MOAIDException("auth.20", null); @@ -123,6 +123,7 @@ public class RequestStorage implements IRequestStorage{ ((RequestImpl)pendingRequest).setRequestID(newRequestID); transactionStorage.changeKey(oldRequestID, newRequestID, pendingRequest); + //only delete oldRequestID, no change. return newRequestID; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index a9a9322ad..428931b5e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -22,7 +22,7 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { @Override public void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException { try { - transactionStorage.put(pIStore.getProcessInstanceId(), pIStore); + transactionStorage.put(pIStore.getProcessInstanceId(), pIStore, -1); // MOASessionDBUtils.saveOrUpdate(pIStore); log.debug("Store process instance with='{}' in the database.", pIStore.getProcessInstanceId()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java index 0dd309154..62105abda 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java @@ -49,7 +49,7 @@ public class PVPAssertionStorage implements SAMLArtifactMap { samlMessage); try { - transactionStorage.put(artifact, assertion); + transactionStorage.put(artifact, assertion, -1); } catch (MOADatabaseException e) { // TODO Insert Error Handling, if Assertion could not be stored diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java index af6c79140..d7adab4e6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java @@ -254,7 +254,7 @@ public class SingleLogOutAction implements IAction { statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; } - transactionStorage.put(artifact, statusCode); + transactionStorage.put(artifact, statusCode, -1); redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java index c2b3b0fc5..4699ad09c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java @@ -73,7 +73,7 @@ public class DBTransactionStorage implements ITransactionStorage { } - public void put(String key, Object value) throws MOADatabaseException { + public void put(String key, Object value, int timeout_ms) throws MOADatabaseException { //search if key already exists AssertionStore element = searchInDatabase(key); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java index 493f24ee8..4651566fc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -48,9 +48,10 @@ public interface ITransactionStorage { * @param key Id which identifiers the data object * @param value Data object which should be stored. * This data must implement the java.io.Serializable interface + * @param timeout_ms Defines the period of time a data object is kept within the storage * @throws MOADatabaseException In case of store operation failed */ - public void put(String key, Object value) throws MOADatabaseException; + public void put(String key, Object value, int timeout_ms) throws MOADatabaseException; /** * Get a data object from transaction storage diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java new file mode 100644 index 000000000..a8294fe88 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java @@ -0,0 +1,355 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.storage; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang.SerializationUtils; +import org.hibernate.HibernateException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.RedisOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.SessionCallback; +import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +@Service("TransactionStorage") +public class RedisTransactionStorage implements ITransactionStorage { + + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + protected AuthConfiguration authConfig; + + @Autowired + private JacksonJsonRedisSerializer assertionStoreSerializer; + + public RedisTemplate getTemplate(){ + return this.redisTemplate; + } + + public void setTemplate(RedisTemplate t){ + this.redisTemplate = t; + } + + public boolean containsKey(String key) { + try { + searchInDatabase(key); + return true; + + } catch (MOADatabaseException e) { + return false; + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.storage.ITransactionStorage#changeKey(java.lang.String, java.lang.String, java.lang.Object) + */ + @Override + public void changeKey(String oldKey, String newKey, Object value) throws MOADatabaseException { + + //search if key already exists + final int expTime = redisTemplate.getExpire(oldKey, TimeUnit.MILLISECONDS).intValue(); + //AssertionStore element = searchInDatabase(oldKey); + if (expTime < 0) { + Logger.info("No transaction-data with oldKey:" + oldKey + + " found. Process gets stopped."); + throw new MOADatabaseException("No transaction-data with oldKey:" + oldKey + + " found. Process gets stopped."); + + } + + //Important: Rename not working here, because the new ID also has to be put into the + //value object. + //redisTemplate.rename(oldKey, newKey); + + final String old_key = oldKey; + + //redisTemplate.delete(oldKey); + //put(null, newKey, value, expTime); + final AssertionStore assertion = prepareAssertion(null, newKey, value); + List txResults = redisTemplate.execute(new SessionCallback>() { + public List execute(RedisOperations operations) throws DataAccessException { + operations.multi(); + operations.delete(old_key); + operations.opsForValue().set(assertion.getArtifact(), new String(assertionStoreSerializer.serialize(assertion)),expTime,TimeUnit.MILLISECONDS); + // This will contain the results of all ops in the transaction + return operations.exec(); + } + }); + + int a= txResults.size(); + } + + public void put(String key, Object value, int timeoutms) throws MOADatabaseException { + + //search if key already exists + AssertionStore element = searchInDatabase(key); + + //create a new entry if key does not exists already + if (element == null) { + element = new AssertionStore(); + + } + + put(element, key, value, timeoutms); + } + + public T get(String key, + final Class clazz) throws MOADatabaseException { + + try { + return get(key, clazz, -1); + + } catch (AuthenticationException e) { + //this execption only occurs if an additional timeOut is used + Logger.error("This exeption should not occur!!!!", e); + return null; + + } + } + + public Object get(String key) throws MOADatabaseException { + AssertionStore element = searchInDatabase(key); + + if (element == null) + return null; + + return SerializationUtils.deserialize(element.getAssertion()); + + + } + + public T get(String key, final Class clazz, long dataTimeOut) throws MOADatabaseException, AuthenticationException { + + AssertionStore element = searchInDatabase(key); + + if (element == null) + return null; + +// dataTimeOut = -1; +// if (dataTimeOut > -1) { +// //check timeout +// long now = new Date().getTime(); +// +// if (now - element.getDatatime().getTime() > dataTimeOut) { +// Logger.info("Transaction-Data with key: " + key + " is out of time."); +// throw new AuthenticationException("1207", new Object[] { key }); +// +// } +// } + + + //Deserialize Assertion + Object data = SerializationUtils.deserialize(element.getAssertion()); + + //check if assertion has the correct class type + try { + @SuppressWarnings("unchecked") + T test = (T) Class.forName(element.getType()).cast(data); + return test; + + } catch (Exception e) { + Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + key); + throw new MOADatabaseException("Sessioninformation Cast-Exception"); + + } + } + + //NOT USED with REDIS + public List clean(Date now, long dataTimeOut) { + + //redis enables to set TTL when creating new values, so we don't need this function anymore + +// Date expioredate = new Date(now.getTime() - dataTimeOut); +// +// List results; + List returnValues = new ArrayList(); +// Session session = MOASessionDBUtils.getCurrentSession(); +// +// synchronized (session) { +// session.beginTransaction(); +// Query query = session.getNamedQuery("getAssertionWithTimeOut"); +// query.setTimestamp("timeout", expioredate); +// results = query.list(); +// session.getTransaction().commit(); +// } +// +// if (results != null) { +// for (AssertionStore el : results) +// returnValues.add(el.getArtifact()); +// +// } + return returnValues; + } + + public void remove(String key) { + + try { + + AssertionStore element = searchInDatabase(key); + if (element == null) { + Logger.debug("Sessioninformation not removed! (Sessioninformation with ID=" + key + + "not found)"); + return; + } + + redisTemplate.delete(key); + //cleanDelete(element); + Logger.debug("Removed stored information with ID: " + key); + + + } catch (MOADatabaseException e) { + Logger.info("Sessioninformation not removed! (Message:"+ e.getMessage() + ")"); + + } catch (HibernateException e) { + Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); + } + } + + //Not used within REDIS store + private void cleanDelete(AssertionStore element) { + try { + element.setAssertion("blank".getBytes()); + MOASessionDBUtils.saveOrUpdate(element); + + } catch (MOADatabaseException e) { + Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); + + } finally { + if (!MOASessionDBUtils.delete(element)) + Logger.error("ShortTime session with artifact=" + element.getArtifact() + + " not removed! (Error during Database communication)"); + + } + + } + + //name="getAssertionWithArtifact", query = "select assertionstore from AssertionStore assertionstore where assertionstore.artifact = :artifact"), + //@NamedQuery(name="getAssertionWithTimeOut", query = "select assertionstore from AssertionStore assertionstore where assertionstore.timestamp < :timeout") + + @SuppressWarnings("rawtypes") + private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { + MiscUtil.assertNotNull(artifact, "artifact"); + Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); + + +// Session session = MOASessionDBUtils.getCurrentSession(); +// List result; +// +// synchronized (session) { +// session.beginTransaction(); +// Query query = session.getNamedQuery("getAssertionWithArtifact"); +// query.setParameter("artifact", artifact); +// result = query.list(); +// +// //send transaction +// session.getTransaction().commit(); +// } + //String id = (String) redisTemplate.opsForSet().pop(artifact); + String assertion = (String) redisTemplate.opsForValue().get(artifact); + //String id = (String) redisTemplate.opsForValue().get(artifact); + if(assertion == null){ + Logger.debug("No transaction information with ID:" + artifact + " found."); + return null; + } + + AssertionStore as = (AssertionStore) assertionStoreSerializer.deserialize(assertion.getBytes()); + //delete the timestamp entry +// String ts = as.getDatatime().toString(); +// redisTemplate.opsForSet().pop(ts); + + if(as == null){ + Logger.debug("No transaction information with ID:" + artifact + " found."); + return null; + } + return as; + + //Assertion requires an unique artifact +// if (result.size() != 1) { +// Logger.debug("No transaction information with ID:" + artifact + " found."); +// +// +// } +// +// return (AssertionStore) result.get(0); + } + + private void put(AssertionStore element, String key, Object value, int timeoutms) throws MOADatabaseException { + + element = prepareAssertion(element, key, value); + + int authDataTimeOut = authConfig.getTransactionTimeOut() * 1000; + + if(timeoutms != -1){ + authDataTimeOut = timeoutms; + } + redisTemplate.opsForValue().set(element.getArtifact(), new String(assertionStoreSerializer.serialize(element)),authDataTimeOut,TimeUnit.MILLISECONDS); + //MOASessionDBUtils.saveOrUpdate(element); + Logger.debug(value.getClass().getName() + " with ID: " + key + " is stored in Database"); + + } + +private AssertionStore prepareAssertion(AssertionStore element, String key, Object value) throws MOADatabaseException { + + if(element == null) + element = new AssertionStore(); + + element.setArtifact(key); + element.setType(value.getClass().getName()); + element.setDatatime(new Date()); + + if (!Serializable.class.isInstance(value)) { + Logger.warn("Transaction-Storage can only store objects which implements the 'Seralizable' interface"); + throw new MOADatabaseException("Transaction-Storage can only store objects which implements the 'Seralizable' interface", null); + } + + //serialize the Assertion for Database storage + byte[] data = SerializationUtils.serialize((Serializable) value); + element.setAssertion(data); + + long id = new Random().nextLong(); + element.setId(id); + + return element; + + } + +} diff --git a/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml b/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml index 11d92cea3..42192d6a0 100644 --- a/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml +++ b/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml @@ -4,6 +4,7 @@ xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd @@ -35,8 +36,7 @@ - + @@ -79,6 +79,28 @@ + scope="prototype"/> + + + + + + + + + + + + + + \ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java index c2f5ec962..d3c7abd1b 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AssertionStore.java @@ -35,6 +35,8 @@ import javax.persistence.Table; import org.hibernate.annotations.DynamicUpdate; +import com.fasterxml.jackson.annotation.JsonCreator; + @Entity @@ -46,8 +48,19 @@ import org.hibernate.annotations.DynamicUpdate; }) public class AssertionStore implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 2804964892915004185L; + + + + @JsonCreator + public AssertionStore(){ + + } + - private static final long serialVersionUID = 1L; @Id //@GeneratedValue(strategy = GenerationType.AUTO) diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java index 803ae388f..b9bed7a22 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java @@ -93,7 +93,7 @@ class OAuth20AuthAction implements IAction { // store data in oath session - transactionStorage.put(code, o); + transactionStorage.put(code, o, -1); Logger.debug("Saved OAuth20SessionObject in session with id: " + code); diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java index b18425839..70b2ebbe9 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java @@ -535,7 +535,7 @@ public class SSOTransferServlet{ container.setDhParams(dhKeyIDP); //store container - transactionStorage.put(token, container); + transactionStorage.put(token, container,(int)transmisionTimeOut); //build QR code String containerURL = authURL diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java index 0ec0d95a2..113fb943f 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java @@ -95,7 +95,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { * time out in milliseconds used by {@link cleanup} for authentication data * store */ - private static final long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes + private static final int authDataTimeOut = 2 * 60 * 1000; // default 2 minutes public Throwable getErrorResponse(String samlArtifact) throws AuthenticationException { @@ -210,7 +210,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { protocolRequest.getOAURL(), protocolRequest.getRequestID(), null); - authenticationDataStore.put(samlArtifact, error); + authenticationDataStore.put(samlArtifact, error, authDataTimeOut); return samlArtifact; } @@ -721,7 +721,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { //synchronized (authenticationDataStore) { Logger.debug("Assertion stored for SAML Artifact: " + samlArtifact); - authenticationDataStore.put(samlArtifact, samlAssertion); + authenticationDataStore.put(samlArtifact, samlAssertion,authDataTimeOut); //} } catch (AuthenticationException ex) { -- cgit v1.2.3 From 4c3ffb1cf320bcdfe02a08007f999f8a22f26f8b Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Mon, 25 Apr 2016 11:46:54 +0200 Subject: Added DummyTransactionStorage for Tests --- .../spring/test/DummyTransactionStorage.java | 135 +++++++++++++++++++++ ...ingExpressionAwareProcessEngineTest-context.xml | 13 +- 2 files changed, 144 insertions(+), 4 deletions(-) create mode 100644 id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java (limited to 'id') diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java new file mode 100644 index 000000000..9f1fc5f2d --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java @@ -0,0 +1,135 @@ +package at.gv.egovernment.moa.id.process.spring.test; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import javax.sql.DataSource; + +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.logging.Logger; + +/** + * Dummy DataSource implementation for convenience in test cases where a + * database connection will never actually be acquired. + * + * @see DataSource + * @author Chris Beams + */ +public class DummyTransactionStorage implements ITransactionStorage { + + public class DummyDBEntry{ + public DummyDBEntry(String key, Object value){ + this.obj =value; + this.key = key; + } + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + public Object getObj() { + return obj; + } + public void setObj(Object obj) { + this.obj = obj; + } + private String key; + private Object obj; + } + + private ArrayList ds = new ArrayList(); + + + + @Override + public boolean containsKey(String key) { + // TODO Auto-generated method stub + Iterator it = ds.iterator(); + while(it.hasNext()){ + DummyDBEntry t = it.next(); + if(t.getKey().equals(key)) + return true; + } + return false; + } + + @Override + public void put(String key, Object value, int timeout_ms) + throws MOADatabaseException { + // TODO Auto-generated method stub + this.remove(key); + this.ds.add(new DummyDBEntry(key, value)); + + } + + @Override + public Object get(String key) throws MOADatabaseException { + // TODO Auto-generated method stub + Iterator it = ds.iterator(); + while(it.hasNext()){ + DummyDBEntry t = it.next(); + if(t.getKey().equals(key)) + return t; + } + return null; + } + + @Override + public T get(String key, Class clazz) throws MOADatabaseException { + + DummyDBEntry o = (DummyDBEntry) get(key); + if(o == null) + return null; + try { + @SuppressWarnings("unchecked") + T test = (T) (clazz.cast(o.getObj())); + return test; + + } catch (Exception e) { + Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + key); + throw new MOADatabaseException("Sessioninformation Cast-Exception"); + + } + } + + @Override + public T get(String key, Class clazz, long dataTimeOut) + throws MOADatabaseException, AuthenticationException { + // TODO Auto-generated method stub + return get(key,clazz); + } + + @Override + public void changeKey(String oldKey, String newKey, Object value) + throws MOADatabaseException { + this.remove(oldKey); + this.put(newKey, value, -1); + + } + + @Override + public void remove(String key) { + Iterator it = ds.iterator(); + while(it.hasNext()){ + DummyDBEntry t = it.next(); + if(t.getKey().equals(key)){ + this.ds.remove(t); + return; + } + } + + } + + @Override + public List clean(Date now, long dataTimeOut) { + // TODO Auto-generated method stub + return null; + } + + +} \ No newline at end of file diff --git a/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml b/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml index bf47c0445..7d9db0ab7 100644 --- a/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml +++ b/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml @@ -1,9 +1,13 @@ + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> @@ -12,7 +16,7 @@ + class="at.gv.egovernment.moa.id.process.spring.test.DummyTransactionStorage"/> @@ -40,4 +44,5 @@ + -- cgit v1.2.3 From 851f8c8ed0959c75a2bd28a61ff4cd5dd49f98f5 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Tue, 26 Apr 2016 15:15:35 +0200 Subject: fixed allowed url prefix check bug --- .../java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index bca080ba6..82e46b6ce 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -525,7 +525,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { boolean isAllowedDestination = false; for (String prefix : allowedPublicURLPrefix) { - if (!resp.getDestination().startsWith( + if (resp.getDestination().startsWith( prefix)) { isAllowedDestination = true; break; -- cgit v1.2.3 From 129285d2c6fcd82a3cba7fc5345e87699129c005 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Tue, 26 Apr 2016 15:35:46 +0200 Subject: modified RedisTransactionStorage, modified beans definition --- id/ConfigWebTool/pom.xml | 6 -- id/moa-id-webgui/pom.xml | 4 - id/server/idserverlib/pom.xml | 4 +- .../moa/id/storage/DBTransactionStorage.java | 89 ++++++++++------------ .../moa/id/storage/RedisTransactionStorage.java | 26 +++---- .../main/resources/moaid.authentication.beans.xml | 20 ----- .../src/main/resources/session.db.beans.xml | 58 ++++++++++++++ .../src/main/resources/session.redis.beans.xml | 34 +++++++++ id/server/moa-id-commons/pom.xml | 4 +- .../src/main/resources/META-INF/persistence.xml | 8 ++ .../id/auth/MOAIDAuthSpringResourceProvider.java | 7 +- 11 files changed, 163 insertions(+), 97 deletions(-) create mode 100644 id/server/idserverlib/src/main/resources/session.db.beans.xml create mode 100644 id/server/idserverlib/src/main/resources/session.redis.beans.xml (limited to 'id') diff --git a/id/ConfigWebTool/pom.xml b/id/ConfigWebTool/pom.xml index c672d32a6..28c0a9fe4 100644 --- a/id/ConfigWebTool/pom.xml +++ b/id/ConfigWebTool/pom.xml @@ -64,12 +64,6 @@ MOA.id.server moa-id-commons - - - hibernate-c3p0 - org.hibernate - - diff --git a/id/moa-id-webgui/pom.xml b/id/moa-id-webgui/pom.xml index 8d35abd20..31247efc1 100644 --- a/id/moa-id-webgui/pom.xml +++ b/id/moa-id-webgui/pom.xml @@ -58,10 +58,6 @@ hyperjaxb3-ejb-runtime org.jvnet.hyperjaxb3 - - hibernate-c3p0 - org.hibernate - diff --git a/id/server/idserverlib/pom.xml b/id/server/idserverlib/pom.xml index 127e7deec..dabce982c 100644 --- a/id/server/idserverlib/pom.xml +++ b/id/server/idserverlib/pom.xml @@ -85,11 +85,11 @@ - + org.hibernate hibernate-entitymanager diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java index 4699ad09c..89df47615 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java @@ -27,24 +27,31 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceException; +import javax.persistence.Query; + import org.apache.commons.lang.SerializationUtils; import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("TransactionStorage") +@Repository +@Transactional("sessionTransactionManager") public class DBTransactionStorage implements ITransactionStorage { - + + @PersistenceContext(unitName="session") + private EntityManager entityManager; + public boolean containsKey(String key) { - try { + try { searchInDatabase(key); return true; @@ -151,16 +158,12 @@ public class DBTransactionStorage implements ITransactionStorage { List results; List returnValues = new ArrayList();; - Session session = MOASessionDBUtils.getCurrentSession(); - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithTimeOut"); - query.setTimestamp("timeout", expioredate); - results = query.list(); - session.getTransaction().commit(); - } + Query query = entityManager.createNamedQuery("getAssertionWithTimeOut"); + query.setParameter("timeout", expioredate); + results = query.getResultList(); + if (results != null) { for (AssertionStore el : results) returnValues.add(el.getArtifact()); @@ -187,24 +190,21 @@ public class DBTransactionStorage implements ITransactionStorage { Logger.info("Sessioninformation not removed! (Message:"+ e.getMessage() + ")"); } catch (HibernateException e) { - Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); + Logger.warn("Sessioninformation not removed! (Erreor during Database communication)", e); } } private void cleanDelete(AssertionStore element) { - try { - element.setAssertion("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(element); - - } catch (MOADatabaseException e) { - Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); + - } finally { - if (!MOASessionDBUtils.delete(element)) + try{ + element.setAssertion("blank".getBytes()); + entityManager.merge(element); + entityManager.remove(element); + }catch(PersistenceException e){ Logger.error("ShortTime session with artifact=" + element.getArtifact() + " not removed! (Error during Database communication)"); - - } + } } @@ -212,29 +212,23 @@ public class DBTransactionStorage implements ITransactionStorage { private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { MiscUtil.assertNotNull(artifact, "artifact"); Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - List result; + List results; - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithArtifact"); - query.setParameter("artifact", artifact); - result = query.list(); + Query query = entityManager.createNamedQuery("getAssertionWithArtifact"); + query.setParameter("artifact", artifact); - //send transaction - session.getTransaction().commit(); - } + results = query.getResultList(); - Logger.trace("Found entries: " + result.size()); + Logger.trace("Found entries: " + results.size()); //Assertion requires an unique artifact - if (result.size() != 1) { + if (results.size() != 1) { Logger.debug("No transaction information with ID:" + artifact + " found."); return null; } - return (AssertionStore) result.get(0); + return results.get(0); } private void put(AssertionStore element, String key, Object value) throws MOADatabaseException { @@ -253,15 +247,16 @@ public class DBTransactionStorage implements ITransactionStorage { element.setAssertion(data); //store AssertionStore element to Database - try { - MOASessionDBUtils.saveOrUpdate(element); + //try { + entityManager.merge(element); + //MOASessionDBUtils.saveOrUpdate(element); Logger.debug(value.getClass().getName() + " with ID: " + key + " is stored in Database"); - - } catch (MOADatabaseException e) { - Logger.warn("Sessioninformation could not be stored."); - throw new MOADatabaseException(e); - - } +// +// } catch (MOADatabaseException e) { +// Logger.warn("Sessioninformation could not be stored."); +// throw new MOADatabaseException(e); +// +// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java index a8294fe88..cae73fafd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java @@ -246,19 +246,19 @@ public class RedisTransactionStorage implements ITransactionStorage { //Not used within REDIS store private void cleanDelete(AssertionStore element) { - try { - element.setAssertion("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(element); - - } catch (MOADatabaseException e) { - Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); - - } finally { - if (!MOASessionDBUtils.delete(element)) - Logger.error("ShortTime session with artifact=" + element.getArtifact() - + " not removed! (Error during Database communication)"); - - } +// try { +// element.setAssertion("blank".getBytes()); +// MOASessionDBUtils.saveOrUpdate(element); +// +// } catch (MOADatabaseException e) { +// Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); +// +// } finally { +// if (!MOASessionDBUtils.delete(element)) +// Logger.error("ShortTime session with artifact=" + element.getArtifact() +// + " not removed! (Error during Database communication)"); +// +// } } diff --git a/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml b/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml index 42192d6a0..cd5fe6acf 100644 --- a/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml +++ b/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml @@ -81,26 +81,6 @@ class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.EvaluateSSOConsentsTaskImpl" scope="prototype"/> - - - - - - - - - - - - \ No newline at end of file diff --git a/id/server/idserverlib/src/main/resources/session.db.beans.xml b/id/server/idserverlib/src/main/resources/session.db.beans.xml new file mode 100644 index 000000000..0aeb24bac --- /dev/null +++ b/id/server/idserverlib/src/main/resources/session.db.beans.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/id/server/idserverlib/src/main/resources/session.redis.beans.xml b/id/server/idserverlib/src/main/resources/session.redis.beans.xml new file mode 100644 index 000000000..421159d08 --- /dev/null +++ b/id/server/idserverlib/src/main/resources/session.redis.beans.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/id/server/moa-id-commons/pom.xml b/id/server/moa-id-commons/pom.xml index ea9e06fd6..613698fc6 100644 --- a/id/server/moa-id-commons/pom.xml +++ b/id/server/moa-id-commons/pom.xml @@ -143,11 +143,11 @@ hibernate-core ${hibernate.version} - + org.hibernate hibernate-entitymanager diff --git a/id/server/moa-id-commons/src/main/resources/META-INF/persistence.xml b/id/server/moa-id-commons/src/main/resources/META-INF/persistence.xml index 9bebfa66f..5c1558507 100644 --- a/id/server/moa-id-commons/src/main/resources/META-INF/persistence.xml +++ b/id/server/moa-id-commons/src/main/resources/META-INF/persistence.xml @@ -12,5 +12,13 @@ http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" + + + org.hibernate.ejb.HibernatePersistence + at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore + + + + \ No newline at end of file diff --git a/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java b/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java index def32e144..47857bcfb 100644 --- a/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java +++ b/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java @@ -40,9 +40,10 @@ public class MOAIDAuthSpringResourceProvider implements SpringResourceProvider { public Resource[] getResourcesToLoad() { ClassPathResource moaidauthConfig = new ClassPathResource("/moaid.configuration.beans.xml", MOAIDAuthInitializer.class); ClassPathResource configurationDBConfig = new ClassPathResource("/configuration.beans.xml", MOAIDAuthInitializer.class); - ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthInitializer.class); - - return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans}; + ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthInitializer.class); + ClassPathResource moaSessionDBBeans = new ClassPathResource("/session.db.beans.xml", MOAIDAuthInitializer.class); + ClassPathResource moaSessionRedisBeans = new ClassPathResource("/session.redis.beans.xml", MOAIDAuthInitializer.class); + return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans, moaSessionDBBeans, moaSessionRedisBeans}; } -- cgit v1.2.3 From 8da90c1f897736d2d2237efedd2b6a3ac362af2d Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Wed, 27 Apr 2016 16:11:49 +0200 Subject: Modified SingleLogOutAction to work with REDIS --- .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 274 +++++++++++---------- .../moa/id/storage/DBTransactionStorage.java | 13 +- .../moa/id/storage/ITransactionStorage.java | 17 ++ .../moa/id/storage/RedisTransactionStorage.java | 22 ++ 4 files changed, 192 insertions(+), 134 deletions(-) (limited to 'id') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java index d7adab4e6..57540138e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java @@ -83,8 +83,8 @@ public class SingleLogOutAction implements IAction { @Autowired private ITransactionStorage transactionStorage; @Autowired private SingleLogOutBuilder sloBuilder; @Autowired private MOAReversionLogger revisionsLogger; - - + + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.data.IAuthData) */ @@ -94,139 +94,145 @@ public class SingleLogOutAction implements IAction { IAuthData authData) throws MOAIDException { PVPTargetConfiguration pvpReq = (PVPTargetConfiguration) req; - + if (pvpReq.getRequest() instanceof MOARequest && ((MOARequest)pvpReq.getRequest()).getSamlRequest() instanceof LogoutRequest) { Logger.debug("Process Single LogOut request"); MOARequest samlReq = (MOARequest) pvpReq.getRequest(); LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); - + AuthenticationSession session = authenticationSessionStorage.searchMOASessionWithNameIDandOAID( logOutReq.getIssuer().getValue(), logOutReq.getNameID().getValue()); - - if (session == null) { - Logger.warn("Can not find active SSO session with nameID " - + logOutReq.getNameID().getValue() + " and OA " - + logOutReq.getIssuer().getValue()); - Logger.info("Search active SSO session with SSO session cookie"); - String ssoID = ssomanager.getSSOSessionID(httpReq); - if (MiscUtil.isEmpty(ssoID)) { + + if (session == null) { + Logger.warn("Can not find active SSO session with nameID " + + logOutReq.getNameID().getValue() + " and OA " + + logOutReq.getIssuer().getValue()); + Logger.info("Search active SSO session with SSO session cookie"); + String ssoID = ssomanager.getSSOSessionID(httpReq); + if (MiscUtil.isEmpty(ssoID)) { + Logger.info("Can not find active Session. Single LogOut not possible!"); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); + Logger.info("Sending SLO success message to requester ..."); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + return null; + + } else { + String moasession = ssomanager.getMOASession(ssoID); + try { + session = authenticationSessionStorage.getSession(moasession); + + } catch (MOADatabaseException e) { Logger.info("Can not find active Session. Single LogOut not possible!"); SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); Logger.info("Sending SLO success message to requester ..."); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); return null; - - } else { - String moasession = ssomanager.getMOASession(ssoID); - try { - session = authenticationSessionStorage.getSession(moasession); - - } catch (MOADatabaseException e) { - Logger.info("Can not find active Session. Single LogOut not possible!"); - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); - //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); - Logger.info("Sending SLO success message to requester ..."); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); - return null; - - } - } + + } + } + } + + authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq); + + } else if (pvpReq.getRequest() instanceof MOAResponse && + ((MOAResponse)pvpReq.getRequest()).getResponse() instanceof LogoutResponse) { + Logger.debug("Process Single LogOut response"); + LogoutResponse logOutResp = (LogoutResponse) ((MOAResponse)pvpReq.getRequest()).getResponse(); + + //Transaction tx = null; + + try { + String relayState = pvpReq.getRequest().getRelayState(); + if (MiscUtil.isEmpty(relayState)) { + Logger.warn("SLO Response from " + logOutResp.getIssuer().getValue() + + " has no SAML2 RelayState."); + throw new SLOException("pvp2.19", null); + } - - authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq); - - } else if (pvpReq.getRequest() instanceof MOAResponse && - ((MOAResponse)pvpReq.getRequest()).getResponse() instanceof LogoutResponse) { - Logger.debug("Process Single LogOut response"); - LogoutResponse logOutResp = (LogoutResponse) ((MOAResponse)pvpReq.getRequest()).getResponse(); - - Transaction tx = null; - - try { - String relayState = pvpReq.getRequest().getRelayState(); - if (MiscUtil.isEmpty(relayState)) { - Logger.warn("SLO Response from " + logOutResp.getIssuer().getValue() - + " has no SAML2 RelayState."); - throw new SLOException("pvp2.19", null); - - } - - Session session = MOASessionDBUtils.getCurrentSession(); - boolean storageSuccess = false; - int counter = 0; - - //TODO: add counter to prevent deadlock - + + //Session session = MOASessionDBUtils.getCurrentSession(); + boolean storageSuccess = false; + int counter = 0; + + //TODO: add counter to prevent deadlock + synchronized(this){ while (!storageSuccess) { - tx = session.beginTransaction(); - - List result; - Query query = session.getNamedQuery("getAssertionWithArtifact"); - query.setParameter("artifact", relayState); - result = query.list(); - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { + // tx = session.beginTransaction(); + // + // List result; + // Query query = session.getNamedQuery("getAssertionWithArtifact"); + // query.setParameter("artifact", relayState); + // result = query.list(); + // + // + // Logger.trace("Found entries: " + result.size()); + // + // //Assertion requires an unique artifact + // if (result.size() != 1) { + // Logger.trace("No entries found."); + // throw new MOADatabaseException("No sessioninformation found with this ID"); + // } + // + // AssertionStore element = (AssertionStore) result.get(0); + // Object data = SerializationUtils.deserialize(element.getAssertion()); + Logger.debug("Current Thread getAssertionStore: "+Thread.currentThread().getId()); + Object o = transactionStorage.getAssertionStore(relayState); + if(o==null){ Logger.trace("No entries found."); - throw new MOADatabaseException("No sessioninformation found with this ID"); + throw new MOADatabaseException("No sessioninformation found with this ID"); } - - AssertionStore element = (AssertionStore) result.get(0); - Object data = SerializationUtils.deserialize(element.getAssertion()); - + AssertionStore element = (AssertionStore) o; + Object data = SerializationUtils.deserialize(element.getAssertion()); + if (data instanceof SLOInformationContainer) { ISLOInformationContainer sloContainer = (ISLOInformationContainer) data; - + //check status sloBuilder.checkStatusCode(sloContainer, logOutResp); - + if (sloContainer.hasFrontChannelOA()) { try { //some response are open byte[] serializedSLOContainer = SerializationUtils.serialize((Serializable) sloContainer); element.setAssertion(serializedSLOContainer); element.setType(sloContainer.getClass().getName()); - - session.saveOrUpdate(element); - tx.commit(); - + + // session.saveOrUpdate(element); + // tx.commit(); + Logger.debug("Current Thread putAssertionStore: "+Thread.currentThread().getId()); + transactionStorage.putAssertionStore(element); + //sloContainer could be stored to database storageSuccess = true; - - } catch(HibernateException e) { - tx.rollback(); + + } catch(MOADatabaseException e) { + //tx.rollback(); counter++; Logger.debug("SLOContainter could not stored to database. Wait some time and restart storage process ... "); java.util.Random rand = new java.util.Random(); - + try { Thread.sleep(rand.nextInt(20)*10); - + } catch (InterruptedException e1) { Logger.warn("Thread could not stopped. ReStart storage process immediately", e1); } } - + } else { - //last response received. - try { - session.delete(element); - tx.commit(); - - } catch(HibernateException e) { - tx.rollback(); - Logger.error("SLOContainter could not deleted from database. "); - - } - + Logger.debug("Current Thread removeElement by Artifact: "+Thread.currentThread().getId()); + transactionStorage.remove(element.getArtifact()); + // session.delete(element); + // tx.commit(); + storageSuccess = true; String redirectURL = null; if (sloContainer.getSloRequest() != null) { @@ -234,70 +240,72 @@ public class SingleLogOutAction implements IAction { SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(sloContainer.getSloRequest()); LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); redirectURL = sloBuilder.getFrontChannelSLOMessageURL(sloService, message, httpReq, httpResp, sloContainer.getSloRequest().getRequest().getRelayState()); - + } else { //print SLO information directly redirectURL = req.getAuthURL() + "/idpSingleLogout"; - + String artifact = Random.nextRandom(); - - String statusCode = null; + + String statusCode = null; if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) { - statusCode = MOAIDAuthConstants.SLOSTATUS_SUCCESS; - revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), - MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); - + sloContainer.getSloFailedOAs().size() == 0) { + statusCode = MOAIDAuthConstants.SLOSTATUS_SUCCESS; + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), + MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); + } else { revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); - statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - + statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; + } transactionStorage.put(artifact, statusCode, -1); - redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); - + redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); + } //redirect to Redirect Servlet String url = req.getAuthURL() + "/RedirectServlet"; url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(redirectURL, "UTF-8")); url = httpResp.encodeRedirectURL(url); - + httpResp.setContentType("text/html"); httpResp.setStatus(302); httpResp.addHeader("Location", url); - + } } else { Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + relayState); throw new MOADatabaseException("Sessioninformation Cast-Exception"); - + } } - - } catch (MOADatabaseException e) { - Logger.error("MOA AssertionDatabase ERROR", e); - throw new SLOException("pvp2.19", null); - - } catch (UnsupportedEncodingException e) { - Logger.error("Finale SLO redirct not possible.", e); - throw new AuthenticationException("pvp2.13", new Object[]{}); - - } finally { - if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) { - tx.commit(); - - } } - - - - } else { - Logger.error("Process SingleLogOutAction but request is NOT of type LogoutRequest or LogoutResponse."); - throw new MOAIDException("pvp2.13", null); - - } - + } catch (MOADatabaseException e) { + Logger.error("MOA AssertionDatabase ERROR", e); + throw new SLOException("pvp2.19", null); + + } catch (UnsupportedEncodingException e) { + Logger.error("Finale SLO redirct not possible.", e); + throw new AuthenticationException("pvp2.13", new Object[]{}); + + } + + // finally { + // if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) { + // tx.commit(); + // + // } + // } + + + + } else { + Logger.error("Process SingleLogOutAction but request is NOT of type LogoutRequest or LogoutResponse."); + throw new MOAIDException("pvp2.13", null); + + } + return null; } @@ -317,7 +325,7 @@ public class SingleLogOutAction implements IAction { public String getDefaultActionName() { return PVP2XProtocol.SINGLELOGOUT; } - + protected static String addURLParameter(String url, String paramname, String paramvalue) { String param = paramname + "=" + paramvalue; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java index 89df47615..fa8ca8547 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java @@ -104,7 +104,11 @@ public class DBTransactionStorage implements ITransactionStorage { Logger.error("This exeption should not occur!!!!", e); return null; - } + } + } + + public Object getAssertionStore(String key) throws MOADatabaseException{ + return searchInDatabase(key); } public Object get(String key) throws MOADatabaseException { @@ -260,4 +264,11 @@ public class DBTransactionStorage implements ITransactionStorage { } + @Override + public void putAssertionStore(Object element) throws MOADatabaseException{ + // TODO Auto-generated method stub + entityManager.merge(element); + + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java index 4651566fc..53a7f4f5e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -111,4 +111,21 @@ public interface ITransactionStorage { */ public List clean(Date now, long dataTimeOut); + + /** + * Get whole AssertionStoreObject, required for SLO + * + * @param key key Id which identifiers the data object + * @return The transaction-data object, or null + * @throws MOADatabaseException In case of load operation failed + */ + public Object getAssertionStore(String key) throws MOADatabaseException; + + /** + * Put whole AssertionStoreObject to db, required for SLO + * + * @param element assertion store object + */ + public void putAssertionStore(Object element) throws MOADatabaseException; + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java index cae73fafd..c17bff358 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java @@ -352,4 +352,26 @@ private AssertionStore prepareAssertion(AssertionStore element, String key, Obje } +@Override +public Object getAssertionStore(String key) throws MOADatabaseException { + return searchInDatabase(key); +} + +@Override +public void putAssertionStore(Object element) throws MOADatabaseException { + // TODO Auto-generated method stub + AssertionStore as = (AssertionStore)element; + final int expTime = redisTemplate.getExpire(as.getArtifact(), TimeUnit.MILLISECONDS).intValue(); + //AssertionStore element = searchInDatabase(oldKey); + if (expTime < 0) { + Logger.info("No transaction-data with oldKey:" + as.getArtifact() + + " found. Process gets stopped."); + throw new MOADatabaseException("No transaction-data with oldKey:" + as.getArtifact() + + " found. Process gets stopped."); + + } + redisTemplate.opsForValue().set(as.getArtifact(), new String(assertionStoreSerializer.serialize(element)),expTime,TimeUnit.MILLISECONDS); + +} + } -- cgit v1.2.3 From 6f353de9f09b26440f67f62ba8186ae82f16adb5 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Wed, 27 Apr 2016 16:16:44 +0200 Subject: Added some tests for redis --- .../spring/test/DummyTransactionStorage.java | 12 ++ .../id/storage/test/DBTransactionStorageTest.java | 122 +++++++++++++++++++ .../test/RedisTransactionMultiThreadTest.java | 130 +++++++++++++++++++++ .../storage/test/RedisTransactionStorageTest.java | 116 ++++++++++++++++++ id/server/idserverlib/src/test/java/testBeans.xml | 130 +++++++++++++++++++++ 5 files changed, 510 insertions(+) create mode 100644 id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java create mode 100644 id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionMultiThreadTest.java create mode 100644 id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java create mode 100644 id/server/idserverlib/src/test/java/testBeans.xml (limited to 'id') diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java index 9f1fc5f2d..ab08c0f5c 100644 --- a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java @@ -131,5 +131,17 @@ public class DummyTransactionStorage implements ITransactionStorage { return null; } + @Override + public Object getAssertionStore(String key) throws MOADatabaseException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void putAssertionStore(Object element) throws MOADatabaseException { + // TODO Auto-generated method stub + + } + } \ No newline at end of file diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java new file mode 100644 index 000000000..4b7f61ef5 --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java @@ -0,0 +1,122 @@ +package at.gv.egovernment.moa.id.storage.test; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.DBTransactionStorage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.util.Constants; +import at.gv.util.DOMUtils; + +public class DBTransactionStorageTest { + + public static void main (String[] args) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + DBTransactionStorageTest t = new DBTransactionStorageTest(); + t.test(); + } + + @Autowired + DBTransactionStorage rts; + + public DBTransactionStorageTest(){ + + } + + + public void test() throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + + + ApplicationContext context = new FileSystemXmlApplicationContext("src/test/java/testBeans.xml"); + + + String requestString = + "" + + "" + + "WRONGARTIFACT" + + ""; + Element request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + ITransactionStorage rts = (ITransactionStorage) context.getBean("DBTransactionStorage"); + //GenericToStringSerializer redisStringSerializer = (GenericToStringSerializer) context.getBean("valueObjectSerializer"); + + // rts.getTemplate().setValueSerializer(new GenericToStringSerializer(Object.class)); + // rts.getTemplate().setHashValueSerializer(new GenericToStringSerializer(Object.class)); + + int cnt = 10; + int averageCnt = 10; + long putTime = 0, getTime = 0, changeTime = 0, removeTime = 0; + long total = 0; + for(int a=0;a" + + "" + + "WRONGARTIFACT" + + ""; + Element request2 = DOMUtils.parseDocument(requestString2, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + System.out.println("Starting MySql change operation."); + start = System.currentTimeMillis(); + for(int i=0; i" + +// "" + +// "WRONGARTIFACT" + +// ""; +// Element request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); +// +// +// +// +// RedisTransactionStorage rts = (RedisTransactionStorage) context.getBean("TransactionStorage"); +// //GenericToStringSerializer redisStringSerializer = (GenericToStringSerializer) context.getBean("valueObjectSerializer"); +// +//// rts.getTemplate().setValueSerializer(new GenericToStringSerializer(Object.class)); +//// rts.getTemplate().setHashValueSerializer(new GenericToStringSerializer(Object.class)); +// +// +// rts.put("test", request,-1); +// System.out.println("Redis store operation done!"); +// +// Element test = (Element)rts.get("test"); +// System.out.println("Read Element from Redis Store: "+test.getTextContent()); +// +// String requestString2 = +// "" + +// "" + +// "WRONGARTIFACT" + +// ""; +// Element request2 = DOMUtils.parseDocument(requestString2, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); +// +// +// rts.changeKey("test", "test_new", request2); +// +// rts.remove("test"); +// rts.remove("test_new"); +// +// ((ConfigurableApplicationContext)context).close(); + } + + private class RedisTask implements Runnable { + + private String message; + + public RedisTask(String message) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException { + + this.message = message; + + + + } + + public void run() { + String requestString = + "" + + "" + + "WRONGARTIFACT" + + ""; + + Element request = null; + try { + request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } + + RedisTransactionStorage rts = (RedisTransactionStorage) context.getBean("RedisTransactionStorage"); + + try { + rts.put(message, request,-1); + rts.changeKey(message, message+"n", request); + } catch (MOADatabaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } + System.out.println("Done with task "+message); + } + + } + +} diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java new file mode 100644 index 000000000..e957ffe05 --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java @@ -0,0 +1,116 @@ +package at.gv.egovernment.moa.id.storage.test; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.DBTransactionStorage; +import at.gv.egovernment.moa.id.storage.RedisTransactionStorage; +import at.gv.egovernment.moa.util.Constants; +import at.gv.util.DOMUtils; + +public class RedisTransactionStorageTest { + + + public RedisTransactionStorageTest(){ + + } + + public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + + + ApplicationContext context = new FileSystemXmlApplicationContext("src/test/java/testBeans.xml"); + + + String requestString = + "" + + "" + + "WRONGARTIFACT" + + ""; + Element request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + RedisTransactionStorage rts = (RedisTransactionStorage) context.getBean("RedisTransactionStorage"); + //GenericToStringSerializer redisStringSerializer = (GenericToStringSerializer) context.getBean("valueObjectSerializer"); + + // rts.getTemplate().setValueSerializer(new GenericToStringSerializer(Object.class)); + // rts.getTemplate().setHashValueSerializer(new GenericToStringSerializer(Object.class)); + + int cnt = 100; + int averageCnt = 10; + long putTime = 0, getTime = 0, changeTime = 0, removeTime = 0; + long total = 0; + for(int a=0;a" + + "" + + "WRONGARTIFACT" + + ""; + Element request2 = DOMUtils.parseDocument(requestString2, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + System.out.println("Starting Redis change operation."); + start = System.currentTimeMillis(); + for(int i=0; i + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file -- cgit v1.2.3 From 61661f2ea4978d56691f7a672469c6d43e9dba41 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Thu, 28 Apr 2016 13:35:55 +0200 Subject: Modifiing MOASessionDBUtils --- .../moa/id/config/ConfigurationProviderImpl.java | 6 +- .../gv/egovernment/moa/id/moduls/SSOManager.java | 7 +- .../id/protocols/pvp2x/AttributQueryAction.java | 7 +- .../storage/DBAuthenticationSessionStoreage.java | 54 ++--- .../src/main/resources/session.common.beans.xml | 54 +++++ .../SpringExpressionAwareProcessEngineTest.java | 2 +- .../moa/id/process/test/ProcessEngineTest.java | 2 +- .../moa/id/commons/db/MOASessionDBUtils.java | 229 +++++++++++---------- .../id/auth/MOAIDAuthSpringResourceProvider.java | 5 +- 9 files changed, 218 insertions(+), 148 deletions(-) create mode 100644 id/server/idserverlib/src/main/resources/session.common.beans.xml (limited to 'id') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java index 5c2f86732..a07099a93 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java @@ -185,6 +185,10 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider String propertyName = key.toString().substring(propPrefix.length()); moaSessionProp.put(propertyName, props.get(key.toString())); } + if (key.toString().startsWith(propPrefix+"dbcp")) { + String propertyName = "hibernate."+(key.toString().substring(propPrefix.length())); + moaSessionProp.put(propertyName, props.get(key.toString())); + } } // read Config Hibernate properties @@ -222,7 +226,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider config.addAnnotatedClass(InterfederationSessionStore.class); //config.addAnnotatedClass(ProcessInstanceStore.class); config.addProperties(moaSessionProp); - MOASessionDBUtils.initHibernate(config, moaSessionProp); + //MOASessionDBUtils.initHibernate(config, moaSessionProp); //initial advanced logging if (Boolean.valueOf(props.getProperty("configuration.advancedlogging.active", "false"))) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java index bc7dd272b..0799760ce 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java @@ -63,6 +63,7 @@ public class SSOManager { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; @Autowired protected AuthConfiguration authConfig; + @Autowired private MOASessionDBUtils moaSessionDBUtils; /** * Check if interfederation IDP is requested via HTTP GET parameter or if interfederation cookie exists. @@ -159,7 +160,7 @@ public class SSOManager { } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); - MOASessionDBUtils.delete(storedSession); + moaSessionDBUtils.delete(storedSession); } } @@ -200,7 +201,7 @@ public class SSOManager { public String existsOldSSOSession(String ssoId) { Logger.trace("Check that the SSOID has already been used"); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; @@ -289,7 +290,7 @@ public class SSOManager { //no local SSO session exist -> request interfederated IDP Logger.info("Delete interfederated IDP " + selectedIDP.getIdpurlprefix() + " from MOASession " + storedSession.getSessionid()); - MOASessionDBUtils.delete(selectedIDP); + moaSessionDBUtils.delete(selectedIDP); } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java index 2168316ab..98c6632f1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java @@ -80,6 +80,7 @@ public class AttributQueryAction implements IAction { @Autowired private AuthenticationDataBuilder authDataBuilder; @Autowired private IDPCredentialProvider pvpCredentials; @Autowired private AuthConfiguration authConfig; + @Autowired private MOASessionDBUtils moaSessionDBUtils; private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -198,7 +199,7 @@ public class AttributQueryAction implements IAction { ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { try { activeOA.setAttributeQueryUsed(true); - MOASessionDBUtils.saveOrUpdate(activeOA); + moaSessionDBUtils.saveOrUpdate(activeOA); } catch (MOADatabaseException e) { Logger.error("MOASession interfederation information can not stored to database.", e); @@ -251,11 +252,11 @@ public class AttributQueryAction implements IAction { //mark attribute request as used if (nextIDPInformation.isStoreSSOInformation()) { nextIDPInformation.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(nextIDPInformation); + moaSessionDBUtils.saveOrUpdate(nextIDPInformation); //delete federated IDP from Session } else { - MOASessionDBUtils.delete(nextIDPInformation); + moaSessionDBUtils.delete(nextIDPInformation); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java index 094e25040..cb470a7b9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -65,7 +65,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class DBAuthenticationSessionStoreage implements IAuthenticationSessionStoreage{ @Autowired AuthConfiguration authConfig; - + @Autowired MOASessionDBUtils moaSessionDBUtils; private static JsonMapper mapper = new JsonMapper(); @Override @@ -104,7 +104,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt encryptSession(session, dbsession); //store AssertionStore element to Database - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.info("Create MOASession with sessionID: " + id); return session; @@ -166,7 +166,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt dbsession.setAdditionalInformation( mapper.serialize(sessionExtensions)); - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.debug("MOASession with sessionID=" + sessionID + " is stored in Database"); @@ -193,7 +193,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt dbsession.setAuthenticated(session.isAuthenticated()); dbsession.setUpdated(new Date()); - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.debug("MOASession with sessionID=" + session.getSessionID() + " is stored in Database"); } catch (MOADatabaseException e) { @@ -205,7 +205,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public void destroySession(String moaSessionID) throws MOADatabaseException { - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -257,7 +257,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 dbsession.setUpdated(new Date()); - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.trace("Change SessionID complete."); @@ -281,7 +281,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt try { session = searchInDatabase(moaSessionID, true); session.setAuthenticated(isAuthenticated); - MOASessionDBUtils.saveOrUpdate(session); + moaSessionDBUtils.saveOrUpdate(session); } catch (MOADatabaseException e) { @@ -293,7 +293,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public String getMOASessionSSOID(String SSOSessionID) { MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID"); Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -346,7 +346,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //TODO: is this method really needed?? MiscUtil.assertNotNull(SSOId, "SSOSessionID"); Logger.trace("Get authenticated session with SSOID " + SSOId + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -387,7 +387,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt try { - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Logger.trace("Add SSO information to session " + moaSessionID); @@ -495,7 +495,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); oas.addAll(dbsession.getActiveOAsessions()); - session = MOASessionDBUtils.getCurrentSession(); + session = moaSessionDBUtils.getCurrentSession(); session.getTransaction().commit(); return oas; @@ -525,7 +525,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); idps.addAll(dbsession.getInderfederation()); - session = MOASessionDBUtils.getCurrentSession(); + session = moaSessionDBUtils.getCurrentSession(); session.getTransaction().commit(); return idps; @@ -552,7 +552,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(userNameID, "userNameID"); Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " + oaID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); Transaction tx = null; List result = null;; @@ -598,7 +598,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(protocolType, "usedProtocol"); Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID " + oaID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -640,7 +640,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt try { MiscUtil.assertNotNull(nameID, "nameID"); Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; @@ -677,7 +677,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID) { MiscUtil.assertNotNull(sessionID, "MOASession"); Logger.trace("Get interfederated IDP for SSO with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -714,7 +714,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(sessionID, "MOASession"); MiscUtil.assertNotNull(idpID, "Interfederated IDP ID"); Logger.trace("Get interfederated IDP "+ idpID + " for SSO with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -818,7 +818,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //store AssertionStore element to Database try { - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); } catch (MOADatabaseException e) { Logger.warn("MOASession could not be created."); @@ -831,7 +831,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(String moaSessionID) { MiscUtil.assertNotNull(moaSessionID, "MOASessionID"); Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -872,7 +872,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID"); Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; @@ -907,7 +907,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } - MOASessionDBUtils.saveOrUpdate(authsession); + moaSessionDBUtils.saveOrUpdate(authsession); return true; } catch (Throwable e) { @@ -922,7 +922,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt Date expioredateupdate = new Date(now.getTime() - authDataTimeOutUpdated); List results; - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); Transaction tx = null; try { synchronized (session) { @@ -972,26 +972,26 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } - private static void cleanDelete(AuthenticatedSessionStore result) { + private void cleanDelete(AuthenticatedSessionStore result) { try { result.setSession("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(result); + moaSessionDBUtils.saveOrUpdate(result); } catch (MOADatabaseException e) { Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e); } finally { - if (!MOASessionDBUtils.delete(result)) + if (!moaSessionDBUtils.delete(result)) Logger.error("Authenticated session with sessionID=" + result.getSessionid() + " not removed! (Error during Database communication)"); } } @SuppressWarnings("rawtypes") - private static AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException { + private AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException { MiscUtil.assertNotNull(sessionID, "moasessionID"); Logger.trace("Get authenticated session with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; diff --git a/id/server/idserverlib/src/main/resources/session.common.beans.xml b/id/server/idserverlib/src/main/resources/session.common.beans.xml new file mode 100644 index 000000000..abc3c3200 --- /dev/null +++ b/id/server/idserverlib/src/main/resources/session.common.beans.xml @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + org.hibernate.dialect.MySQLDialect + ${moasession.hibernate.show_sql} + update + thread + true + true + + + + + + + + + \ No newline at end of file diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java index 2cb2a3278..b308e2fa8 100644 --- a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java @@ -78,7 +78,7 @@ public class SpringExpressionAwareProcessEngineTest { config.addProperties(props); //config.addAnnotatedClass(ProcessInstanceStore.class); config.addAnnotatedClass(AssertionStore.class); - MOASessionDBUtils.initHibernate(config, props); + //MOASessionDBUtils.initHibernate(config, props); } catch (Exception e) { e.printStackTrace(); } diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java index a7e351e25..197627a66 100644 --- a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java @@ -73,7 +73,7 @@ public class ProcessEngineTest { config.addProperties(props); //config.addAnnotatedClass(ProcessInstanceStore.class); config.addAnnotatedClass(AssertionStore.class); - MOASessionDBUtils.initHibernate(config, props); + //MOASessionDBUtils.initHibernate(config, props); } catch (Exception e) { e.printStackTrace(); } 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 ecb13ef34..88de9ceb5 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 @@ -24,62 +24,67 @@ package at.gv.egovernment.moa.id.commons.db; import java.util.Properties; -import org.apache.commons.lang3.StringUtils; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; -import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; -import org.hibernate.service.ServiceRegistry; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.logging.Logger; -public final class MOASessionDBUtils { +@Transactional +public class MOASessionDBUtils { - private static SessionFactory sessionFactory; - private static ServiceRegistry serviceRegistry; - - @SuppressWarnings("rawtypes") - private static final ThreadLocal THREAD_LOCAL = new ThreadLocal(); - private static boolean automaticSessionHandling = false; - private static final String[] AUTOMATIC_SESSION_HANDLING_VALUES = new String[] { "jta", "thread" }; - private static final String SESSION_HANDLING_KEY = "hibernate.current_session_context_class"; + private SessionFactory sessionFactory; +// private static ServiceRegistry serviceRegistry; - protected MOASessionDBUtils() { } +// @SuppressWarnings("rawtypes") +// private static final ThreadLocal THREAD_LOCAL = new ThreadLocal(); +// private static boolean automaticSessionHandling = false; + +// private static final String[] AUTOMATIC_SESSION_HANDLING_VALUES = new String[] { "jta", "thread" }; +// private static final String SESSION_HANDLING_KEY = "hibernate.current_session_context_class"; + @Autowired + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } - public static void initHibernate(Configuration config, Properties hibernateProperties) { - - String scm = StringUtils.trimToNull(hibernateProperties.getProperty(SESSION_HANDLING_KEY)); - if (scm != null) { - automaticSessionHandling = scm.indexOf(AUTOMATIC_SESSION_HANDLING_VALUES[0]) != -1 || scm.indexOf(AUTOMATIC_SESSION_HANDLING_VALUES[1]) != -1; - } - Logger.debug("Evaluating hibernate property \"" + SESSION_HANDLING_KEY + "\"."); - if (automaticSessionHandling) { - Logger.info("Hibernate is automatically handling session context management."); - } else { - Logger.info("Hibernate is NOT automatically handling session context management. Using build-in ThreadLocal session handling."); - } - try { - //Create the SessionFactory - Logger.debug("Creating initial MOASession session factory..."); - - config.configure("hibernate_moasession.cfg.xml"); - //serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); - - serviceRegistry = new StandardServiceRegistryBuilder(). - applySettings(config.getProperties()).build(); - - sessionFactory = config.buildSessionFactory(serviceRegistry); - Logger.debug("Initial MOASession session factory successfully created."); - - } catch (Throwable ex) { - Logger.error("Initial MOASession session factory creation failed: " + ex.getMessage()); - throw new ExceptionInInitializerError(ex); - } - } + public void initHibernate(Configuration config, Properties hibernateProperties) { +// +// String scm = StringUtils.trimToNull(hibernateProperties.getProperty(SESSION_HANDLING_KEY)); +// if (scm != null) { +// automaticSessionHandling = scm.indexOf(AUTOMATIC_SESSION_HANDLING_VALUES[0]) != -1 || scm.indexOf(AUTOMATIC_SESSION_HANDLING_VALUES[1]) != -1; +// } +// Logger.debug("Evaluating hibernate property \"" + SESSION_HANDLING_KEY + "\"."); +// if (automaticSessionHandling) { +// Logger.info("Hibernate is automatically handling session context management."); +// } else { +// Logger.info("Hibernate is NOT automatically handling session context management. Using build-in ThreadLocal session handling."); +// } +// try { +// //Create the SessionFactory +// Logger.debug("Creating initial MOASession session factory..."); +// +// config.configure("hibernate_moasession.cfg.xml"); +// //serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); +// +// // serviceRegistry = new StandardServiceRegistryBuilder(). +// // applySettings(config.getProperties()).build(); +// +// //dbSessionSessionFactory = config.buildSessionFactory(serviceRegistry); +// +// Logger.debug("Initial MOASession session factory successfully created."); +// +// } catch (Throwable ex) { +// Logger.error("Initial MOASession session factory creation failed: " + ex.getMessage()); +// throw new ExceptionInInitializerError(ex); +// } + } /** * Checks if a session factory is currently available. If necessary a new @@ -89,37 +94,39 @@ public final class MOASessionDBUtils { * @throws HibernateException * thrown if a hibernate error occurs */ - public static Session getCurrentSession() { - if (automaticSessionHandling) { - return sessionFactory.getCurrentSession(); - } - Session session = (Session) THREAD_LOCAL.get(); - // Open a new Session, if this Thread has none yet - if (session == null || !session.isConnected()) { - session = getNewSession(); - } - return session; + public Session getCurrentSession() { + return sessionFactory.getCurrentSession(); +// if (automaticSessionHandling) { +// return dbSessionSessionFactory.getCurrentSession(); +// } +// Session session = (Session) THREAD_LOCAL.get(); +// // Open a new Session, if this Thread has none yet +// if (session == null || !session.isConnected()) { +// session = getNewSession(); +// } +// return session; } @SuppressWarnings("unchecked") - public static Session getNewSession() { - if (automaticSessionHandling) { - Logger.warn("Session is being automatically handled by hibernate. Therefore this session maybe not being newly created. Use HibernateUtil.getCurrentSession() instead."); - return sessionFactory.getCurrentSession(); - } - Session session = (Session) THREAD_LOCAL.get(); - if (session != null) { - Logger.warn("Previous MOASession session has not been closed; closing session now."); - closeSession(); - } - Logger.debug("Opening new MOASession hibernate session..."); - try { - session = sessionFactory.openSession(); - THREAD_LOCAL.set(session); - } catch (HibernateException hex) { - Logger.error(hex.getMessage()); - } - return session; + public Session getNewSession() { + return sessionFactory.getCurrentSession(); +// if (automaticSessionHandling) { +// Logger.warn("Session is being automatically handled by hibernate. Therefore this session maybe not being newly created. Use HibernateUtil.getCurrentSession() instead."); +// return dbSessionSessionFactory.getCurrentSession(); +// } +// Session session = (Session) THREAD_LOCAL.get(); +// if (session != null) { +// Logger.warn("Previous MOASession session has not been closed; closing session now."); +// closeSession(); +// } +// Logger.debug("Opening new MOASession hibernate session..."); +// try { +// session = dbSessionSessionFactory.openSession(); +// THREAD_LOCAL.set(session); +// } catch (HibernateException hex) { +// Logger.error(hex.getMessage()); +// } +// return session; } /** @@ -130,61 +137,63 @@ public final class MOASessionDBUtils { * occurs. */ @SuppressWarnings("unchecked") - public static void closeSession() { - if (automaticSessionHandling) { - Logger.warn("Session is being automatically handled by hibernate. Therefore the current session cannot be closed on demand."); - return; - } - Logger.debug("Closing current MOASession hibernate session..."); - Session session = (Session) THREAD_LOCAL.get(); - THREAD_LOCAL.set(null); - if (session != null) { - try { - session.close(); - - } catch (HibernateException hex) { - Logger.error(hex.getMessage()); - } - } + public void closeSession() { + return; +// if (automaticSessionHandling) { +// Logger.warn("Session is being automatically handled by hibernate. Therefore the current session cannot be closed on demand."); +// return; +// } +// Logger.debug("Closing current MOASession hibernate session..."); +// Session session = (Session) THREAD_LOCAL.get(); +// THREAD_LOCAL.set(null); +// if (session != null) { +// try { +// session.close(); +// +// } catch (HibernateException hex) { +// Logger.error(hex.getMessage()); +// } +// } } - public static boolean saveOrUpdate(Object dbo) throws MOADatabaseException { - Transaction tx = null; + public boolean saveOrUpdate(Object dbo) throws MOADatabaseException { + // Transaction tx = null; try { - Session session = MOASessionDBUtils.getCurrentSession(); - - synchronized (session) { - tx = session.beginTransaction(); - session.saveOrUpdate(dbo); - tx.commit(); - } - return true; + Session session = sessionFactory.getCurrentSession(); + session.saveOrUpdate(dbo); + return true; +// +// synchronized (session) { +// tx = session.beginTransaction(); +// session.saveOrUpdate(dbo); +// tx.commit(); +// } +// return true; } catch(HibernateException e) { Logger.warn("Error during MOASession database saveOrUpdate. Rollback.", e); - if (tx != null) - tx.rollback(); + throw new MOADatabaseException(e); } } - public static boolean delete(Object dbo) { - Transaction tx = null; + public boolean delete(Object dbo) { + //Transaction tx = null; try { - Session session = MOASessionDBUtils.getCurrentSession(); - - synchronized (session) { - tx = session.beginTransaction(); - session.delete(dbo); - tx.commit(); - } + Session session = sessionFactory.getCurrentSession(); + session.delete(dbo); +// synchronized (session) { +// tx = session.beginTransaction(); +// session.delete(dbo); +// tx.commit(); +// } return true; } catch(HibernateException e) { Logger.warn("Error during MOASession database delete. Rollback.", e); - if (tx != null) - tx.rollback(); +// if (tx != null) +// tx.rollback(); return false; } } diff --git a/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java b/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java index 47857bcfb..bfa1baddd 100644 --- a/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java +++ b/id/server/moa-id-spring-initializer/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java @@ -40,10 +40,11 @@ public class MOAIDAuthSpringResourceProvider implements SpringResourceProvider { public Resource[] getResourcesToLoad() { ClassPathResource moaidauthConfig = new ClassPathResource("/moaid.configuration.beans.xml", MOAIDAuthInitializer.class); ClassPathResource configurationDBConfig = new ClassPathResource("/configuration.beans.xml", MOAIDAuthInitializer.class); - ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthInitializer.class); + ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthInitializer.class); + ClassPathResource moaSessionCommonBeans = new ClassPathResource("/session.common.beans.xml", MOAIDAuthInitializer.class); ClassPathResource moaSessionDBBeans = new ClassPathResource("/session.db.beans.xml", MOAIDAuthInitializer.class); ClassPathResource moaSessionRedisBeans = new ClassPathResource("/session.redis.beans.xml", MOAIDAuthInitializer.class); - return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans, moaSessionDBBeans, moaSessionRedisBeans}; + return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans, moaSessionDBBeans, moaSessionRedisBeans, moaSessionCommonBeans}; } -- cgit v1.2.3 From 42e40bb58ec9b4c6b7a474e058e79d366548a520 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Tue, 3 May 2016 11:38:51 +0200 Subject: Added Transactional Support to MOASessionDBUtils --- .../storage/DBAuthenticationSessionStoreage.java | 132 +++++++++++---------- .../src/main/resources/session.common.beans.xml | 2 +- .../src/main/resources/session.db.beans.xml | 19 --- .../moa/id/commons/db/MOASessionDBUtils.java | 119 +------------------ .../db/dao/session/AuthenticatedSessionStore.java | 4 +- .../moa/id/monitoring/DatabaseTestModule.java | 3 +- 6 files changed, 78 insertions(+), 201 deletions(-) (limited to 'id') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java index cb470a7b9..4d7936f25 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -35,6 +35,7 @@ import org.hibernate.Transaction; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonProcessingException; @@ -74,7 +75,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt AuthenticatedSessionStore session; try { - session = searchInDatabase(moaSessionID, true); + session = searchInDatabase(moaSessionID); return session.isAuthenticated(); } catch (MOADatabaseException e) { @@ -128,7 +129,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return null; try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); return decryptSession(dbsession); } catch (MOADatabaseException e) { @@ -143,7 +144,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); if (MiscUtil.isNotEmpty(dbsession.getAdditionalInformation())) { try { @@ -161,7 +162,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public void setAuthenticationSessionExtensions(String sessionID, AuthenticationSessionExtensions sessionExtensions) throws MOADatabaseException { try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); dbsession.setAdditionalInformation( mapper.serialize(sessionExtensions)); @@ -185,7 +186,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException { try { - AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); + AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID()); encryptSession(session, dbsession); @@ -216,6 +217,8 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt Query query = session.getNamedQuery("getSessionWithID"); query.setParameter("sessionid", moaSessionID); result = query.list(); + + Logger.trace("Found entries: " + result.size()); @@ -243,7 +246,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public String changeSessionID(AuthenticationSession session, String newSessionID) throws BuildException, MOADatabaseException { - AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); + AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID()); Logger.debug("Change SessionID from " + session.getSessionID() + "to " + newSessionID); @@ -279,7 +282,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt AuthenticatedSessionStore session; try { - session = searchInDatabase(moaSessionID, true); + session = searchInDatabase(moaSessionID); session.setAuthenticated(isAuthenticated); moaSessionDBUtils.saveOrUpdate(session); @@ -331,7 +334,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public boolean isSSOSession(String sessionID) throws MOADatabaseException { try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); return dbsession.isSSOSession(); } catch (MOADatabaseException e) { @@ -487,63 +490,63 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public List getAllActiveOAFromMOASession(AuthenticationSession moaSession) { MiscUtil.assertNotNull(moaSession, "MOASession"); - Session session = null; - - try { - List oas = new ArrayList(); - - AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); - oas.addAll(dbsession.getActiveOAsessions()); - - session = moaSessionDBUtils.getCurrentSession(); - session.getTransaction().commit(); - - return oas; - - } 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().getStatus().equals(TransactionStatus.COMMITTED)) { - session.getTransaction().rollback(); - throw e; - - } - - } - - return null; + + Logger.trace("Get OAs for moaSession " + moaSession.getSessionID() + " from database."); + Session session = moaSessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getAllActiveOAsForSessionID"); + query.setParameter("sessionID", moaSession.getSessionID()); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + return result; + + } catch (Exception e) { + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) + tx.rollback(); + throw e; + } } @Override public List getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) { MiscUtil.assertNotNull(moaSession, "MOASession"); - Session session = null; - try { - List idps = new ArrayList(); - AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); - idps.addAll(dbsession.getInderfederation()); - - session = moaSessionDBUtils.getCurrentSession(); - session.getTransaction().commit(); - - return idps; - - } 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().getStatus().equals(TransactionStatus.COMMITTED)) { - session.getTransaction().rollback(); - throw e; - - } - - } - - return null; + + Logger.trace("Get active IDPs for moaSession " + moaSession.getSessionID() + " from database."); + Session session = moaSessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getAllActiveIDPsForSessionID"); + query.setParameter("sessionID", moaSession.getSessionID()); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + return result; + + } catch (Exception e) { + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) + tx.rollback(); + throw e; + } } @Override @@ -756,7 +759,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt String moaSession = getMOASessionSSOID(req.getMOASessionIdentifier()); if (MiscUtil.isNotEmpty(moaSession)) { try { - dbsession = searchInDatabase(moaSession, true); + dbsession = searchInDatabase(moaSession); }catch (MOADatabaseException e) { Logger.error("NO MOASession found but MOASession MUST already exist!"); @@ -988,7 +991,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @SuppressWarnings("rawtypes") - private AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException { + private AuthenticatedSessionStore searchInDatabase(String sessionID) throws MOADatabaseException { MiscUtil.assertNotNull(sessionID, "moasessionID"); Logger.trace("Get authenticated session with sessionID " + sessionID + " from database."); Session session = moaSessionDBUtils.getCurrentSession(); @@ -1003,8 +1006,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt result = query.list(); //send transaction - if (commit) - tx.commit(); + tx.commit(); } Logger.trace("Found entries: " + result.size()); @@ -1019,7 +1021,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return (AuthenticatedSessionStore) result.get(0); } catch (Exception e) { - if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED) && commit) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } diff --git a/id/server/idserverlib/src/main/resources/session.common.beans.xml b/id/server/idserverlib/src/main/resources/session.common.beans.xml index abc3c3200..300bbd463 100644 --- a/id/server/idserverlib/src/main/resources/session.common.beans.xml +++ b/id/server/idserverlib/src/main/resources/session.common.beans.xml @@ -1,5 +1,5 @@ - - - - - - - - - - - - - - - - - - - - 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 88de9ceb5..fbbaf9476 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 @@ -41,49 +41,14 @@ public class MOASessionDBUtils { private SessionFactory sessionFactory; -// private static ServiceRegistry serviceRegistry; - -// @SuppressWarnings("rawtypes") -// private static final ThreadLocal THREAD_LOCAL = new ThreadLocal(); -// private static boolean automaticSessionHandling = false; -// private static final String[] AUTOMATIC_SESSION_HANDLING_VALUES = new String[] { "jta", "thread" }; -// private static final String SESSION_HANDLING_KEY = "hibernate.current_session_context_class"; @Autowired public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public void initHibernate(Configuration config, Properties hibernateProperties) { -// -// String scm = StringUtils.trimToNull(hibernateProperties.getProperty(SESSION_HANDLING_KEY)); -// if (scm != null) { -// automaticSessionHandling = scm.indexOf(AUTOMATIC_SESSION_HANDLING_VALUES[0]) != -1 || scm.indexOf(AUTOMATIC_SESSION_HANDLING_VALUES[1]) != -1; -// } -// Logger.debug("Evaluating hibernate property \"" + SESSION_HANDLING_KEY + "\"."); -// if (automaticSessionHandling) { -// Logger.info("Hibernate is automatically handling session context management."); -// } else { -// Logger.info("Hibernate is NOT automatically handling session context management. Using build-in ThreadLocal session handling."); -// } -// try { -// //Create the SessionFactory -// Logger.debug("Creating initial MOASession session factory..."); -// -// config.configure("hibernate_moasession.cfg.xml"); -// //serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); -// -// // serviceRegistry = new StandardServiceRegistryBuilder(). -// // applySettings(config.getProperties()).build(); -// -// //dbSessionSessionFactory = config.buildSessionFactory(serviceRegistry); -// -// Logger.debug("Initial MOASession session factory successfully created."); -// -// } catch (Throwable ex) { -// Logger.error("Initial MOASession session factory creation failed: " + ex.getMessage()); -// throw new ExceptionInInitializerError(ex); -// } + } /** @@ -96,104 +61,30 @@ public class MOASessionDBUtils { */ public Session getCurrentSession() { return sessionFactory.getCurrentSession(); -// if (automaticSessionHandling) { -// return dbSessionSessionFactory.getCurrentSession(); -// } -// Session session = (Session) THREAD_LOCAL.get(); -// // Open a new Session, if this Thread has none yet -// if (session == null || !session.isConnected()) { -// session = getNewSession(); -// } -// return session; - } - - @SuppressWarnings("unchecked") - public Session getNewSession() { - return sessionFactory.getCurrentSession(); -// if (automaticSessionHandling) { -// Logger.warn("Session is being automatically handled by hibernate. Therefore this session maybe not being newly created. Use HibernateUtil.getCurrentSession() instead."); -// return dbSessionSessionFactory.getCurrentSession(); -// } -// Session session = (Session) THREAD_LOCAL.get(); -// if (session != null) { -// Logger.warn("Previous MOASession session has not been closed; closing session now."); -// closeSession(); -// } -// Logger.debug("Opening new MOASession hibernate session..."); -// try { -// session = dbSessionSessionFactory.openSession(); -// THREAD_LOCAL.set(session); -// } catch (HibernateException hex) { -// Logger.error(hex.getMessage()); -// } -// return session; - } - - /** - * Closes the current session. - * - * @throws HibernateException - * thrown if session is already closed or a hibernate error - * occurs. - */ - @SuppressWarnings("unchecked") - public void closeSession() { - return; -// if (automaticSessionHandling) { -// Logger.warn("Session is being automatically handled by hibernate. Therefore the current session cannot be closed on demand."); -// return; -// } -// Logger.debug("Closing current MOASession hibernate session..."); -// Session session = (Session) THREAD_LOCAL.get(); -// THREAD_LOCAL.set(null); -// if (session != null) { -// try { -// session.close(); -// -// } catch (HibernateException hex) { -// Logger.error(hex.getMessage()); -// } -// } } public boolean saveOrUpdate(Object dbo) throws MOADatabaseException { - // Transaction tx = null; try { Session session = sessionFactory.getCurrentSession(); - session.saveOrUpdate(dbo); + session.merge(dbo); return true; -// -// synchronized (session) { -// tx = session.beginTransaction(); -// session.saveOrUpdate(dbo); -// tx.commit(); -// } -// return true; } catch(HibernateException e) { - Logger.warn("Error during MOASession database saveOrUpdate. Rollback.", e); + Logger.warn("Error during MOASession database saveOrUpdate.", e); throw new MOADatabaseException(e); } } public boolean delete(Object dbo) { - //Transaction tx = null; + try { Session session = sessionFactory.getCurrentSession(); session.delete(dbo); -// synchronized (session) { -// tx = session.beginTransaction(); -// session.delete(dbo); -// tx.commit(); -// } - return true; } catch(HibernateException e) { - Logger.warn("Error during MOASession database delete. Rollback.", e); -// if (tx != null) -// tx.rollback(); + Logger.warn("Error during MOASession database delete. Rollback."); return false; } } diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java index 6333451b9..f5fc798b0 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/AuthenticatedSessionStore.java @@ -57,7 +57,9 @@ import org.hibernate.annotations.DynamicUpdate; @NamedQuery(name="getMOASessionWithNameIDandOAID", query = "select authenticatedsessionstore from AuthenticatedSessionStore authenticatedsessionstore join fetch authenticatedsessionstore.activeOAsessions activeOAsessions where activeOAsessions.oaurlprefix = :oaID and activeOAsessions.userNameID = :nameID"), @NamedQuery(name="getInterfederatedIDPForAttributeQueryWithSessionID", query = "select authenticatedsessionstore from AuthenticatedSessionStore authenticatedsessionstore join fetch authenticatedsessionstore.inderfederation inderfederations where inderfederations.attributesRequested is false and authenticatedsessionstore.sessionid = :sessionID"), @NamedQuery(name="getInterfederatedIDPForSSOWithSessionID", query = "select authenticatedsessionstore from AuthenticatedSessionStore authenticatedsessionstore join fetch authenticatedsessionstore.inderfederation inderfederations where inderfederations.attributesRequested is true and inderfederations.storeSSOInformation is true and authenticatedsessionstore.sessionid = :sessionID order by inderfederations.QAALevel DESC"), - @NamedQuery(name="getInterfederatedIDPForSSOWithSessionIDIDPID", query = "select authenticatedsessionstore from AuthenticatedSessionStore authenticatedsessionstore join fetch authenticatedsessionstore.inderfederation inderfederations where inderfederations.attributesRequested is true and authenticatedsessionstore.sessionid = :sessionID and inderfederations.idpurlprefix = :idpID") + @NamedQuery(name="getInterfederatedIDPForSSOWithSessionIDIDPID", query = "select authenticatedsessionstore from AuthenticatedSessionStore authenticatedsessionstore join fetch authenticatedsessionstore.inderfederation inderfederations where inderfederations.attributesRequested is true and authenticatedsessionstore.sessionid = :sessionID and inderfederations.idpurlprefix = :idpID"), + @NamedQuery(name="getAllActiveOAsForSessionID", query = "select activeOAsessions from AuthenticatedSessionStore authenticatedsessionstore join authenticatedsessionstore.activeOAsessions activeOAsessions where authenticatedsessionstore.sessionid = :sessionID "), + @NamedQuery(name="getAllActiveIDPsForSessionID", query = "select inderfederation from AuthenticatedSessionStore authenticatedsessionstore join authenticatedsessionstore.inderfederation inderfederation where authenticatedsessionstore.sessionid = :sessionID ") }) public class AuthenticatedSessionStore implements Serializable{ diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java index 5e4183146..f1561b6aa 100644 --- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java @@ -70,9 +70,10 @@ public class DatabaseTestModule implements TestModuleInterface{ Date expioredate = new Date(new Date().getTime() - 120); + MOASessionDBUtils dbUtils = new MOASessionDBUtils(); try { List results; - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = dbUtils.getCurrentSession(); synchronized (session) { session.beginTransaction(); -- cgit v1.2.3 From 33da825e528c4b04bba9de09ed386bcf606aec39 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Tue, 3 May 2016 13:39:09 +0200 Subject: added redis config parameters --- id/server/idserverlib/src/main/resources/session.redis.beans.xml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'id') diff --git a/id/server/idserverlib/src/main/resources/session.redis.beans.xml b/id/server/idserverlib/src/main/resources/session.redis.beans.xml index 421159d08..9caf5fc6a 100644 --- a/id/server/idserverlib/src/main/resources/session.redis.beans.xml +++ b/id/server/idserverlib/src/main/resources/session.redis.beans.xml @@ -18,7 +18,9 @@ + p:use-pool="${redis.use-pool}" + p:host-name="${redis.host-name}" + p:port="${redis.port}"/> -- cgit v1.2.3 From 3d88ece5e3ed76f9a023681d5cd2d5a19a863c6f Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Wed, 18 May 2016 13:36:13 +0200 Subject: Spring-ified AuthenticationSessionCleaner --- .../moa/id/auth/AuthenticationSessionCleaner.java | 29 +++++----------------- 1 file changed, 6 insertions(+), 23 deletions(-) (limited to 'id') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java index e0552c337..bbb322a4f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java @@ -8,6 +8,8 @@ import java.util.List; import org.hibernate.HibernateException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; @@ -29,6 +31,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @version $Id$ */ @Service("AuthenticationSessionCleaner") +@EnableScheduling public class AuthenticationSessionCleaner implements Runnable { @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @@ -36,7 +39,7 @@ public class AuthenticationSessionCleaner implements Runnable { @Autowired protected AuthConfiguration authConfig; /** interval the AuthenticationSessionCleaner is run in */ - private static final long SESSION_CLEANUP_INTERVAL = 5 * 60; // 5 min + private static final long SESSION_CLEANUP_INTERVAL = 5 * 60 *1000 ; // 5 min /** * Runs the thread. Cleans the AuthenticationServer session store @@ -45,8 +48,8 @@ public class AuthenticationSessionCleaner implements Runnable { * Cleans up expired session and authentication data stores. * */ + @Scheduled(fixedRate = SESSION_CLEANUP_INTERVAL) public void run() { - while (true) { try { Logger.debug("AuthenticationSessionCleaner run"); Date now = new Date(); @@ -66,7 +69,7 @@ public class AuthenticationSessionCleaner implements Runnable { try { try { Object entry = transactionStorage.get(entryKey); - //if entry is an exception --> log it because is could be unhandled + //if entry is an exception --> log it because it could be unhandled if (entry != null && entry instanceof ExceptionContainer) { ExceptionContainer exContainer = (ExceptionContainer) entry; @@ -115,12 +118,6 @@ public class AuthenticationSessionCleaner implements Runnable { } catch (Exception e) { Logger.error(MOAIDMessageProvider.getInstance().getMessage("cleaner.01", null), e); } - try { - Thread.sleep(SESSION_CLEANUP_INTERVAL * 1000); - } - catch (InterruptedException e) { - } - } } /** @@ -143,18 +140,4 @@ public class AuthenticationSessionCleaner implements Runnable { } } } - - /** - * start the sessionCleaner - */ - public static void start(Runnable clazz) { - // start the session cleanup thread - Thread sessionCleaner = - new Thread(clazz, "AuthenticationSessionCleaner"); - sessionCleaner.setName("SessionCleaner"); - sessionCleaner.setDaemon(true); - sessionCleaner.setPriority(Thread.MIN_PRIORITY); - sessionCleaner.start(); - } - } -- cgit v1.2.3 From 9e5fefab3ea53859e31af25c5fd3e68a23fe9883 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Wed, 18 May 2016 13:39:45 +0200 Subject: changed constants to final static hash map --- .../moa/id/auth/MOAIDAuthInitializer.java | 11 -- .../java/at/gv/egovernment/moa/util/Constants.java | 13 +- .../moa/id/auth/servlet/MonitoringController.java | 136 +++++++++++++++++++++ .../moa/id/auth/servlet/MonitoringServlet.java | 136 --------------------- 4 files changed, 148 insertions(+), 148 deletions(-) create mode 100644 id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java delete mode 100644 id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java (limited to 'id') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index d1cf3338a..926131b59 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -109,12 +109,6 @@ public class MOAIDAuthInitializer { // Initializes SSLSocketFactory store SSLUtils.initialize(); - // Initializes Namespace Map - Constants.nSMap.put(Constants.SAML_PREFIX, Constants.SAML_NS_URI); - Constants.nSMap.put(Constants.ECDSA_PREFIX, - "http://www.w3.org/2001/04/xmldsig-more#"); - Constants.nSMap.put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); - //seed the random number generator Random.seedRandom(); Logger.debug("Random-number generator is seeded."); @@ -157,11 +151,6 @@ public class MOAIDAuthInitializer { } - - // Starts the session cleaner thread to remove unpicked authentication data - AuthenticationSessionCleaner sessioncleaner = rootContext.getBean("AuthenticationSessionCleaner", AuthenticationSessionCleaner.class); - AuthenticationSessionCleaner.start(sessioncleaner); - MOAGarbageCollector.start(); } } diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java index 5a5f4edac..260b2ecb1 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/util/Constants.java @@ -24,7 +24,10 @@ package at.gv.egovernment.moa.util; +import java.util.Collections; import java.util.HashMap; +import java.util.Map; + /** * Contains various constants used throughout the system. @@ -509,6 +512,14 @@ public interface Constants { /** * A map used to map namespace prefixes to namespace URIs */ - public static HashMap nSMap = new HashMap(5); + public static final Map nSMap = Collections.unmodifiableMap(new HashMap(){ + private static final long serialVersionUID = 3845384324295136490L; + { + put(Constants.SAML_PREFIX, Constants.SAML_NS_URI); + put(Constants.ECDSA_PREFIX, "http://www.w3.org/2001/04/xmldsig-more#"); + put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + } + }); + } diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java new file mode 100644 index 000000000..70448ef09 --- /dev/null +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + ******************************************************************************/ +package at.gv.egovernment.moa.id.auth.servlet; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.List; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.monitoring.TestManager; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +@Controller +public class MonitoringServlet { + + private static final String REQUEST_ATTR_MODULE = "module"; + + @Autowired private AuthConfiguration authConfig; + + public MonitoringServlet() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + " with mapping '/MonitoringServlet'."); + } + + @RequestMapping(value = "/MonitoringServlet", method = RequestMethod.GET) + public void getStatusInformation(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + + try { + if (authConfig.isMonitoringActive()) { + Logger.debug("Monitoring Servlet received request"); + + TestManager tests = TestManager.getInstance(); + + String modulename = req.getParameter(REQUEST_ATTR_MODULE); + if (MiscUtil.isEmpty(modulename)) { + + List error = tests.executeTests(); + if (error != null && error.size() > 0) { + createErrorMessage(req, resp, error); + + } else { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("text/html;charset=UTF-8"); + resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); + Logger.info("Monitoring Servlet finished without errors"); + } + + } else { + if (tests.existsModule(modulename)) { + List errors = tests.executeTest(modulename); + if (errors != null && errors.size() > 0) { + createErrorMessage(req, resp, errors); + + } else { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("text/html;charset=UTF-8"); + resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); + Logger.info("Monitoring Servlet finished without errors"); + } + + } else { + Logger.warn("NO Testmodule exists with modulename " + modulename); + resp.setStatus(HttpServletResponse.SC_NOT_FOUND); + resp.setContentType("text/html;charset=UTF-8"); + PrintWriter out; + try { + out = new PrintWriter(resp.getOutputStream()); + out.write("NO Testmodule exists with modulename " + modulename); + out.flush(); + + } catch (IOException e) { + Logger.warn("Internal Monitoring Servlet Error. ", e); + } + } + + } + } + + } catch (ConfigurationException e) { + createErrorMessage(req, resp, Arrays.asList(e.getMessage())); + } + } + + private void createErrorMessage(HttpServletRequest req, HttpServletResponse resp, List errorMessage) { + Logger.warn("Monitoring Servlet found some Error: " + errorMessage); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.setContentType("text/html;charset=UTF-8"); + PrintWriter out; + try { + out = new PrintWriter(resp.getOutputStream()); + for (String error : errorMessage) + out.write(error + "
"); + out.flush(); + + } catch (IOException e) { + Logger.warn("Internal Monitoring Servlet Error. ", e); + } + } + + private String getHtml(String text) { + return "Reponse" + text +""; + } +} diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java deleted file mode 100644 index 70448ef09..000000000 --- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.monitoring.TestManager; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -@Controller -public class MonitoringServlet { - - private static final String REQUEST_ATTR_MODULE = "module"; - - @Autowired private AuthConfiguration authConfig; - - public MonitoringServlet() { - super(); - Logger.debug("Registering servlet " + getClass().getName() + " with mapping '/MonitoringServlet'."); - } - - @RequestMapping(value = "/MonitoringServlet", method = RequestMethod.GET) - public void getStatusInformation(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - try { - if (authConfig.isMonitoringActive()) { - Logger.debug("Monitoring Servlet received request"); - - TestManager tests = TestManager.getInstance(); - - String modulename = req.getParameter(REQUEST_ATTR_MODULE); - if (MiscUtil.isEmpty(modulename)) { - - List error = tests.executeTests(); - if (error != null && error.size() > 0) { - createErrorMessage(req, resp, error); - - } else { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); - Logger.info("Monitoring Servlet finished without errors"); - } - - } else { - if (tests.existsModule(modulename)) { - List errors = tests.executeTest(modulename); - if (errors != null && errors.size() > 0) { - createErrorMessage(req, resp, errors); - - } else { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); - Logger.info("Monitoring Servlet finished without errors"); - } - - } else { - Logger.warn("NO Testmodule exists with modulename " + modulename); - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out; - try { - out = new PrintWriter(resp.getOutputStream()); - out.write("NO Testmodule exists with modulename " + modulename); - out.flush(); - - } catch (IOException e) { - Logger.warn("Internal Monitoring Servlet Error. ", e); - } - } - - } - } - - } catch (ConfigurationException e) { - createErrorMessage(req, resp, Arrays.asList(e.getMessage())); - } - } - - private void createErrorMessage(HttpServletRequest req, HttpServletResponse resp, List errorMessage) { - Logger.warn("Monitoring Servlet found some Error: " + errorMessage); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out; - try { - out = new PrintWriter(resp.getOutputStream()); - for (String error : errorMessage) - out.write(error + "
"); - out.flush(); - - } catch (IOException e) { - Logger.warn("Internal Monitoring Servlet Error. ", e); - } - } - - private String getHtml(String text) { - return "Reponse" + text +""; - } -} -- cgit v1.2.3 From 0cf75d5ee50f3c285a772ce96411f7bf98fe2a72 Mon Sep 17 00:00:00 2001 From: Christian Maierhofer Date: Wed, 18 May 2016 13:40:42 +0200 Subject: Adopted Monitoring Servlet --- .../moa/id/auth/servlet/MonitoringController.java | 88 ++++++++++------------ .../moa/id/monitoring/DatabaseTestModule.java | 8 +- .../MonitoringSpringResourceProvider.java | 29 +++++++ .../egovernment/moa/id/monitoring/TestManager.java | 58 +++++++------- ...iz.components.spring.api.SpringResourceProvider | 1 + .../src/main/resources/moaid_monitoring.beans.xml | 15 ++++ 6 files changed, 121 insertions(+), 78 deletions(-) create mode 100644 id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/MonitoringSpringResourceProvider.java create mode 100644 id/server/modules/module-monitoring/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider create mode 100644 id/server/modules/module-monitoring/src/main/resources/moaid_monitoring.beans.xml (limited to 'id') diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java index 70448ef09..8d324b535 100644 --- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringController.java @@ -24,7 +24,6 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; import java.io.PrintWriter; -import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; @@ -37,39 +36,51 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.monitoring.TestManager; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Controller -public class MonitoringServlet { +public class MonitoringController { private static final String REQUEST_ATTR_MODULE = "module"; @Autowired private AuthConfiguration authConfig; + @Autowired private TestManager tests; - public MonitoringServlet() { + public MonitoringController() { super(); Logger.debug("Registering servlet " + getClass().getName() + " with mapping '/MonitoringServlet'."); } @RequestMapping(value = "/MonitoringServlet", method = RequestMethod.GET) public void getStatusInformation(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + throws ServletException, IOException{ - try { - if (authConfig.isMonitoringActive()) { - Logger.debug("Monitoring Servlet received request"); + if (authConfig.isMonitoringActive()) { + Logger.debug("Monitoring Servlet received request"); - TestManager tests = TestManager.getInstance(); - - String modulename = req.getParameter(REQUEST_ATTR_MODULE); - if (MiscUtil.isEmpty(modulename)) { + + + String modulename = req.getParameter(REQUEST_ATTR_MODULE); + if (MiscUtil.isEmpty(modulename)) { + + List error = tests.executeTests(); + if (error != null && error.size() > 0) { + createErrorMessage(req, resp, error); + + } else { + resp.setStatus(HttpServletResponse.SC_OK); + resp.setContentType("text/html;charset=UTF-8"); + resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); + Logger.info("Monitoring Servlet finished without errors"); + } - List error = tests.executeTests(); - if (error != null && error.size() > 0) { - createErrorMessage(req, resp, error); + } else { + if (tests.existsModule(modulename)) { + List errors = tests.executeTest(modulename); + if (errors != null && errors.size() > 0) { + createErrorMessage(req, resp, errors); } else { resp.setStatus(HttpServletResponse.SC_OK); @@ -79,38 +90,21 @@ public class MonitoringServlet { } } else { - if (tests.existsModule(modulename)) { - List errors = tests.executeTest(modulename); - if (errors != null && errors.size() > 0) { - createErrorMessage(req, resp, errors); - - } else { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); - Logger.info("Monitoring Servlet finished without errors"); - } - - } else { - Logger.warn("NO Testmodule exists with modulename " + modulename); - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out; - try { - out = new PrintWriter(resp.getOutputStream()); - out.write("NO Testmodule exists with modulename " + modulename); - out.flush(); - - } catch (IOException e) { - Logger.warn("Internal Monitoring Servlet Error. ", e); - } - } - - } - } - - } catch (ConfigurationException e) { - createErrorMessage(req, resp, Arrays.asList(e.getMessage())); + Logger.warn("NO Testmodule exists with modulename " + modulename); + resp.setStatus(HttpServletResponse.SC_NOT_FOUND); + resp.setContentType("text/html;charset=UTF-8"); + PrintWriter out; + try { + out = new PrintWriter(resp.getOutputStream()); + out.write("NO Testmodule exists with modulename " + modulename); + out.flush(); + + } catch (IOException e) { + Logger.warn("Internal Monitoring Servlet Error. ", e); + } + } + + } } } diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java index f1561b6aa..b6d217e4c 100644 --- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java @@ -40,6 +40,12 @@ import at.gv.egovernment.moa.util.MiscUtil; public class DatabaseTestModule implements TestModuleInterface{ + private MOASessionDBUtils dbUtils; + + public DatabaseTestModule(MOASessionDBUtils dbUtils){ + this.dbUtils = dbUtils; + } + public List performTests() throws Exception { Logger.trace("Start MOA-ID Database Test."); @@ -70,7 +76,7 @@ public class DatabaseTestModule implements TestModuleInterface{ Date expioredate = new Date(new Date().getTime() - 120); - MOASessionDBUtils dbUtils = new MOASessionDBUtils(); + try { List results; Session session = dbUtils.getCurrentSession(); diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/MonitoringSpringResourceProvider.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/MonitoringSpringResourceProvider.java new file mode 100644 index 000000000..0f7dfc7fe --- /dev/null +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/MonitoringSpringResourceProvider.java @@ -0,0 +1,29 @@ +package at.gv.egovernment.moa.id.monitoring; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; + +public class MonitoringSpringResourceProvider implements SpringResourceProvider{ + + @Override + public String getName() { + // TODO Auto-generated method stub + return "MOA-ID Monitoring Module"; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Resource[] getResourcesToLoad() { + ClassPathResource monitoringResource = new ClassPathResource("/moaid_monitoring.beans.xml", MonitoringSpringResourceProvider.class); + + return new Resource[] {monitoringResource}; + } + +} diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java index b25eed520..b5ccd73f6 100644 --- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java @@ -27,49 +27,27 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; + import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.FileUtils; -public class TestManager { - - private static TestManager instance; +public class TestManager{ + @Autowired private MOASessionDBUtils moaSessionDBUtils; + @Autowired private AuthConfiguration authConfig; private Map tests = new HashMap(); - public static TestManager getInstance() throws ConfigurationException { - if (instance == null) - instance = new TestManager(); - - return instance; - } - - private TestManager() throws ConfigurationException { - - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - - //add Database test - DatabaseTestModule test1 = new DatabaseTestModule(); - tests.put(test1.getName(), test1); - - //add IdentityLink verification test - IdentityLinkTestModule test2 = new IdentityLinkTestModule(); - String idlurl = FileUtils.makeAbsoluteURL(config.getMonitoringTestIdentityLinkURL(), config.getRootConfigFileDir()); - try { - test2.initializeTest(0, idlurl); - tests.put(test2.getName(), test2);; - - } catch (Exception e) { - Logger.warn("MOA-ID IdentityLink Test can not performed without IdentityLink. Insert IdentityLink file to MOA-ID configuration", e); - } + public TestManager(){ + } public List executeTests() { Logger.debug("Start MOA-ID-Auth testing"); - List errors; for (TestModuleInterface test : tests.values()) { @@ -109,4 +87,24 @@ public class TestManager { public boolean existsModule(String modulename) { return tests.containsKey(modulename); } + + public void init() throws ConfigurationException{ + Logger.debug("Start initializing MOA-ID-Auth TestManager"); + + //add Database test + DatabaseTestModule test1 = new DatabaseTestModule(this.moaSessionDBUtils); + tests.put(test1.getName(), test1); + + //add IdentityLink verification test + IdentityLinkTestModule test2 = new IdentityLinkTestModule(); + String idlurl = FileUtils.makeAbsoluteURL(authConfig.getMonitoringTestIdentityLinkURL(), authConfig.getRootConfigFileDir()); + try { + test2.initializeTest(0, idlurl); + tests.put(test2.getName(), test2);; + + } catch (Exception e) { + Logger.warn("MOA-ID IdentityLink Test can not performed without IdentityLink. Insert IdentityLink file to MOA-ID configuration", e); + } + } + } diff --git a/id/server/modules/module-monitoring/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/id/server/modules/module-monitoring/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider new file mode 100644 index 000000000..b696bcdd7 --- /dev/null +++ b/id/server/modules/module-monitoring/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -0,0 +1 @@ +at.gv.egovernment.moa.id.monitoring.MonitoringSpringResourceProvider \ No newline at end of file diff --git a/id/server/modules/module-monitoring/src/main/resources/moaid_monitoring.beans.xml b/id/server/modules/module-monitoring/src/main/resources/moaid_monitoring.beans.xml new file mode 100644 index 000000000..41fab4444 --- /dev/null +++ b/id/server/modules/module-monitoring/src/main/resources/moaid_monitoring.beans.xml @@ -0,0 +1,15 @@ + + + + + \ No newline at end of file -- cgit v1.2.3