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.CS41FileAttachmentHandler.java

License:Open Source License

protected CS41FileAttachmentEntity fetchFileAttachmentEntity(String strFile)
        throws WGAPIException, HibernateException {

    // We cannot query if the entity is transient
    if (((MainEntity) _entity).getCreated() == null) {
        return null;
    }// ww w .  j a v a2  s  .co m

    String hqlQuery = "select cfm from " + _entityDescriptor.getHQLFileMetaEntity() + " cfm where cfm."
            + _entityDescriptor.getHQLFileMetaParentProperty() + "=:entity and cfm.name=:name";
    Query query = _handling.getParent().getSession().createQuery(hqlQuery);
    query.setParameter("entity", _entity);
    query.setParameter("name", strFile);

    Iterator<?> it = query.iterate();
    if (it.hasNext()) {
        return (CS41FileAttachmentEntity) it.next();
    } else {
        return null;
    }

}

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

License:Open Source License

@Override
protected CS5P4FileAttachmentEntity fetchFileAttachmentEntity(String strFile)
        throws WGAPIException, HibernateException {

    // We cannot query if the entity is transient
    if (((MainEntity) _entity).getCreated() == null) {
        return null;
    }/*from w w  w.  ja v  a  2  s  . c  om*/

    String hqlQuery = "select cfm from " + _entityDescriptor.getHQLFileMetaEntity() + " cfm where cfm."
            + _entityDescriptor.getHQLFileMetaParentProperty() + "=:entity and cfm.name=:name";
    Query query = _handling.getParent().getSession().createQuery(hqlQuery);
    query.setLockMode("cfm", LockMode.PESSIMISTIC_READ);
    query.setParameter("entity", _entity);
    query.setParameter("name", strFile);

    Iterator<?> it = query.iterate();
    if (it.hasNext()) {
        return (CS5P4FileAttachmentEntity) it.next();
    } else {
        return null;
    }

}

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

License:Open Source License

public List<WGFileDerivateMetaData> getFileDerivates(String fileName) throws WGAPIException {

    CS5P4FileAttachmentEntity entity = fetchFileAttachmentEntity(fileName);
    if (entity == null || entity.getChecksumSha512() == null) {
        return null;
    }//  ww  w  .  j a va 2  s.co m

    List<WGFileDerivateMetaData> metaData = new ArrayList<WGFileDerivateMetaData>();

    String hql = "select cfd from ContentFileDerivate as cfd where cfd.parentSha512 = :checksum";
    Query q = _handling.getParent().getSession().createQuery(hql);
    q.setParameter("checksum", entity.getChecksumSha512());
    Iterator<?> derivates = q.iterate();
    while (derivates.hasNext()) {
        ContentFileDerivate cfd = (ContentFileDerivate) derivates.next();
        WGDocumentImpl docImpl = _handling.getParent().createDocumentImpl(entity.getParentEntity());
        WGFileDerivateMetaData md = new WGFileDerivateMetaData(_doc.getParent().getDb(),
                WGDocument.buildDocumentKey(docImpl, _doc.getParent().getDb()), cfd.getId(), cfd.getCreator(),
                cfd.getName(), cfd.getCreated(), cfd.getLastmodified(), cfd.getSize(), cfd.getDerivateSha512(),
                cfd.getParentSha512());
        ((CS5P4FileHandling) _handling).loadMdExtensionData(md, cfd);
        metaData.add(md);
    }

    return metaData;

}

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

License:Open Source License

public String storeFileDerivate(WGFileMetaData originalFileMd, String creator, String derivateName,
        InputStream in, Map<String, Object> customMdFields) throws WGAPIException {

    if (originalFileMd.getSha512Checksum() == null) {
        throw new WGIllegalStateException("Cannot create derivate of file '" + originalFileMd.getName()
                + "' because it is not yet stored as distinct file content");
    }//from   ww w .  jav  a2  s . co m

    // Lookup if this derivate of the sha512/creator/name combination already exists
    String hql = "from ContentFileDerivate as cfd where cfd.parentSha512=:checksum and cfd.creator=:creator and cfd.name=:name";
    Query q = getParent().getSession().createQuery(hql);
    q.setParameter("checksum", originalFileMd.getSha512Checksum());
    q.setParameter("creator", creator);
    q.setParameter("name", derivateName);
    if (q.iterate().hasNext()) {
        throw new WGDuplicateKeyException("A file derivate '" + creator + "/" + derivateName
                + "' for that file content does already exist");
    }

    try {
        ContentFileDerivate cfd = new ContentFileDerivate();
        cfd.setParentSha512(originalFileMd.getSha512Checksum());
        cfd.setCreator(creator);
        cfd.setName(derivateName);
        cfd.setCreated(new Date());
        cfd.setLastmodified(new Date());

        if (customMdFields != null) {
            for (Map.Entry<String, Object> entry : customMdFields.entrySet()) {
                cfd.writeExtensionData(getParent(), null, entry.getKey(), entry.getValue());
            }
        }

        // create digest for checksum computation
        MessageDigest digestMd5 = MessageDigest.getInstance("MD5");
        MessageDigest digestSha512 = MessageDigest.getInstance("SHA-512");

        ContentFileContent fileContent = storeFileContents(new CS5P4ContentFileDescriptor(), in,
                getParent().getSession(), digestMd5, digestSha512);
        cfd.setDerivateSha512(fileContent.getChecksumSha512());
        cfd.setSize(fileContent.getSize());

        if (getParent().isSaveIsolationActive()) {
            getParent().getSession().save(cfd);
        }

        getParent().createLogEntry(getParent().getSession(), WGUpdateLog.TYPE_UPDATE,
                WGDocument.TYPENAME_FILEDERIVATE + "/" + cfd.getId(), cfd.getId());
        getParent().commitHibernateTransaction();

        return cfd.getId();
    } catch (NoSuchAlgorithmException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    } catch (IllegalAccessException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    } catch (InstantiationException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    } catch (IOException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    }

}

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

