Search in sources :

Example 26 with TypedQuery

use of javax.persistence.TypedQuery in project dataverse by IQSS.

the class DatasetVersionServiceBean method findByFriendlyVersionNumber.

public DatasetVersion findByFriendlyVersionNumber(Long datasetId, String friendlyVersionNumber) {
    // FIXME: this logic doesn't work
    Long majorVersionNumber = null;
    Long minorVersionNumber = null;
    String[] versions = friendlyVersionNumber.split("\\.");
    try {
        if (versions.length == 1) {
            majorVersionNumber = Long.parseLong(versions[0]);
        } else if (versions.length == 2) {
            majorVersionNumber = Long.parseLong(versions[0]);
            minorVersionNumber = Long.parseLong(versions[1]);
        } else {
            return null;
        }
    } catch (NumberFormatException n) {
        return null;
    }
    if (minorVersionNumber != null) {
        String queryStr = "SELECT v from DatasetVersion v where v.dataset.id = :datasetId  and v.versionNumber= :majorVersionNumber and v.minorVersionNumber= :minorVersionNumber";
        DatasetVersion foundDatasetVersion = null;
        try {
            Query query = em.createQuery(queryStr);
            query.setParameter("datasetId", datasetId);
            query.setParameter("majorVersionNumber", majorVersionNumber);
            query.setParameter("minorVersionNumber", minorVersionNumber);
            foundDatasetVersion = (DatasetVersion) query.getSingleResult();
        } catch (javax.persistence.NoResultException e) {
            logger.warning("no ds version found: " + datasetId + " " + friendlyVersionNumber);
        // DO nothing, just return null.
        }
        return foundDatasetVersion;
    }
    if (majorVersionNumber == null && minorVersionNumber == null) {
        return null;
    }
    if (majorVersionNumber != null && minorVersionNumber == null) {
        try {
            TypedQuery<DatasetVersion> typedQuery = em.createQuery("SELECT v from DatasetVersion v where v.dataset.id = :datasetId  and v.versionNumber= :majorVersionNumber", DatasetVersion.class);
            typedQuery.setParameter("datasetId", datasetId);
            typedQuery.setParameter("majorVersionNumber", majorVersionNumber);
            DatasetVersion retVal = null;
            List<DatasetVersion> versionsList = typedQuery.getResultList();
            for (DatasetVersion dsvTest : versionsList) {
                if (retVal == null) {
                    retVal = dsvTest;
                } else {
                    if (retVal.getMinorVersionNumber().intValue() < dsvTest.getMinorVersionNumber().intValue()) {
                        retVal = dsvTest;
                    }
                }
            }
            return retVal;
        } catch (javax.persistence.NoResultException e) {
            logger.warning("no ds version found: " + datasetId + " " + friendlyVersionNumber);
        // DO nothing, just return null.
        }
    }
    return null;
}
Also used : TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query)

Example 27 with TypedQuery

use of javax.persistence.TypedQuery in project deltaspike by apache.

the class QueryCriteria method createQuery.

@Override
public TypedQuery<R> createQuery() {
    try {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<R> query = createCriteriaQuery(builder);
        From<C, C> root = query.from(entityClass);
        if (selections.size() == 1) {
            Selection<?>[] selections = prepareSelections(query, builder, root);
            query.select((Selection<? extends R>) selections[0]);
        }
        if (selections.size() > 1) {
            query.multiselect(prepareSelections(query, builder, root));
        }
        List<Predicate> predicates = predicates(builder, root);
        query.distinct(distinct);
        if (!predicates.isEmpty()) {
            query.where(predicates.toArray(new Predicate[predicates.size()]));
        }
        applyProcessors(query, builder, root);
        return (TypedQuery<R>) entityManager.createQuery(query);
    } catch (RuntimeException e) {
        log.log(Level.SEVERE, "Exception while creating JPA query", e);
        throw e;
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) TypedQuery(javax.persistence.TypedQuery) Selection(javax.persistence.criteria.Selection) QuerySelection(org.apache.deltaspike.data.api.criteria.QuerySelection) Predicate(javax.persistence.criteria.Predicate)

Example 28 with TypedQuery

use of javax.persistence.TypedQuery in project mycore by MyCoRe-Org.

the class MCRIView2Commands method fixDeadEntries.

@MCRCommand(syntax = "fix dead tile jobs", help = "Deletes entries for files which dont exist anymore!")
public static void fixDeadEntries() {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
    List<MCRTileJob> tiles = allTileJobQuery.getResultList();
    tiles.stream().filter(tj -> {
        MCRPath path = MCRPath.getPath(tj.getDerivate(), tj.getPath());
        return !Files.exists(path);
    }).peek(tj -> LOGGER.info("Delete TileJob {}:{}", tj.getDerivate(), tj.getPath())).forEach(em::remove);
}
Also used : MCRIView2Tools(org.mycore.iview2.services.MCRIView2Tools) Enumeration(java.util.Enumeration) TypedQuery(javax.persistence.TypedQuery) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MCRRecursiveDeleter(org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter) DirectoryStream(java.nio.file.DirectoryStream) JDOMException(org.jdom2.JDOMException) MCRImage(org.mycore.imagetiler.MCRImage) MCRTileJob(org.mycore.iview2.services.MCRTileJob) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRTiledPictureProps(org.mycore.imagetiler.MCRTiledPictureProps) ZipFile(java.util.zip.ZipFile) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRTilingQueue(org.mycore.iview2.services.MCRTilingQueue) ImageReader(javax.imageio.ImageReader) BufferedImage(java.awt.image.BufferedImage) Files(java.nio.file.Files) MCRAbstractCommands(org.mycore.frontend.cli.MCRAbstractCommands) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRImageTiler(org.mycore.iview2.services.MCRImageTiler) IOException(java.io.IOException) EntityManager(javax.persistence.EntityManager) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) CRC32(java.util.zip.CRC32) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) EntityManager(javax.persistence.EntityManager) FileSystem(java.nio.file.FileSystem) MCRTileJob(org.mycore.iview2.services.MCRTileJob) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 29 with TypedQuery

