Example usage for org.hibernate Session getNamedQuery

List of usage examples for org.hibernate Session getNamedQuery

Introduction

In this page you can find the example usage for org.hibernate Session getNamedQuery.

Prototype

org.hibernate.Query getNamedQuery(String queryName);

Source Link

Document

Create a Query instance for the named query.

Usage

From source file:com.duroty.task.POP3ServiceTask.java

License:Open Source License

/**
 * DOCUMENT ME!//from  w w  w  . j a va 2s.  co  m
 */
private void flush() {
    setInit(true);

    SessionFactory hfactory = null;
    Session hsession = null;
    javax.mail.Session msession = null;

    try {
        hfactory = (SessionFactory) ctx.lookup(hibernateSessionFactory);
        hsession = hfactory.openSession();
        msession = (javax.mail.Session) ctx.lookup(durotyMailFactory);

        String pop3Host = msession.getProperty("mail.pop3.host");

        int port = 0;

        try {
            port = Integer.parseInt(msession.getProperty("mail.pop3.port"));
        } catch (Exception ex) {
            port = 0;
        }

        Query query = hsession.getNamedQuery("users-mail");
        query.setBoolean("active", true);
        query.setString("role", "mail");

        ScrollableResults scroll = query.scroll();

        while (scroll.next()) {
            POP3Client client = new POP3Client();

            try {
                if (port > 0) {
                    client.connect(pop3Host, port);
                } else {
                    client.connect(pop3Host);
                }

                client.setState(POP3Client.AUTHORIZATION_STATE);

                //client.setDefaultTimeout()
                Users user = (Users) scroll.get(0);

                String repositoryName = user.getUseUsername();

                if (client.login(repositoryName, user.getUsePassword())) {
                    POP3MessageInfo[] info = client.listUniqueIdentifiers();

                    if ((info != null) && (info.length > 0)) {
                        for (int i = 0; i < info.length; i++) {
                            if (pool.size() >= poolSize) {
                                break;
                            }

                            Reader reader = client.retrieveMessage(info[i].number);

                            boolean existMessage = existMessageName(hfactory.openSession(), user,
                                    info[i].identifier);

                            String key = info[i].identifier + "--" + repositoryName;

                            if (existMessage) {
                                client.deleteMessage(info[i].number);
                            } else {
                                if (!poolContains(key)) {
                                    addPool(key);

                                    MimeMessage mime = buildMimeMessage(info[i].identifier, reader, user);

                                    if (!isSpam(user, mime)) {
                                        client.deleteMessage(info[i].number);

                                        Mailet mailet = new Mailet(this, info[i].identifier, repositoryName,
                                                mime);

                                        Thread thread = new Thread(mailet, key);
                                        thread.start();
                                    } else {
                                        client.deleteMessage(info[i].number);
                                    }
                                }
                            }

                            Thread.sleep(100);
                        }
                    }
                } else {
                }
            } catch (Exception e) {
            } finally {
                System.gc();

                try {
                    client.logout();
                    client.disconnect();
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (OutOfMemoryError e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } catch (Throwable e) {
        System.gc();
        pool.clear();
        DLog.log(DLog.ERROR, this.getClass(), e.getMessage());
    } finally {
        System.gc();

        GeneralOperations.closeHibernateSession(hsession);

        setInit(false);
    }
}

From source file:com.enonic.cms.store.dao.AbstractBaseEntityDao.java

License:Open Source License

public int deleteByNamedQuery(final String queryName, final String[] paramNames, final Object[][] paramValues) {
    return ((Number) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.getNamedQuery(queryName);
            if (paramNames != null) {
                for (int i = 0; i < paramNames.length; i++) {
                    query.setParameterList(paramNames[i], paramValues[i]);
                }/*w w  w.j a v  a  2s. c  o m*/
            }

            return query.executeUpdate();
        }
    })).intValue();
}

From source file:com.enonic.cms.store.dao.AbstractBaseEntityDao.java

License:Open Source License

private int executeByNamedQuery(final String queryName, final String[] paramNames, final Object[] paramValues) {
    return ((Number) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.getNamedQuery(queryName);
            if (paramNames != null) {
                for (int i = 0; i < paramNames.length; i++) {
                    query.setParameter(paramNames[i], paramValues[i]);
                }// w  w  w  .j av  a 2  s .c  o m
            }

            return query.executeUpdate();
        }
    })).intValue();
}