License:Open Source License

protected FileAttachmentEntity getOriginalFileForDerivate(ContentFileDerivate cfd) throws WGAPIException {

    // On CS5P4 we can only fetch the "first best" original file that matches the checksum. There may be multiple
    String hql = "from ContentFileMeta as cfm where cfm.checksumSha512=:checksum";
    Query q = getParent().getSession().createQuery(hql);
    q.setParameter("checksum", cfd.getParentSha512());
    @SuppressWarnings("unchecked")
    Iterator<ContentFileMeta> it = q.iterate();
    if (it.hasNext()) {
        return (ContentFileMeta) it.next();
    } else {//from   w w  w  . j a v  a2  s  . c o  m
        return null;
    }

}

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

License:Open Source License

public InputStream getFileDerivateData(String id) throws WGAPIException {

    ContentFileDerivate cfd = (ContentFileDerivate) getParent().getSession().get(ContentFileDerivate.class, id);
    if (cfd == null) {
        return null;
    }/*from  w w  w .  j  a  v  a  2 s .c o m*/

    String hql = "select cfc from ContentFileContent as cfc where cfc.checksumSha512 = :checksum order by cfc.ordinalnr asc";
    Query q = getParent().getSession().createQuery(hql);
    q.setParameter("checksum", cfd.getDerivateSha512());
    @SuppressWarnings("rawtypes")
    Iterator it = q.iterate();
    try {
        if (!it.hasNext()) {
            return null;
        }
        ContentFileContent cfc = (ContentFileContent) it.next();

        String hqlQuery = "select cfp from ContentFileContentPart as cfp where cfp.fileContents = :contents order by cfp.partnr asc";
        Query query = getParent().getSession().createQuery(hqlQuery);
        query.setParameter("contents", cfc);
        return createOptimizedInputStream(query);
    } finally {
        Hibernate.close(it);
    }

}

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

License:Open Source License

protected ContentFileContent fetchFileContents(String checksumSha512) throws WGAPIException {
    ContentFileContent fileContents = null;
    Query contentsQuery = getParent().getSession().createQuery(
            "from ContentFileContent as cfc where cfc.checksumSha512 = :checksum order by cfc.ordinalnr asc");
    contentsQuery.setParameter("checksum", checksumSha512);
    Iterator<?> it = contentsQuery.iterate();
    try {//from www.j ava 2 s.  c om
        if (it.hasNext()) {
            fileContents = (ContentFileContent) it.next();
        }
        return fileContents;
    } finally {
        Hibernate.close(it);
    }
}

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