use of javax.persistence.TypedQuery in project openremote by openremote.

the class ManagerIdentityProvider method getUsersFromDb.

static User[] getUsersFromDb(PersistenceService persistenceService, UserQuery query) {
    StringBuilder sb = new StringBuilder();
    List<Object> parameters = new ArrayList<>();
    final UserQuery userQuery = query != null ? query : new UserQuery();
    // BUILD SELECT
    sb.append("SELECT u");
    // BUILD FROM
    sb.append(" FROM User u");
    if (userQuery.assetPredicate != null || userQuery.pathPredicate != null) {
        sb.append(" join UserAssetLink ua on ua.id.userId = u.id");
    }
    // BUILD WHERE
    sb.append(" WHERE 1=1");
    if (userQuery.tenantPredicate != null && !TextUtil.isNullOrEmpty(userQuery.tenantPredicate.realm)) {
        sb.append(" AND u.realm = ?").append(parameters.size() + 1);
        parameters.add(userQuery.tenantPredicate.realm);
    }
    if (userQuery.assetPredicate != null) {
        sb.append(" AND ua.id.assetId = ?").append(parameters.size() + 1);
        parameters.add(userQuery.assetPredicate.id);
    }
    if (userQuery.pathPredicate != null) {
        sb.append(" AND ?").append(parameters.size() + 1).append(" <@ get_asset_tree_path(ua.asset_id)");
        parameters.add(userQuery.pathPredicate.path);
    }
    if (userQuery.ids != null && userQuery.ids.length > 0) {
        sb.append(" AND u.id IN (?").append(parameters.size() + 1);
        parameters.add(userQuery.ids[0]);
        for (int i = 1; i < userQuery.ids.length; i++) {
            sb.append(",?").append(parameters.size() + 1);
            parameters.add(userQuery.ids[i]);
        }
        sb.append(")");
    }
    if (userQuery.usernames != null && userQuery.usernames.length > 0) {
        sb.append(" and (");
        boolean isFirst = true;
        for (StringPredicate pred : userQuery.usernames) {
            if (!isFirst) {
                sb.append(" or ");
            }
            isFirst = false;
            final int pos = parameters.size() + 1;
            // No case support for username
            sb.append("upper(u.username)");
            sb.append(buildMatchFilter(pred, pos));
            parameters.add(pred.prepareValue());
        }
        sb.append(")");
    }
    if (userQuery.select != null && userQuery.select.excludeRegularUsers) {
        sb.append(" and u.secret IS NOT NULL");
    } else if (userQuery.select != null && userQuery.select.excludeServiceUsers) {
        sb.append(" and u.secret IS NULL");
    }
    // BUILD ORDER BY
    if (userQuery.orderBy != null) {
        if (userQuery.orderBy.property != null) {
            sb.append(" ORDER BY");
            switch(userQuery.orderBy.property) {
                case CREATED_ON:
                    sb.append(" u.createdOn");
                    break;
                case FIRST_NAME:
                    sb.append(" u.firstName");
                    break;
                case LAST_NAME:
                    sb.append(" u.lastName");
                    break;
                case USERNAME:
                    // Remove service user prefix
                    sb.append(" replace(u.username, '").append(User.SERVICE_ACCOUNT_PREFIX).append("', '')");
                    break;
                case EMAIL:
                    sb.append(" u.email");
                    break;
                default:
                    throw new UnsupportedOperationException("Unsupported order by value: " + userQuery.orderBy.property);
            }
            if (userQuery.orderBy.descending) {
                sb.append(" DESC");
            }
        }
    }
    List<User> users = persistenceService.doReturningTransaction(entityManager -> {
        TypedQuery<User> sqlQuery = entityManager.createQuery(sb.toString(), User.class);
        IntStream.range(0, parameters.size()).forEach(i -> sqlQuery.setParameter(i + 1, parameters.get(i)));
        if (userQuery.limit != null && userQuery.limit > 0) {
            sqlQuery.setMaxResults(userQuery.limit);
        }
        if (userQuery.offset != null && userQuery.offset > 0) {
            sqlQuery.setFirstResult(query.offset);
        }
        return sqlQuery.getResultList();
    });
    if (userQuery.select != null && (userQuery.select.basic || userQuery.select.excludeSystemUsers)) {
        // TODO: Move this within the query
        return users.stream().filter(user -> {
            boolean keep = !userQuery.select.excludeSystemUsers || !user.isSystemAccount();
            if (keep && userQuery.select.basic) {
                // Clear out data and leave only basic info
                user.setAttributes(null);
                user.setEmail(null);
                user.setRealmId(null);
                user.setSecret(null);
            }
            return keep;
        }).toArray(User[]::new);
    }
    return users.toArray(new User[0]);
}
Also used : IdentityProvider(org.openremote.container.security.IdentityProvider) AssetStorageService(org.openremote.manager.asset.AssetStorageService) org.openremote.model.security(org.openremote.model.security) IntStream(java.util.stream.IntStream) java.util(java.util) AssetStorageService.buildMatchFilter(org.openremote.manager.asset.AssetStorageService.buildMatchFilter) AuthContext(org.openremote.container.security.AuthContext) MASTER_REALM(org.openremote.model.Constants.MASTER_REALM) TypedQuery(javax.persistence.TypedQuery) Collectors(java.util.stream.Collectors) TenantFilter(org.openremote.model.event.shared.TenantFilter) StringPredicate(org.openremote.model.query.filter.StringPredicate) UserQuery(org.openremote.model.query.UserQuery) PersistenceService(org.openremote.container.persistence.PersistenceService) TextUtil(org.openremote.model.util.TextUtil) StringPredicate(org.openremote.model.query.filter.StringPredicate) UserQuery(org.openremote.model.query.UserQuery)

