Example usage for org.hibernate Query setParameter

List of usage examples for org.hibernate Query setParameter

Introduction

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

Prototype

@SuppressWarnings("unchecked")
Query<R> setParameter(int position, Object val);

Source Link

Document

Bind a positional query parameter using its inferred Type.

Usage

From source file:applicationController.Handlers.SendChatHandler.java

@Override
public void handleIt(HashMap inMap, JSONOutputStream outToClient) {
    Session session = HibernateUtilSingleton.getSessionFactory().getCurrentSession();
    Transaction transaction = session.beginTransaction();
    Query query = session.createQuery("FROM Meeting WHERE meeting_id = :meeting ");
    query.setParameter("meeting", this.commBean.convertLong(((HashMap) inMap.get("data")).get("meeting")));
    Meeting meeting = (Meeting) query.uniqueResult();
    Message msg = new Message();
    msg.setMeeting(meeting);//  w  w  w  . j  a va 2s  . co  m
    msg.setUsername(((HashMap) inMap.get("data")).get("username").toString());
    msg.setMsg(((HashMap) inMap.get("data")).get("msg").toString());
    session.save(msg);
    session.getTransaction().commit();

    this.commBean.setCommand("SENDCHAT");
    HashMap data = new HashMap();
    data.put("msg", ((HashMap) inMap.get("data")).get("msg").toString());
    data.put("username", ((HashMap) inMap.get("data")).get("username").toString());
    this.commBean.setData(data);

    try {
        outToClient.writeObject(this.commBean);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.hibernate.work.AbstractWork.java

License:Apache License

protected List<DatastoreModel> getDatastoreModelsForEntity(Session session, Object entity) {
    Query query = session.getNamedQuery("datastoreModel.getModelForEntity");
    query.setParameter("entityClassName", entity.getClass().getSimpleName());
    query.setParameter("entityID", String.valueOf(EntityUtil.getID(entity)));
    return query.list();
}

From source file:at.gv.egovernment.moa.id.moduls.SSOManager.java

License:EUPL

public String existsOldSSOSession(String ssoId) {

    Logger.trace("Check that the SSOID has already been used");
    Session session = MOASessionDBUtils.getCurrentSession();

    List<OldSSOSessionIDStore> result;

    synchronized (session) {

        session.beginTransaction();//from w w  w .j a v a2  s  . co m
        Query query = session.getNamedQuery("getSSOSessionWithOldSessionID");
        query.setParameter("sessionid", ssoId);
        result = query.list();

        // send transaction

    }

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

    // Assertion requires an unique artifact
    if (result.size() == 0) {
        session.getTransaction().commit();
        return null;
    }

    OldSSOSessionIDStore oldSSOSession = result.get(0);

    AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession();

    if (correspondingMoaSession == null) {
        Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found.");
        return null;
    }

    String moasessionid = correspondingMoaSession.getSessionid();

    session.getTransaction().commit();

    return moasessionid;

}

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);//w  ww.  j a v a2 s . com
                    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

@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  ww w.ja va 2  s  . c  o  m*/

    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  www. ja  va2 s .c om
        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  www  .  j  a  v  a2 s  .  co  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 w  w  . j av a 2 s. co m*/
        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  w  ww. j ava 2  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();// ww  w . j av a2 s. 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;
    }
}