Example usage for org.hibernate Query iterate

List of usage examples for org.hibernate Query iterate

Introduction

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

Prototype

Iterator<R> iterate();

Source Link

Document

Return the query results as an Iterator.

Usage

From source file:de.innovationgate.webgate.api.jdbc.filehandling.CS5P5FileHandling.java

License:Open Source License

@Override
public long dailyFileMaintenance(Logger log) throws WGAPIException {

    Session session = getParent().getSession();
    try {//  w  w  w  .  j av a 2  s  . c  o  m

        session.setDefaultReadOnly(false);
        long freedMemory = 0;
        int deletedDuplicates = 0;

        // Remove duplicate file contents
        String hql = "select cfc.checksumSha512 as checksum from ContentFileContent as cfc group by cfc.checksumSha512 having count(*) > 1";
        @SuppressWarnings("unchecked")
        Iterator<String> duplicateChecksums = session.createQuery(hql).iterate();
        while (duplicateChecksums.hasNext()) {
            String duplicaceChecksum = duplicateChecksums.next();
            hql = "select cfc.id as id from ContentFileContent as cfc where cfc.checksumSha512 = :checksum order by cfc.ordinalnr asc";
            Query q = session.createQuery(hql);
            q.setParameter("checksum", duplicaceChecksum);
            @SuppressWarnings("unchecked")
            Iterator<String> duplicateIds = q.iterate();
            if (!duplicateIds.hasNext()) { // Just in case
                continue;
            }

            // Skip the first one. That is the one that will be kept and
            // constantly retrieved
            duplicateIds.next();

            // Delete the other duplicates
            while (duplicateIds.hasNext()) {
                String id = duplicateIds.next();
                ContentFileContent cfc = (ContentFileContent) session.get(ContentFileContent.class, id);
                if (cfc != null) {
                    deletedDuplicates++;
                    freedMemory += cfc.getSize();
                    session.setReadOnly(cfc, false);

                    // Delete data entities via HQL to prevent loading them
                    hql = "delete ContentFileContentPart cfp where cfp.fileContents=:cfc";
                    Query deleteQ = session.createQuery(hql);
                    deleteQ.setParameter("cfc", cfc);
                    deleteQ.executeUpdate();

                    session.delete(cfc);
                    getParent().commitHibernateTransaction();
                }
            }
            Hibernate.close(duplicateIds);
        }
        Hibernate.close(duplicateChecksums);

        // Remove unused file contents, not used on attachments, derivates
        // or binary extension data
        long deletedUnusedFiles = 0;
        hql = "select cfc.id as id from ContentFileContent as cfc where cfc.checksumSha512 not in (select distinct cfm.checksumSha512 from ContentFileMeta as cfm where cfm.checksumSha512 is not null) and cfc.checksumSha512 not in (select distinct cfd.derivateSha512 from ContentFileDerivate as cfd) and cfc.checksumSha512 not in (select distinct ext.binarySha512 from ExtensionData as ext where ext.type=7)";
        @SuppressWarnings("unchecked")
        Iterator<String> obsoleteIds = session.createQuery(hql).iterate();
        while (obsoleteIds.hasNext()) {
            String id = obsoleteIds.next();
            ContentFileContent cfc = (ContentFileContent) session.get(ContentFileContent.class, id);
            if (cfc != null) {
                deletedUnusedFiles++;
                freedMemory += cfc.getSize();
                session.setReadOnly(cfc, false);

                // Delete data entities via HQL to prevent loading them
                hql = "delete ContentFileContentPart cfp where cfp.fileContents=:cfc";
                Query deleteQ = session.createQuery(hql);
                deleteQ.setParameter("cfc", cfc);
                deleteQ.executeUpdate();

                session.delete(cfc);
                // log.info("Deleted file contents " +
                // cfc.getChecksumSha512() + " ordinal nr " +
                // cfc.getOrdinalnr());
                getParent().commitHibernateTransaction();
            }
        }
        Hibernate.close(obsoleteIds);

        // Remove unused derivates of old CS5P4 style. Corresponding
        // derivate data is deleted in the next run.
        hql = "select cfd.id as id from ContentFileDerivate as cfd where cfd.parentMeta is null and cfd.parentSha512 not in (select distinct cfc.checksumSha512 from ContentFileContent as cfc)";
        @SuppressWarnings("unchecked")
        Iterator<String> obsoleteDerivateIds = session.createQuery(hql).iterate();
        while (obsoleteDerivateIds.hasNext()) {
            String id = obsoleteDerivateIds.next();
            ContentFileDerivate cfd = (ContentFileDerivate) session.get(ContentFileDerivate.class, id);
            if (cfd != null) {
                session.setReadOnly(cfd, false);
                session.delete(cfd);
                getParent().commitHibernateTransaction();
            }
        }
        Hibernate.close(obsoleteDerivateIds);

        String freedMemoryText;
        if (deletedDuplicates > 0 || deletedUnusedFiles > 0) {
            if (freedMemory > 1024 * 1024) {
                freedMemoryText = WGUtils.DECIMALFORMAT_STANDARD.format(freedMemory / 1024 / 1024)
                        + " MB of file storage";
            } else {
                freedMemoryText = WGUtils.DECIMALFORMAT_STANDARD.format(freedMemory) + " Bytes of file storage";
            }
            log.info("Maintenance on content store of app/plugin '" + getParent().getDb().getDbReference()
                    + "': Deleted " + WGUtils.DECIMALFORMAT_STANDARD.format(deletedDuplicates)
                    + " duplicates and " + WGUtils.DECIMALFORMAT_STANDARD.format(deletedUnusedFiles)
                    + " unused file contents freeing " + freedMemoryText);
        }
        return freedMemory;

    } catch (Throwable e) {
        try {
            session.getTransaction().rollback();
        } catch (Exception e2) {
        }
        throw new WGBackendException("Exception running daily maintenance", e);
    } finally {
        session.setDefaultReadOnly(true);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.HibernateResultSet.java

License:Open Source License

private int fetchResultCount() throws WGAPIException {
    String query = getQuery().getQueryString();

    String querySearchString = WGUtils.clearStrings(query, '\'', 'X').toLowerCase();

    int startIdx = -1;
    Matcher fromAtStartMatcher = PATTERN_FROM_AT_START.matcher(querySearchString);
    if (fromAtStartMatcher.find()) {
        startIdx = 0;/*  w ww . j a v  a2 s .  c o  m*/
    } else {
        Matcher fromMatcher = PATTERN_FROM_INSIDE.matcher(querySearchString);
        if (fromMatcher.find()) {
            startIdx = fromMatcher.start();
        }
    }

    // Cannot create count query if we have no regular select/from query
    if (startIdx == -1) {
        return 0;
    }

    int orderIdx = querySearchString.indexOf("order by");
    int groupIdx = querySearchString.toLowerCase().indexOf("group by");

    int endIdx = query.length();
    if (orderIdx != -1) {
        endIdx = orderIdx;
    }
    if (groupIdx != -1 && groupIdx < endIdx) {
        endIdx = groupIdx;
    }

    String countQueryString = "select count(*) " + query.substring(startIdx, endIdx);
    Query countQuery = getParent().getSession().createQuery(countQueryString);
    injectQueryParams(countQuery, _parameters);
    int countResults = ((Number) countQuery.iterate().next()).intValue();

    // Look if we are beyond max results, if so return it (#00001818)
    if (_options.containsKey(WGDatabase.QUERYOPTION_MAXRESULTS)) {
        Integer maxResults = (Integer) _options.get(WGDatabase.QUERYOPTION_MAXRESULTS);
        if (maxResults != null && maxResults.intValue() < countResults) {
            return maxResults.intValue();
        }

    }

    return countResults;

}

From source file:de.innovationgate.webgate.api.jdbc.PortletItemStorageImpl.java

License:Open Source License

@Override
public void pushData(WGPortletItemStorage targetStorage) throws WGAPIException {

    Query query = _parent.getSession().createQuery("select portlet from UserProfilePortlet as portlet");
    Iterator<UserProfilePortlet> it = query.iterate();
    while (it.hasNext()) {
        UserProfilePortlet p = it.next();
        targetStorage.receiveData(p);/*from w w  w  .  ja  v  a2s  .c  o m*/
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

/**
 * @throws WGAPIException //from   ww w .ja  v  a 2 s.c o m
 * @see de.innovationgate.webgate.api.WGDatabaseCore#getAllContent(WGStructEntry)
 */
public List getAllContent(WGStructEntry structEntry, boolean includeArchived) throws WGAPIException {

    try {
        StructEntry hentry = (StructEntry) ((WGDocumentImpl) structEntry.getCore()).getEntity();

        StringBuffer queryText = new StringBuffer();
        queryText.append("select content from Content as content where content.structentry = :entry");
        if (!includeArchived) {
            queryText.append(" and not content.status = 'a'");
        }
        Query query = getSession().createQuery(queryText.toString());
        query.setParameter("entry", hentry);
        Iterator contentIt = query.iterate();

        List contentList = new ArrayList();
        Content content = null;
        while (contentIt.hasNext()) {
            content = (Content) contentIt.next();
            if (includeArchived || content.getStatus() != WGContent.STATUS_ARCHIVE) {
                contentList.add(createDocumentImpl(content));
            }
        }
        return contentList;
    } catch (HibernateException e) {
        throw new WGBackendException("Exception retrieving struct entry content", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

/**
 * @throws WGAPIException //from   w ww.ja  v a  2  s . co  m
 * @see de.innovationgate.webgate.api.WGDatabaseCore#getContentByKey(WGContentKey)
 */
public WGDocumentCore getContentByKey(WGContentKey key) throws WGAPIException {

    try {

        Query contentQuery;
        if (key.getVersion() != 0) {
            contentQuery = getSession().createQuery(
                    "from Content as content where content.structentry.key =:structkey and content.language.name =:lang and content.version =:version");
            contentQuery.setInteger("version", key.getVersion());
        } else {
            contentQuery = getSession().createQuery(
                    "from Content as content where content.structentry.key =:structkey and content.language.name =:lang and content.status ='p'");
        }
        contentQuery.setString("structkey", String.valueOf(key.getStructKey()));
        contentQuery.setString("lang", key.getLanguage());

        Iterator it = contentQuery.iterate();

        if (it.hasNext()) {
            Content content = (Content) it.next();
            return createDocumentImpl(content);
        } else {
            return null;
        }
    } catch (HibernateException e) {
        throw new WGBackendException("Error loading content by key", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

/**
 * @throws WGAPIException /*w w w  .ja  va  2 s.  c o m*/
 * @see de.innovationgate.webgate.api.WGDatabaseCore#getContentByName(String,
 *      String)
 */
public WGDocumentCore getContentByName(String strName, String strLanguage) throws WGAPIException {

    strName = strName.toLowerCase();
    strLanguage = (strLanguage != null ? strLanguage.toLowerCase() : null);

    String queryStr = "from Content as content where content.status='p' and content.uniquename=:name";
    if (strLanguage != null) {
        queryStr += " and content.language.name=:lang";
    }

    Iterator contents;
    try {
        Query query = getSession().createQuery(queryStr);
        query.setString("name", strName);
        if (strLanguage != null) {
            query.setString("lang", strLanguage);
        }

        contents = query.iterate();
    } catch (HibernateException e) {
        throw new WGBackendException("Error searching content by name", e);
    }

    Content content;
    if (contents.hasNext()) {
        content = (Content) contents.next();
        return createDocumentImpl(content);
    }

    return null;

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public List<WGUpdateLog> getUpdateLogs(Comparable fromRevision) throws WGAPIException {

    try {/*from   w  w w .jav  a  2s . c  o  m*/
        Iterator logEntries;
        if (_ddlVersion >= WGDatabase.CSVERSION_WGA5) {
            Query logEntriesQ = getSession().createQuery(
                    "from de.innovationgate.webgate.api.jdbc.LogEntry as logentry where id > :start order by id asc");
            logEntriesQ.setLong("start", ((Long) fromRevision).longValue());
            logEntries = logEntriesQ.iterate();

        } else {
            Date cutoff = (Date) fromRevision;
            Query logEntriesQ = getSession().createQuery(
                    "from de.innovationgate.webgate.api.jdbc.LogEntry as logentry where logtime >= :start order by logtime asc");
            logEntriesQ.setTimestamp("start", new java.sql.Timestamp(cutoff.getTime()));
            logEntries = logEntriesQ.iterate();
        }

        List wgLogs = new ArrayList();
        LinkedMap wgLogsByTarget = new LinkedMap();
        Map conflictTargets = new HashMap();

        LogEntry entry;

        // First pass: Create update logs
        while (logEntries.hasNext()) {
            entry = (LogEntry) logEntries.next();
            WGUpdateLog newLog = null;
            WGUpdateLog oldLog = null;
            Date currentTime = null;
            if (entry.getTarget() != null && !entry.getTarget().equals("#UNKNOWN#")) {
                newLog = readUpdateLog(entry);
                wgLogs.add(newLog);

                List logsList = (List) wgLogsByTarget.get(entry.getTarget());
                if (logsList == null) {
                    logsList = new ArrayList();
                    wgLogsByTarget.put(entry.getTarget(), logsList);
                }
                logsList.add(newLog);
            }
        }

        // Second pass for CS version < 5 to workaround some weaknesses of the CS3/4 history log
        if (_ddlVersion < WGDatabase.CSVERSION_WGA5) {

            // Determine conflicting log entries, where update and delete is done on the same time and the same document
            Iterator wgLogsByTargetIt = wgLogsByTarget.values().iterator();
            while (wgLogsByTargetIt.hasNext()) {
                List logs = (List) wgLogsByTargetIt.next();
                WGUtils.sortByProperty(logs, "date");
                Iterator logsIt = logs.iterator();
                Date lastTime = null;
                List<WGUpdateLog> logsAtSameTime = new ArrayList();
                while (logsIt.hasNext()) {
                    WGUpdateLog log = (WGUpdateLog) logsIt.next();
                    if (log.getDate().equals(lastTime)) {
                        logsAtSameTime.add(log);
                    } else {
                        resolveLogConflicts(wgLogs, logsAtSameTime);
                        logsAtSameTime.clear();
                    }
                    lastTime = log.getDate();
                }
            }

            // Order logentries that have the same time in an order that assures dependency documents are created before their dependent documents
            Collections.sort(wgLogs, new DocumentDependencyComparator());

        }

        return wgLogs;
    } catch (HibernateException e) {
        throw new WGBackendException("Unable to retrieve updated documents", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public WGDocumentCore getStructEntryByName(String strName) throws WGAPIException {

    Query query = getSession().createQuery(HQLQUERY_GET_STRUCT_BY_NAME);
    query.setParameter("name", strName);
    Iterator results = query.iterate();
    if (results.hasNext()) {
        StructEntry entry = (StructEntry) results.next();
        return createDocumentImpl(entry);
    } else {//w  w  w .  j a  v  a2s.co  m
        return null;
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public Iterator<String> getAllUserProfileNames() throws WGAPIException {

    try {/*  w w  w.  jav a2 s .  c o  m*/
        String fullQuery = "select profile.name from UserProfile profile order by profile.name asc";

        Query hqlQuery = getSession().createQuery(fullQuery);
        return hqlQuery.iterate();

    } catch (QueryException e) {
        throw new WGQueryException("Querying all user profile names", e.getMessage(), e);
    } catch (HibernateException e) {
        throw new WGBackendException("Error executing profile query", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

private int newContentVersion(WGStructEntry structEntry, WGLanguage lang) throws WGAPIException {

    String hql = "select max(content.version) from Content as content where content.structentry.key=:key and content.language.name=:lang";
    Query q = getSession().createQuery(hql);
    q.setParameter("key", structEntry.getStructKey());
    q.setParameter("lang", lang.getName());
    Iterator it = q.iterate();
    Number maxVersion = null;//  www  .  j  a v a2s. c  o  m
    if (it.hasNext()) {
        maxVersion = (Number) it.next();
    }

    if (maxVersion == null) {
        maxVersion = 0;
    }

    return maxVersion.intValue() + 1;

}