Example usage for org.hibernate Query list

List of usage examples for org.hibernate Query list

Introduction

In this page you can find the example usage for org.hibernate Query list.

Prototype

List<R> list();

Source Link

Document

Return the query results as a List.

Usage

From source file:at.gv.egovernment.moa.id.monitoring.DatabaseTestModule.java

License:EUPL

private String testMOAAdvancedLoggingDatabase() {

    Date expioredate = new Date(new Date().getTime() - 120);
    try {//  w  w  w  .  j a va2  s.  c o  m
        Session session = StatisticLogDBUtils.getCurrentSession();

        List<StatisticLog> results;

        synchronized (session) {
            session.beginTransaction();
            Query query = session.getNamedQuery("getAllEntriesNotBeforeTimeStamp");
            query.setTimestamp("timeout", expioredate);
            results = query.list();
            session.getTransaction().commit();
        }

        Logger.trace("Finish Test: AdvancedLoggingDataBase");
        return null;

    } catch (Throwable e) {
        Logger.warn("Failed Test: AdvancedLoggingDataBase", e);
        return "AdvancedLoggingDataBase: " + e.getMessage();
    }
}

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.SingleLogOutAction.java

License:EUPL

@Override
public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq,
        HttpServletResponse httpResp, 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 = AuthenticationSessionStoreage.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");
            SSOManager ssomanager = SSOManager.getInstance();
            String ssoID = ssomanager.getSSOSessionID(httpReq);
            if (MiscUtil.isEmpty(ssoID)) {
                Logger.warn("Can not find active Session. Single LogOut not possible!");
                SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq);
                //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI);
                LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, null);
                Logger.info("Sending SLO success message to requester ...");
                SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp,
                        samlReq.getRelayState());
                return null;

            } else {
                String moasession = ssomanager.getMOASession(ssoID);
                try {
                    session = AuthenticationSessionStoreage.getSession(moasession);

                } catch (MOADatabaseException e) {
                    Logger.warn("Can not find active Session. Single LogOut not possible!");
                    SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq);
                    //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI);
                    LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq,
                            null);/*from  www.ja v  a 2  s .c  om*/
                    Logger.info("Sending SLO success message to requester ...");
                    SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp,
                            samlReq.getRelayState());
                    return null;

                }
            }
        }

        AuthenticationManager authManager = AuthenticationManager.getInstance();
        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

            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) {
                    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());

                if (data instanceof SLOInformationContainer) {
                    SLOInformationContainer sloContainer = (SLOInformationContainer) data;

                    //check status
                    SingleLogOutBuilder.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();

                            //sloContainer could be stored to database
                            storageSuccess = true;

                        } catch (HibernateException 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. ");

                        }

                        storageSuccess = true;
                        String redirectURL = null;
                        if (sloContainer.getSloRequest() != null) {
                            //send SLO response to SLO request issuer
                            SingleLogoutService sloService = SingleLogOutBuilder
                                    .getResponseSLODescriptor(sloContainer.getSloRequest());
                            LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService,
                                    sloContainer.getSloRequest(), sloContainer.getSloFailedOAs());
                            redirectURL = SingleLogOutBuilder.getFrontChannelSLOMessageURL(sloService, message,
                                    httpReq, httpResp,
                                    sloContainer.getSloRequest().getRequest().getRelayState());

                        } else {
                            //print SLO information directly
                            redirectURL = AuthConfigurationProvider.getInstance().getPublicURLPrefix()
                                    + "/idpSingleLogout";

                            String artifact = Random.nextRandom();

                            String statusCode = null;
                            if (sloContainer.getSloFailedOAs() == null
                                    || sloContainer.getSloFailedOAs().size() == 0)
                                statusCode = SLOSTATUS_SUCCESS;
                            else
                                statusCode = SLOSTATUS_ERROR;

                            AssertionStorage.getInstance().put(artifact, statusCode);
                            redirectURL = addURLParameter(redirectURL, PARAM_SLOSTATUS, artifact);

                        }
                        //redirect to Redirect Servlet
                        String url = AuthConfigurationProvider.getInstance().getPublicURLPrefix()
                                + "/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.wasCommitted()) {
                tx.commit();

            }
        }

    } else {
        Logger.error("Process SingleLogOutAction but request is NOT of type LogoutRequest or LogoutResponse.");
        throw new MOAIDException("pvp2.13", null);

    }

    return null;
}

From source file:at.gv.egovernment.moa.id.storage.AssertionStorage.java

License:EUPL

public void clean(long now, long authDataTimeOut) {
    Date expioredate = new Date(now - authDataTimeOut);

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

    synchronized (session) {
        session.beginTransaction();/*w  w w .j  a v  a2 s. co  m*/
        Query query = session.getNamedQuery("getAssertionWithTimeOut");
        query.setTimestamp("timeout", expioredate);
        results = query.list();
        session.getTransaction().commit();
    }

    if (results.size() != 0) {
        for (AssertionStore result : results) {
            try {
                cleanDelete(result);
                Logger.info("Remove sessioninformation with ID=" + result.getArtifact() + " after timeout.");

            } catch (HibernateException e) {
                Logger.warn("Sessioninformation with ID=" + result.getArtifact()
                        + " not removed after timeout! (Error during Database communication)", e);
            }

        }
    }
}

From source file:at.gv.egovernment.moa.id.storage.AssertionStorage.java

License:EUPL

@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;//from   www  .  j a va2 s.com

    synchronized (session) {
        session.beginTransaction();
        Query query = session.getNamedQuery("getAssertionWithArtifact");
        query.setParameter("artifact", artifact);
        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.");
        throw new MOADatabaseException("No sessioninformation found with this ID");
    }

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

From source file:at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

License:EUPL

public static void destroySession(String moaSessionID) throws MOADatabaseException {

    Session session = MOASessionDBUtils.getCurrentSession();

    List<AuthenticatedSessionStore> result;

    synchronized (session) {

        session.beginTransaction();/*from   w w  w.  ja va 2 s  . c o m*/
        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);
    }

}

From source file:at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

License:EUPL

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();//from  w  w  w . j av a  2s . c  o  m
        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();

    }
}

From source file:at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

License:EUPL

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();/*from  w ww  .j a va2  s.c om*/
        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);
    }
}

From source file:at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

License:EUPL

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

    AuthenticatedSessionStore dbsession;
    Transaction tx = null;/*from   ww w  . j a  va2 s .  c o  m*/

    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);
    }
}

From source file:at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

License:EUPL

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();/*from  w  w  w  .jav a2s. c o m*/
        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;
    }
}

From source file:at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage.java

License:EUPL

public static OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID,
        String protocolType) {/*from   ww  w.  j  a va  2  s .  c  om*/
    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);
}