From source file:com.enonic.cms.store.dao.UserEntityDao.java

License:Open Source License

public List<UserEntity> findByUserStoreKey(final UserStoreKey userStoreKey, final Integer index,
        final Integer count, final boolean includeDeleted) {

    return executeListResult(UserEntity.class, new HibernateCallback() {

        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.getNamedQuery("UserEntity.findByUserStoreKey");
            if (index != null) {
                query.setFirstResult(index);
            }//from   w  w w.jav  a  2 s  .com
            query.setInteger("userStoreKey", userStoreKey.toInt());
            query.setInteger("deleted", includeDeleted ? 1 : 0);

            List list = query.list();
            if (count == null) {
                return list;
            } else {
                return list.subList(0, Math.min(count, list.size()));
            }
        }
    });
}

From source file:com.enonic.cms.store.resource.FileResourceServiceImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<VirtualFileEntity> findChildren(Session session, String key) {
    Query query = session.getNamedQuery("VirtualFileEntity.findChildren");
    query.setParameter("parentKey", key);
    return query.list();
}

From source file:com.evolveum.midpoint.repo.sql.helpers.CertificationCaseHelper.java

License:Apache License

public void deleteCertificationCampaignCases(Session session, String oid) {
    // TODO couldn't this cascading be done by hibernate itself?
    Query deleteDecisions = session.getNamedQuery("delete.campaignCasesDecisions");
    deleteDecisions.setParameter("oid", oid);
    deleteDecisions.executeUpdate();/* www.jav a 2  s  .co m*/

    Query deleteReferences = session.getNamedQuery("delete.campaignCasesReferences");
    deleteReferences.setParameter("oid", oid);
    deleteReferences.executeUpdate();

    Query deleteCases = session.getNamedQuery("delete.campaignCases");
    deleteCases.setParameter("oid", oid);
    deleteCases.executeUpdate();
}

From source file:com.evolveum.midpoint.repo.sql.helpers.CertificationCaseHelper.java

License:Apache License

protected List<Long> addOrDeleteCases(Session session, String campaignOid,
        Collection<? extends ItemDelta> modifications) throws SchemaException, DtoTranslationException {
    final ItemPath casePath = new ItemPath(AccessCertificationCampaignType.F_CASE);
    boolean replacePresent = false;
    List<Long> affectedIds = new ArrayList<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (!casePath.isSubPathOrEquivalent(deltaPath)) {
            throw new IllegalStateException("Wrong campaign delta sneaked into updateCampaignCases: class="
                    + delta.getClass() + ", path=" + deltaPath);
        }//from   w w w . ja  va2s. co m

        if (deltaPath.size() == 1) {
            if (delta.getValuesToDelete() != null) {
                // todo do 'bulk' delete like delete from ... where oid=? and id in (...)
                for (PrismContainerValue value : (Collection<PrismContainerValue>) delta.getValuesToDelete()) {
                    Long id = value.getId();
                    if (id == null) {
                        throw new SchemaException("Couldn't delete certification case with null id");
                    }
                    affectedIds.add(id);
                    // TODO couldn't this cascading be done by hibernate itself?
                    Integer integerCaseId = RUtil.toInteger(id);
                    Query deleteCaseDecisions = session.getNamedQuery("delete.campaignCaseDecisions");
                    deleteCaseDecisions.setString("oid", campaignOid);
                    deleteCaseDecisions.setInteger("id", integerCaseId);
                    deleteCaseDecisions.executeUpdate();
                    Query deleteCaseReferences = session.createSQLQuery("delete from "
                            + RCertCaseReference.TABLE + " where owner_owner_oid=:oid and owner_id=:id");
                    deleteCaseReferences.setString("oid", campaignOid);
                    deleteCaseReferences.setInteger("id", integerCaseId);
                    deleteCaseReferences.executeUpdate();
                    Query deleteCase = session.getNamedQuery("delete.campaignCase");
                    deleteCase.setString("oid", campaignOid);
                    deleteCase.setInteger("id", integerCaseId);
                    deleteCase.executeUpdate();
                }
            }
            // TODO generated IDs might conflict with client-provided ones
            // also, client-provided IDs might conflict with those that are already in the database
            // So it's safest not to provide any IDs by the client
            if (delta.getValuesToAdd() != null) {
                int currentId = generalHelper.findLastIdInRepo(session, campaignOid, "get.campaignCaseLastId")
                        + 1;
                addCertificationCampaignCases(session, campaignOid, delta.getValuesToAdd(), currentId,
                        affectedIds);
            }
            if (delta.getValuesToReplace() != null) {
                deleteCertificationCampaignCases(session, campaignOid);
                addCertificationCampaignCases(session, campaignOid, delta.getValuesToReplace(), 1, affectedIds);
                replacePresent = true;
            }

        }
    }
    return replacePresent ? null : affectedIds;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.CertificationCaseHelper.java