Example 30 with TypedQuery

use of javax.persistence.TypedQuery in project dataverse by IQSS.

the class OAIRecordServiceBean method findOAIRecordBySetNameandGlobalId.

public OAIRecord findOAIRecordBySetNameandGlobalId(String setName, String globalId) {
    OAIRecord oaiRecord = null;
    String queryString = "SELECT object(h) from OAIRecord h where h.globalId = :globalId";
    // and h.setName is null";
    queryString += setName != null ? " and h.setName = :setName" : "";
    logger.fine("findOAIRecordBySetNameandGlobalId; query: " + queryString + "; globalId: " + globalId + "; setName: " + setName);
    TypedQuery query = em.createQuery(queryString, OAIRecord.class).setParameter("globalId", globalId);
    if (setName != null) {
        query.setParameter("setName", setName);
    }
    try {
        oaiRecord = (OAIRecord) query.setMaxResults(1).getSingleResult();
    } catch (javax.persistence.NoResultException e) {
    // Do nothing, just return null.
    }
    logger.fine("returning oai record.");
    return oaiRecord;
}
Also used : TypedQuery(javax.persistence.TypedQuery)

Aggregations

TypedQuery (javax.persistence.TypedQuery)52 EntityManager (javax.persistence.EntityManager)28 List (java.util.List)24 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)24 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)21 ArrayList (java.util.ArrayList)16 Query (javax.persistence.Query)14 Predicate (javax.persistence.criteria.Predicate)14 Root (javax.persistence.criteria.Root)13 Map (java.util.Map)10 LinkedList (java.util.LinkedList)9 NoResultException (javax.persistence.NoResultException)9 Collectors (java.util.stream.Collectors)8 UserTransaction (javax.transaction.UserTransaction)8 Item (org.jpwh.model.querying.Item)8 Test (org.testng.annotations.Test)8 EntityTransaction (javax.persistence.EntityTransaction)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Set (java.util.Set)5