License:Open Source License

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

    Session session = getParent().getSession();
    try {/*w w  w .  j  a  v  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
        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)";
        @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.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.filehandling.CS5P5FileAttachmentHandler.java

License:Open Source License

public List<WGFileDerivateMetaData> getFileDerivates(String fileName) throws WGAPIException {

    CS5P4FileAttachmentEntity entity = fetchFileAttachmentEntity(fileName);
    if (entity == null || entity.getChecksumSha512() == null) {
        return null;
    }//from www. j  ava 2 s .  c o m

    WGDocumentImpl docImpl = _handling.getParent().createDocumentImpl(entity.getParentEntity());
    List<WGFileDerivateMetaData> metaData = new ArrayList<WGFileDerivateMetaData>();

    // CS5P5 derivates, directly connected to their original attachment
    String hql = "select cfd from ContentFileDerivate as cfd where cfd.parentMeta = :meta";
    Query q = _handling.getParent().getSession().createQuery(hql);
    q.setParameter("meta", entity);
    Iterator<?> derivates = q.iterate();
    while (derivates.hasNext()) {
        ContentFileDerivate cfd = (ContentFileDerivate) derivates.next();
        WGFileDerivateMetaData md = new WGFileDerivateMetaData(_doc.getParent().getDb(),
                WGDocument.buildDocumentKey(docImpl, _doc.getParent().getDb()), cfd.getId(), cfd.getCreator(),
                cfd.getName(), cfd.getCreated(), cfd.getLastmodified(), cfd.getSize(), cfd.getDerivateSha512(),
                cfd.getParentSha512());
        ((CS5P4FileHandling) _handling).loadMdExtensionData(md, cfd);
        metaData.add(md);
    }

    // Fallback for derivates still stored CS5P4 style, connected only loosely via SHA512 checksum
    hql = "select cfd from ContentFileDerivate as cfd where cfd.parentMeta is null and cfd.parentSha512 = :checksum";
    q = _handling.getParent().getSession().createQuery(hql);
    q.setParameter("checksum", entity.getChecksumSha512());
    derivates = q.iterate();
    while (derivates.hasNext()) {
        ContentFileDerivate cfd = (ContentFileDerivate) derivates.next();
        WGFileDerivateMetaData md = new WGFileDerivateMetaData(_doc.getParent().getDb(),
                WGDocument.buildDocumentKey(docImpl, _doc.getParent().getDb()), cfd.getId(), cfd.getCreator(),
                cfd.getName(), cfd.getCreated(), cfd.getLastmodified(), cfd.getSize(), cfd.getDerivateSha512(),
                cfd.getParentSha512());
        ((CS5P4FileHandling) _handling).loadMdExtensionData(md, cfd);
        metaData.add(md);
    }

    return metaData;

}

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

License:Open Source License

public String storeFileDerivate(WGFileMetaData originalFileMd, String creator, String derivateName,
        InputStream in, Map<String, Object> customMdFields) throws WGAPIException {

    // Fetch the meta so we can bind to it
    WGDocumentImpl docCore = (WGDocumentImpl) originalFileMd.getParentDocument().getCore();
    if (docCore == null) {
        throw new WGBackendException(
                "Cannot store file derivate for a file, as it does not belong to a document");
    }//from ww w.  jav a 2 s . c o m

    String hql = "from ContentFileMeta as cfm where cfm.parentcontent =:content and cfm.name=:name";
    Query q = getParent().getSession().createQuery(hql);
    q.setParameter("content", docCore.getEntity());
    q.setParameter("name", originalFileMd.getName());
    java.util.Iterator<?> results = q.iterate();
    if (!results.hasNext()) {
        throw new WGBackendException(
                "The metadata entity of file '" + originalFileMd.getName() + "' cannot be found");
    }
    ContentFileMeta cfm = (ContentFileMeta) results.next();

    // Lookup if this derivate of the parent/creator/name combination
    // exists, if so cancel
    hql = "from ContentFileDerivate as cfd where cfd.parentMeta=:meta and cfd.creator=:creator and cfd.name=:name";
    q = getParent().getSession().createQuery(hql);
    q.setParameter("meta", cfm);
    q.setParameter("creator", creator);
    q.setParameter("name", derivateName);
    if (q.iterate().hasNext()) {
        throw new WGDuplicateKeyException("A file derivate '" + creator + "/" + derivateName
                + "' for that file content does already exist");
    }

    // Lookup if an old CSP4 style derivate of the sha512/creator/name
    // combination exists, if so delete it
    hql = "from ContentFileDerivate as cfd where cfd.parentMeta is null and cfd.parentSha512=:checksum and cfd.creator=:creator and cfd.name=:name";
    q = getParent().getSession().createQuery(hql);
    q.setParameter("checksum", originalFileMd.getSha512Checksum());
    q.setParameter("creator", creator);
    q.setParameter("name", derivateName);
    @SuppressWarnings("rawtypes")
    java.util.Iterator oldDerivates = q.iterate();
    while (oldDerivates.hasNext()) {
        getParent().getSession().delete(oldDerivates.next());
    }

    // Create the new derivate
    try {
        ContentFileDerivate cfd = new ContentFileDerivate();
        cfd.setParentMeta(cfm);
        cfd.setParentSha512(originalFileMd.getSha512Checksum());
        cfd.setCreator(creator);
        cfd.setName(derivateName);
        cfd.setCreated(new Date());
        cfd.setLastmodified(new Date());

        if (customMdFields != null) {
            for (Map.Entry<String, Object> entry : customMdFields.entrySet()) {
                cfd.writeExtensionData(getParent(), null, entry.getKey(), entry.getValue());
            }
        }

        // create digest for checksum computation
        MessageDigest digestMd5 = MessageDigest.getInstance("MD5");
        MessageDigest digestSha512 = MessageDigest.getInstance("SHA-512");

        ContentFileContent fileContent = storeFileContents(new CS5P4ContentFileDescriptor(), in,
                getParent().getSession(), digestMd5, digestSha512);
        cfd.setDerivateSha512(fileContent.getChecksumSha512());
        cfd.setSize(fileContent.getSize());

        if (getParent().isSaveIsolationActive()) {
            getParent().getSession().save(cfd);
        }

        getParent().createLogEntry(getParent().getSession(), WGUpdateLog.TYPE_UPDATE,
                WGDocument.TYPENAME_FILEDERIVATE + "/" + cfd.getId(), cfd.getId());
        getParent().commitHibernateTransaction();

        return cfd.getId();
    } catch (NoSuchAlgorithmException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    } catch (IllegalAccessException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    } catch (InstantiationException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    } catch (IOException e) {
        throw new WGBackendException("Exception storing file derivate", e);
    }

}