License:Apache License

private void updateCasesContent(Session session, String campaignOid,
        Collection<? extends ItemDelta> modifications, List<Long> casesAddedOrDeleted,
        RepoModifyOptions modifyOptions)
        throws SchemaException, ObjectNotFoundException, DtoTranslationException {
    Set<Long> casesModified = new HashSet<>();
    for (ItemDelta delta : modifications) {
        ItemPath deltaPath = delta.getPath();
        if (deltaPath.size() > 1) {
            LOGGER.trace("Updating campaign " + campaignOid + " with delta " + delta);

            // should start with "case[id]"
            long id = checkPathSanity(deltaPath, casesAddedOrDeleted);

            Query query = session.getNamedQuery("get.campaignCase");
            query.setString("ownerOid", campaignOid);
            query.setInteger("id", (int) id);

            byte[] fullObject = (byte[]) query.uniqueResult();
            if (fullObject == null) {
                throw new ObjectNotFoundException("Couldn't update cert campaign " + campaignOid
                        + " + by delta with path " + deltaPath + " - specified case does not exist");
            }/*w  w  w  .  j a  v a2  s.c o m*/
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext,
                    false);

            delta = delta.clone(); // to avoid changing original modifications
            delta.setParentPath(delta.getParentPath().tail(2)); // remove "case[id]" from the delta path
            delta.applyTo(aCase.asPrismContainerValue());

            // we need to generate IDs but we (currently) do not use that for setting "isTransient" flag
            PrismIdentifierGenerator generator = new PrismIdentifierGenerator();
            generator.generate(aCase, PrismIdentifierGenerator.Operation.MODIFY);

            RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase, prismContext);
            session.merge(rCase);

            LOGGER.trace("Access certification case {} merged", rCase);
            casesModified.add(aCase.getId());
        }
    }

    // refresh campaign cases, if requested
    if (RepoModifyOptions.isExecuteIfNoChanges(modifyOptions)) {
        Query query = session.getNamedQuery("get.campaignCases");
        query.setString("ownerOid", campaignOid);
        List<Object> cases = query.list();
        for (Object o : cases) {
            if (!(o instanceof byte[])) {
                throw new IllegalStateException("Certification case: expected byte[], got " + o.getClass());
            }
            byte[] fullObject = (byte[]) o;
            AccessCertificationCaseType aCase = RAccessCertificationCase.createJaxb(fullObject, prismContext,
                    false);
            Long id = aCase.getId();
            if (id != null && casesAddedOrDeleted != null && !casesAddedOrDeleted.contains(id)
                    && !casesModified.contains(id)) {
                RAccessCertificationCase rCase = RAccessCertificationCase.toRepo(campaignOid, aCase,
                        prismContext);
                session.merge(rCase);
                LOGGER.trace("Access certification case {} refreshed", rCase);
            }
        }
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.GeneralHelper.java

License:Apache License

public int findLastIdInRepo(Session session, String tableOid, String queryName) {
    Query query = session.getNamedQuery(queryName);
    query.setString("oid", tableOid);
    Integer lastId = (Integer) query.uniqueResult();
    if (lastId == null) {
        lastId = 0;/*from ww  w  . j a  va2s.  c om*/
    }
    return lastId;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.LookupTableHelper.java

License:Apache License

/**
 * This method removes all lookup table rows for object defined by oid
 * @param session// w w w.j  av  a  2  s .c o  m
 * @param oid
 */
public void deleteLookupTableRows(Session session, String oid) {
    Query query = session.getNamedQuery("delete.lookupTableData");
    query.setParameter("oid", oid);

    query.executeUpdate();
}