at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

Source

/*******************************************************************************
 * 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.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.SerializationUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
import at.gv.egovernment.moa.id.auth.exception.BuildException;
import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils;
import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore;
import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore;
import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore;
import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore;
import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
import at.gv.egovernment.moa.id.config.ConfigurationException;
import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
import at.gv.egovernment.moa.id.data.EncryptedData;
import at.gv.egovernment.moa.id.data.SLOInformationInterface;
import at.gv.egovernment.moa.id.moduls.IRequest;
import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAOImpl;
import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption;
import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor;
import at.gv.egovernment.moa.id.util.Random;
import at.gv.egovernment.moa.id.util.SessionEncrytionUtil;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.MiscUtil;

public class AuthenticationSessionStoreage {

    //private static HashMap<String, AuthenticationSession> sessionStore = new HashMap<String, AuthenticationSession>();

    public static boolean isAuthenticated(String moaSessionID) {

        AuthenticatedSessionStore session;

        try {
            session = searchInDatabase(moaSessionID, true);
            return session.isAuthenticated();

        } catch (MOADatabaseException e) {
            return false;
        }
    }

    public static AuthenticationSession createSession(String pendingRequestID)
            throws MOADatabaseException, BuildException {
        String id = Random.nextRandom();

        AuthenticatedSessionStore dbsession = new AuthenticatedSessionStore();
        dbsession.setSessionid(id);
        dbsession.setAuthenticated(false);

        //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1
        Date now = new Date();
        dbsession.setCreated(now);
        dbsession.setUpdated(now);

        dbsession.setPendingRequestID(pendingRequestID);

        AuthenticationSession session = new AuthenticationSession(id, now);
        encryptSession(session, dbsession);

        //store AssertionStore element to Database
        try {
            MOASessionDBUtils.saveOrUpdate(dbsession);
            Logger.info("MOASession with sessionID=" + id + " is stored in Database");

        } catch (MOADatabaseException e) {
            Logger.warn("MOASession could not be created.");
            throw new MOADatabaseException(e);
        }

        return session;
    }

    public static AuthenticationSession getSession(String sessionID) throws MOADatabaseException {

        try {
            AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
            return decryptSession(dbsession);

        } catch (MOADatabaseException e) {
            Logger.info("No MOA Session with id: " + sessionID);
            throw new MOADatabaseException("No MOA Session with id: " + sessionID);

        } catch (Throwable e) {
            Logger.warn("MOASession deserialization-exception by using MOASessionID=" + sessionID, e);
            throw new MOADatabaseException("MOASession deserialization-exception");
        }
    }

    public static void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException {
        storeSession(session, null);
    }

    public static void storeSession(AuthenticationSession session, String pendingRequestID)
            throws MOADatabaseException, BuildException {

        try {
            AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true);

            if (MiscUtil.isNotEmpty(pendingRequestID))
                dbsession.setPendingRequestID(pendingRequestID);

            encryptSession(session, dbsession);

            //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1
            dbsession.setAuthenticated(session.isAuthenticated());
            dbsession.setUpdated(new Date());

            MOASessionDBUtils.saveOrUpdate(dbsession);
            Logger.debug("MOASession with sessionID=" + session.getSessionID() + " is stored in Database");

        } catch (MOADatabaseException e) {
            Logger.warn("MOASession could not be stored.");
            throw new MOADatabaseException(e);
        }
    }

    public static void destroySession(String moaSessionID) throws MOADatabaseException {

        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {

            session.beginTransaction();
            Query query = session.getNamedQuery("getSessionWithID");
            query.setParameter("sessionid", moaSessionID);
            result = query.list();

            Logger.trace("Found entries: " + result.size());

            //Assertion requires an unique artifact
            if (result.size() != 1) {
                Logger.trace("No entries found.");
                throw new MOADatabaseException("No session found with this sessionID");
            }

            AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0);
            session.getTransaction().commit();
            cleanDelete(dbsession);
        }

    }

    public static String changeSessionID(AuthenticationSession session, String newSessionID)
            throws BuildException, AuthenticationException {
        try {
            AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true);

            Logger.debug("Change SessionID from " + session.getSessionID() + "to " + newSessionID);

            session.setSessionID(newSessionID);
            encryptSession(session, dbsession);

            dbsession.setSessionid(newSessionID);
            dbsession.setAuthenticated(session.isAuthenticated());

            //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1
            dbsession.setUpdated(new Date());

            MOASessionDBUtils.saveOrUpdate(dbsession);

            Logger.trace("Change SessionID complete.");

            return newSessionID;

        } catch (MOADatabaseException e) {
            throw new AuthenticationException("TODO!", null);
        }

    }

    public static String changeSessionID(AuthenticationSession session)
            throws AuthenticationException, BuildException {
        String id = Random.nextRandom();
        return changeSessionID(session, id);

    }

    public static void setAuthenticated(String moaSessionID, boolean value) {

        AuthenticatedSessionStore session;

        try {
            session = searchInDatabase(moaSessionID, true);
            session.setAuthenticated(value);
            MOASessionDBUtils.saveOrUpdate(session);

        } catch (MOADatabaseException e) {
            Logger.warn("isAuthenticated can not be stored in MOASession " + moaSessionID, e);
        }
    }

    public static String getMOASessionSSOID(String SSOSessionID) {
        MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID");
        Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getSessionWithSSOID");
            query.setParameter("sessionid", SSOSessionID);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() != 1) {
            Logger.trace("No entries found.");
            return null;

        } else {
            return result.get(0).getSessionid();

        }
    }

    public static boolean isSSOSession(String sessionID) throws MOADatabaseException {
        try {
            AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
            return dbsession.isSSOSession();

        } catch (MOADatabaseException e) {
            Logger.info("No MOA Session with id: " + sessionID);
            throw new MOADatabaseException("No MOA Session with id: " + sessionID);
        }
    }

    public static AuthenticatedSessionStore isValidSessionWithSSOID(String SSOId, String moaSessionId) {
        MiscUtil.assertNotNull(SSOId, "SSOSessionID");
        Logger.trace("Get authenticated session with SSOID " + SSOId + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getSessionWithSSOID");
            query.setParameter("sessionid", SSOId);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() != 1) {
            Logger.trace("No entries found.");
            return null;

        } else {
            return result.get(0);
        }
    }

    public static void addSSOInformation(String moaSessionID, String SSOSessionID, SLOInformationInterface SLOInfo,
            String OAUrl) throws AuthenticationException {

        AuthenticatedSessionStore dbsession;
        Transaction tx = null;

        try {

            Session session = MOASessionDBUtils.getCurrentSession();
            List<AuthenticatedSessionStore> result;

            Logger.trace("Add SSO information to session " + moaSessionID);

            synchronized (session) {

                tx = session.beginTransaction();
                Query query = session.getNamedQuery("getSessionWithID");
                query.setParameter("sessionid", moaSessionID);
                result = query.list();

                Logger.trace("Found entries: " + result.size());

                //Assertion requires an unique artifact
                if (result.size() != 1) {
                    Logger.trace("No entries found.");
                    tx.rollback();
                    throw new MOADatabaseException("No session found with this sessionID");
                }

                dbsession = (AuthenticatedSessionStore) result.get(0);

                OASessionStore activeOA = null;
                //check if OA already has an active OA session
                if (dbsession.getActiveOAsessions() != null) {
                    for (OASessionStore el : dbsession.getActiveOAsessions()) {
                        if (el.getOaurlprefix().equals(OAUrl))
                            activeOA = el;
                    }
                }

                if (activeOA == null)
                    activeOA = new OASessionStore();

                //set active OA applications
                activeOA.setOaurlprefix(OAUrl);
                activeOA.setMoasession(dbsession);
                activeOA.setCreated(new Date());

                //set additional information for SLO
                if (SLOInfo != null) {
                    activeOA.setAssertionSessionID(SLOInfo.getSessionIndex());
                    activeOA.setUserNameID(SLOInfo.getUserNameIdentifier());
                    activeOA.setUserNameIDFormat(SLOInfo.getUserNameIDFormat());
                    activeOA.setProtocolType(SLOInfo.getProtocolType());
                    activeOA.setAttributeQueryUsed(false);

                }

                List<OASessionStore> activeOAs = dbsession.getActiveOAsessions();
                activeOAs.add(activeOA);
                dbsession.setActiveOAsessions(activeOAs);

                //Store used SSOId 
                if (dbsession.getSSOsessionid() != null) {
                    OldSSOSessionIDStore oldSSOId = new OldSSOSessionIDStore();
                    oldSSOId.setOldsessionid(dbsession.getSSOsessionid());
                    oldSSOId.setMoasession(dbsession);

                    List<OldSSOSessionIDStore> oldSSOIds = dbsession.getOldssosessionids();
                    oldSSOIds.add(oldSSOId);
                }

                dbsession.setSSOSession(true);
                dbsession.setSSOsessionid(SSOSessionID);
                dbsession.setAuthenticated(false);
                dbsession.setPendingRequestID("empty");

                //Store MOASession
                session.saveOrUpdate(dbsession);

                //send transaction
                tx.commit();

                Logger.debug("Add SSO-Session login information for OA: " + OAUrl + " and AssertionID: "
                        + SLOInfo.getSessionIndex());
            }

        } catch (MOADatabaseException e) {
            throw new AuthenticationException("No MOASession found with Id=" + moaSessionID, null);

        } catch (HibernateException e) {
            Logger.warn("Error during database saveOrUpdate. Rollback.", e);
            tx.rollback();
            throw new AuthenticationException("SSO Session information can not be stored!  --> SSO is deactivated",
                    null);
        }
    }

    public static List<OASessionStore> getAllActiveOAFromMOASession(AuthenticationSession moaSession) {
        MiscUtil.assertNotNull(moaSession, "MOASession");

        try {
            List<OASessionStore> oas = new ArrayList<OASessionStore>();

            AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false);
            oas.addAll(dbsession.getActiveOAsessions());

            Session session = MOASessionDBUtils.getCurrentSession();
            session.getTransaction().commit();

            return oas;

        } catch (MOADatabaseException e) {
            Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e);

        }

        return null;
    }

    public static List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(
            AuthenticationSession moaSession) {
        MiscUtil.assertNotNull(moaSession, "MOASession");

        try {
            List<InterfederationSessionStore> idps = new ArrayList<InterfederationSessionStore>();
            AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false);
            idps.addAll(dbsession.getInderfederation());

            Session session = MOASessionDBUtils.getCurrentSession();
            session.getTransaction().commit();

            return idps;

        } catch (MOADatabaseException e) {
            Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e);

        }

        return null;
    }

    public static AuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID) {
        MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier");
        MiscUtil.assertNotNull(userNameID, "userNameID");
        Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " + oaID + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID");
            query.setParameter("oaID", oaID);
            query.setParameter("nameID", userNameID);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() != 1) {
            Logger.trace("No unique entry found.");
            return null;

        }
        try {
            return decryptSession(result.get(0));

        } catch (BuildException e) {
            Logger.warn(
                    "MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(),
                    e);
            return null;
        }
    }

    public static OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID,
            String protocolType) {
        MiscUtil.assertNotNull(moaSession, "MOASession");
        MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier");
        MiscUtil.assertNotNull(protocolType, "usedProtocol");
        Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID "
                + oaID + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol");
            query.setParameter("sessionID", moaSession.getSessionID());
            query.setParameter("oaID", oaID);
            query.setParameter("protocol", protocolType);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() == 0) {
            Logger.trace("No entries found.");
            return null;

        }

        return result.get(0).getActiveOAsessions().get(0);
    }

    public static String getPendingRequestID(String sessionID) {
        try {
            AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
            return dbsession.getPendingRequestID();

        } catch (MOADatabaseException e) {
            Logger.warn("MOASession with ID " + sessionID + " not found");
            return "";
        }
    }

    public static AuthenticationSession getSessionWithPendingRequestID(String pedingRequestID) {
        try {
            MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID");
            Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database.");
            Session session = MOASessionDBUtils.getCurrentSession();

            List<AuthenticatedSessionStore> result;

            synchronized (session) {
                session.beginTransaction();
                Query query = session.getNamedQuery("getSessionWithPendingRequestID");
                query.setParameter("sessionid", pedingRequestID);
                result = query.list();

                //send transaction
                session.getTransaction().commit();
            }

            Logger.trace("Found entries: " + result.size());

            //Assertion requires an unique artifact
            if (result.size() != 1) {
                Logger.trace("No entries found.");
                return null;
            }

            return decryptSession(result.get(0));

        } catch (Throwable e) {
            Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID);
            return null;
        }
    }

    public static boolean deleteSessionWithPendingRequestID(String id) {
        MiscUtil.assertNotNull(id, "PendingRequestID");
        Logger.trace("Delete MOAsession with PendingRequestID " + id + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getSessionWithPendingRequestID");
            query.setParameter("sessionid", id);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() != 1) {
            Logger.trace("No entries found.");
            return false;

        } else {
            cleanDelete(result.get(0));
            return true;
        }

    }

    public static AuthenticationSession getSessionWithUserNameID(String nameID) {

        try {
            MiscUtil.assertNotNull(nameID, "nameID");
            Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database.");
            Session session = MOASessionDBUtils.getCurrentSession();

            List<AuthenticatedSessionStore> result;

            synchronized (session) {
                session.beginTransaction();
                Query query = session.getNamedQuery("getMOAISessionWithUserNameID");
                query.setParameter("usernameid", StringEscapeUtils.escapeHtml(nameID));
                result = query.list();

                //send transaction
                session.getTransaction().commit();
            }

            Logger.trace("Found entries: " + result.size());

            //Assertion requires an unique artifact
            if (result.size() == 0) {
                Logger.trace("No entries found.");
                return null;
            }

            return decryptSession(result.get(0));

        } catch (Throwable e) {
            Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID);
            return null;
        }

    }

    public static InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID) {
        MiscUtil.assertNotNull(sessionID, "MOASession");
        Logger.trace("Get interfederated IDP for SSO with sessionID " + sessionID + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID");
            query.setParameter("sessionID", sessionID);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() == 0) {
            Logger.trace("No entries found.");
            return null;

        }

        return result.get(0).getInderfederation().get(0);
    }

    public static InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID,
            String idpID) {
        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();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID");
            query.setParameter("sessionID", sessionID);
            query.setParameter("idpID", idpID);
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() == 0) {
            Logger.trace("No entries found.");
            return null;

        }

        return result.get(0).getInderfederation().get(0);
    }

    public static String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID)
            throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException {
        AuthenticatedSessionStore dbsession = null;

        //search for active SSO session
        if (MiscUtil.isNotEmpty(ssoID)) {
            String moaSession = getMOASessionSSOID(ssoID);
            if (MiscUtil.isNotEmpty(moaSession)) {
                try {
                    dbsession = searchInDatabase(moaSession, true);

                } catch (MOADatabaseException e) {

                }
            }
        }

        String id = null;
        Date now = new Date();
        //create new MOASession if any exists
        AuthenticationSession session = null;
        if (dbsession == null) {
            id = Random.nextRandom();
            dbsession = new AuthenticatedSessionStore();
            dbsession.setSessionid(id);
            dbsession.setCreated(now);
            dbsession.setPendingRequestID(req.getRequestID());
            session = new AuthenticationSession(id, now);

        } else {
            id = dbsession.getSessionid();
            session = decryptSession(dbsession);

        }

        dbsession.setInterfederatedSSOSession(true);
        dbsession.setAuthenticated(isAuthenticated);
        dbsession.setUpdated(now);
        session.setAuthenticated(true);
        session.setAuthenticatedUsed(false);
        encryptSession(session, dbsession);

        //add interfederation information
        List<InterfederationSessionStore> idpList = dbsession.getInderfederation();
        InterfederationSessionStore idp = null;
        if (idpList == null) {
            idpList = new ArrayList<InterfederationSessionStore>();
            dbsession.setInderfederation(idpList);

        } else {
            for (InterfederationSessionStore el : idpList) {
                //resue old entry if interfederation IDP is reused for authentication
                if (el.getIdpurlprefix().equals(req.getInterfederationResponse().getEntityID()))
                    idp = el;

            }
        }

        //create new interfederation IDP entry
        if (idp == null) {
            idp = new InterfederationSessionStore();
            idp.setCreated(now);
            idp.setIdpurlprefix(req.getInterfederationResponse().getEntityID());

            try {
                OAAuthParameter oa = AuthConfigurationProvider.getInstance()
                        .getOnlineApplicationParameter(idp.getIdpurlprefix());
                idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed());

            } catch (ConfigurationException e) {
                Logger.warn("MOASession could not be created.");
                throw new MOADatabaseException(e);

            }
            idp.setMoasession(dbsession);
            idpList.add(idp);

        }
        AssertionAttributeExtractor extract = new AssertionAttributeExtractor(
                req.getInterfederationResponse().getResponse());
        idp.setSessionIndex(extract.getSessionIndex());
        idp.setUserNameID(extract.getNameID());
        idp.setAttributesRequested(false);
        idp.setQAALevel(extract.getQAALevel());

        //store AssertionStore element to Database
        try {
            MOASessionDBUtils.saveOrUpdate(dbsession);
            Logger.info("MOASession with sessionID=" + id + " is stored in Database");

        } catch (MOADatabaseException e) {
            Logger.warn("MOASession could not be created.");
            throw new MOADatabaseException(e);
        }

        return id;
    }

    public static InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(
            AuthenticationSession moaSession) {
        MiscUtil.assertNotNull(moaSession, "MOASession");
        Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSession.getSessionID()
                + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List<AuthenticatedSessionStore> result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID");
            query.setParameter("sessionID", moaSession.getSessionID());
            result = query.list();

            //send transaction
            session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() == 0) {
            Logger.trace("No entries found.");
            return null;

        }

        return result.get(0).getInderfederation().get(0);
    }

    /**
     * @param entityID
     * @param requestID
     */
    public static boolean removeInterfederetedSession(String entityID, String pedingRequestID) {

        try {
            Logger.debug("Remove interfederated IDP from local SSO session ...");

            MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID");
            Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database.");
            Session session = MOASessionDBUtils.getCurrentSession();

            List<AuthenticatedSessionStore> result;

            synchronized (session) {
                session.beginTransaction();
                Query query = session.getNamedQuery("getSessionWithPendingRequestID");
                query.setParameter("sessionid", pedingRequestID);
                result = query.list();

                //send transaction
                session.getTransaction().commit();
            }

            Logger.trace("Found entries: " + result.size());

            //Assertion requires an unique artifact
            if (result.size() != 1) {
                Logger.trace("No entries found.");
                return false;
            }

            AuthenticatedSessionStore authsession = result.get(0);

            List<InterfederationSessionStore> idpSessions = authsession.getInderfederation();
            if (idpSessions != null) {
                for (InterfederationSessionStore idp : idpSessions) {
                    if (idp.getIdpurlprefix().equals(entityID))
                        idpSessions.remove(idp);

                }
            }

            MOASessionDBUtils.saveOrUpdate(authsession);
            return true;

        } catch (Throwable e) {
            Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID);
            return false;
        }
    }

    public static void clean(long now, long authDataTimeOutCreated, long authDataTimeOutUpdated) {
        Date expioredatecreate = new Date(now - authDataTimeOutCreated);
        Date expioredateupdate = new Date(now - authDataTimeOutUpdated);

        List<AuthenticatedSessionStore> results;
        Session session = MOASessionDBUtils.getCurrentSession();

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getMOAISessionsWithTimeOut");
            query.setTimestamp("timeoutcreate", expioredatecreate);
            query.setTimestamp("timeoutupdate", expioredateupdate);
            results = query.list();
            session.getTransaction().commit();
        }

        if (results.size() != 0) {
            for (AuthenticatedSessionStore result : results) {
                try {
                    cleanDelete(result);
                    Logger.info("Authenticated session with sessionID=" + result.getSessionid()
                            + " after session timeout.");

                } catch (HibernateException e) {
                    Logger.warn("Authenticated session with sessionID=" + result.getSessionid()
                            + " not removed after timeout! (Error during Database communication)", e);
                }
            }
        }
    }

    private static void encryptSession(AuthenticationSession session, AuthenticatedSessionStore dbsession)
            throws BuildException {
        byte[] serialized = SerializationUtils.serialize(session);

        EncryptedData encdata = SessionEncrytionUtil.getInstance().encrypt(serialized);
        dbsession.setSession(encdata.getEncData());
        dbsession.setIv(encdata.getIv());
    }

    private static AuthenticationSession decryptSession(AuthenticatedSessionStore dbsession) throws BuildException {
        EncryptedData encdata = new EncryptedData(dbsession.getSession(), dbsession.getIv());
        byte[] decrypted = SessionEncrytionUtil.getInstance().decrypt(encdata);

        return (AuthenticationSession) SerializationUtils.deserialize(decrypted);

    }

    private static void cleanDelete(AuthenticatedSessionStore result) {

        try {
            AuthenticationSession session = getSession(result.getSessionid());
            if (session.getProcessInstanceId() != null) {
                ProcessInstanceStoreDAOImpl.getInstance().remove(session.getProcessInstanceId());
            }

        } catch (MOADatabaseException e) {
            Logger.warn("Removing process associated with moa session " + result.getSessionid() + " FAILED.", e);
        }

        try {
            result.setSession("blank".getBytes());
            MOASessionDBUtils.saveOrUpdate(result);

        } catch (MOADatabaseException e) {
            Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e);

        } finally {
            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 {
        MiscUtil.assertNotNull(sessionID, "moasessionID");
        Logger.trace("Get authenticated session with sessionID " + sessionID + " from database.");
        Session session = MOASessionDBUtils.getCurrentSession();

        List result;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getSessionWithID");
            query.setParameter("sessionid", sessionID);
            result = query.list();

            //send transaction
            if (commit)
                session.getTransaction().commit();
        }

        Logger.trace("Found entries: " + result.size());

        //Assertion requires an unique artifact
        if (result.size() != 1) {
            Logger.trace("No entries found.");
            throw new MOADatabaseException("No session found with this sessionID");
        }

        return (AuthenticatedSessionStore) result.get(0);
    }
}