List of usage examples for org.hibernate.criterion Projections id
public static IdentifierProjection id()
From source file:net.firejack.platform.service.authority.broker.role.ReleaseContextUserRolesBroker.java
License:Apache License
@Override protected ServiceResponse perform(ServiceRequest<UserRole> request) throws Exception { List<UserRole> userRoles = request.getDataList(); ServiceResponse response;//from w ww .j ava2 s. c om if (userRoles == null || userRoles.isEmpty()) { response = new ServiceResponse<UserRole>("No user role information specified.", false); } else { OPFContext context = OPFContext.getContext(); if (context == null || context.getPrincipal().isGuestPrincipal()) { response = new ServiceResponse<UserRole>("Guest user is not authorized to release context roles.", false); } else { Set<String> lookupList = new HashSet<String>(); LinkedList<UserRole> userRolesValidated = new LinkedList<UserRole>(); for (UserRole userRole : userRoles) { Role role = userRole.getRole(); BaseUser user = userRole.getUser(); if (role != null && StringUtils.isNotBlank(role.getLookup()) && user != null && user.getId() != null && StringUtils.isNotBlank(userRole.getTypeLookup()) && (userRole.getModelId() != null || StringUtils.isNotBlank(userRole.getComplexPK()))) { userRolesValidated.add(userRole); lookupList.add(role.getLookup()); } } if (!lookupList.isEmpty()) { LinkedList<Criterion> restrictions = new LinkedList<Criterion>(); restrictions.add(Restrictions.in("lookup", lookupList)); List<Object[]> roles = roleStore.searchWithProjection(restrictions, Projections.projectionList().add(Projections.property("lookup")).add(Projections.id()), null); restrictions.clear(); Map<String, Long> rolesMap = new HashMap<String, Long>(); for (Object[] roleModelData : roles) { rolesMap.put((String) roleModelData[0], (Long) roleModelData[1]); } LinkedList<UserRoleModel> userRoleList = new LinkedList<UserRoleModel>(); for (UserRole userRole : userRolesValidated) { Role role = userRole.getRole(); if (role != null && StringUtils.isNotBlank(role.getLookup())) { Long roleId = rolesMap.get(role.getLookup()); if (roleId != null) { restrictions.add(Restrictions.eq("user.id", userRole.getUser().getId())); restrictions.add(Restrictions.eq("role.id", roleId)); restrictions.add(Restrictions.eq("type", userRole.getTypeLookup())); if (userRole.getModelId() == null) { restrictions.add(Restrictions.eq("externalId", userRole.getComplexPK())); } else { restrictions.add(Restrictions.eq("internalId", userRole.getModelId())); } List<UserRoleModel> foundUserRoles = userRoleStore.search(restrictions, null, null, false); if (!foundUserRoles.isEmpty()) { userRoleList.add(foundUserRoles.get(0)); } restrictions.clear(); } } } userRoleStore.deleteAll(userRoleList); } response = new ServiceResponse<UserRole>("Success", true); } } return response; }
From source file:net.webpasswordsafe.server.dao.PasswordDAOHibernate.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public List<Password> findPasswordByFuzzySearch(String query, User user, boolean activeOnly, Collection<Tag> tags, Match tagMatch) { //kludge to not use ilike on text column if MSSQL boolean isMSSQL = ((SessionFactoryImpl) getSessionFactory()).getDialect().toString().contains("SQLServer"); Criteria crit = getSession().createCriteria(getPersistentClass()); crit.setFetchMode("tags", FetchMode.JOIN); crit.add(Restrictions.or(/* ww w.j a v a2 s .c o m*/ Restrictions.or(Restrictions.ilike("name", query, MatchMode.ANYWHERE), Restrictions.ilike("username", query, MatchMode.ANYWHERE)), isMSSQL ? Restrictions.like("notes", query, MatchMode.ANYWHERE) : Restrictions.ilike("notes", query, MatchMode.ANYWHERE))); if (activeOnly) { crit.add(Restrictions.eq("active", true)); } Criterion tagsCriterion = null; for (Tag tag : tags) { Criterion tc = Restrictions.sqlRestriction( "? in (select tag_id from password_tags where password_id = {alias}.id)", tag.getId(), StandardBasicTypes.LONG); if (null == tagsCriterion) { tagsCriterion = tc; } else { tagsCriterion = tagMatch.equals(Match.AND) ? Restrictions.and(tagsCriterion, tc) : Restrictions.or(tagsCriterion, tc); } } if (tagsCriterion != null) crit.add(tagsCriterion); crit.createAlias("permissions", "pm"); crit.add(Restrictions.in("pm.accessLevel", new String[] { AccessLevel.READ.name(), AccessLevel.WRITE.name(), AccessLevel.GRANT.name() })); if (!authorizer.isAuthorized(user, Function.BYPASS_PASSWORD_PERMISSIONS.name())) { DetachedCriteria groupQuery = DetachedCriteria.forClass(Group.class); groupQuery.setProjection(Projections.id()); groupQuery.createCriteria("users", "u").add(Restrictions.eq("u.id", user.getId())); crit.add(Restrictions.or(Restrictions.eq("pm.subject", user), Subqueries.propertyIn("pm.subject", groupQuery))); } crit.addOrder(Order.asc("name")); crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return crit.list(); }
From source file:org.ambraproject.annotation.service.AnnotationServiceImpl.java
License:Apache License
@Override public Long createComment(UserProfile user, String articleDoi, String title, String body, String ciStatement, Context context, boolean flagAsCorrection) { if (articleDoi == null) { throw new IllegalArgumentException("Attempted to create comment with null article id"); } else if (user == null || user.getID() == null) { throw new IllegalArgumentException("Attempted to create comment without a creator"); } else if (body == null || body.isEmpty()) { throw new IllegalArgumentException("Attempted to create comment with no body"); }//from w w w . ja v a 2 s .com String xpath = null; if (context != null) { try { //ContextFormatter.asXPointer() can return null or empty if the context doesn't indicate a path xpath = ContextFormatter.asXPointer(context); } catch (ApplicationException e) { throw new IllegalArgumentException("Invalid context", e); } } log.debug("Creating comment on article: {}; title: {}; body: {}", new Object[] { articleDoi, title, body }); Long articleID; try { articleID = (Long) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", articleDoi)).setProjection(Projections.id())).get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Invalid doi: " + articleDoi); } //If the xpointer was valid, it's an inline note. Else it's a general comment AnnotationType type; if (!StringUtils.isEmpty(xpath)) { type = AnnotationType.NOTE; //kick the article out of cache articleHtmlCache.remove(articleDoi); } else { type = AnnotationType.COMMENT; } //generate an annotation uri Annotation comment = new Annotation(user, type, articleID); comment.setAnnotationUri(URIGenerator.generate(comment)); comment.setTitle(title); comment.setBody(body); comment.setCompetingInterestBody(ciStatement); comment.setXpath(xpath); Long id = (Long) hibernateTemplate.save(comment); if (flagAsCorrection) { Flag flag = new Flag(user, FlagReasonCode.CORRECTION, comment); flag.setComment("Note created and flagged as a correction"); hibernateTemplate.save(flag); } return id; }
From source file:org.ambraproject.article.service.ArticleServiceImpl.java
License:Apache License
@Override public ArticleInfo getBasicArticleView(String articleDoi) throws NoSuchArticleIdException { if (articleDoi == null) { throw new NoSuchArticleIdException("Null doi"); }/* w w w . j a va2s . com*/ log.debug("loading up title and doi for article: {}", articleDoi); Object[] results = new Object[0]; try { results = (Object[]) hibernateTemplate.findByCriteria( DetachedCriteria.forClass(Article.class).add(Restrictions.eq("doi", articleDoi)).setProjection( Projections.projectionList().add(Projections.id()).add(Projections.property("title"))), 0, 1).get(0); } catch (IndexOutOfBoundsException e) { throw new NoSuchArticleIdException(articleDoi.toString()); } ArticleInfo articleInfo = new ArticleInfo(); articleInfo.setDoi(articleDoi); articleInfo.setId((Long) results[0]); articleInfo.setTitle((String) results[1]); return articleInfo; }
From source file:org.ambraproject.service.annotation.AnnotationServiceImpl.java
License:Apache License
@Override @Transactional/*from www . j av a2 s .co m*/ public Long createComment(UserProfile user, String articleDoi, String title, String body, String ciStatement) { if (articleDoi == null) { throw new IllegalArgumentException("Attempted to create comment with null article id"); } else if (user == null || user.getID() == null) { throw new IllegalArgumentException("Attempted to create comment without a creator"); } else if (body == null || body.isEmpty()) { throw new IllegalArgumentException("Attempted to create comment with no body"); } log.debug("Creating comment on article: {}; title: {}; body: {}", new Object[] { articleDoi, title, body }); Long articleID; try { articleID = (Long) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", articleDoi)).setProjection(Projections.id())).get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Invalid doi: " + articleDoi); } //generate an annotation uri Annotation comment = new Annotation(user, AnnotationType.COMMENT, articleID); comment.setAnnotationUri(URIGenerator.generate(comment)); comment.setTitle(title); comment.setBody(body); comment.setCompetingInterestBody(ciStatement); Long id = (Long) hibernateTemplate.save(comment); return id; }
From source file:org.ambraproject.service.article.ArticleServiceImpl.java
License:Apache License
/** * Returns ArticleInfo object with articleID, doi, title, authors, collaborativeAuthors and article type populated * @param articleIdentifier articleID or articleDoi * @return ArticleInfo object with articleID, doi, title, authors, collaborativeAuthors and article type populated * @throws NoSuchArticleIdException/*from ww w . j av a2 s. c om*/ */ private ArticleInfo getBasicArticleViewArticleInfo(Object articleIdentifier) throws NoSuchArticleIdException { Object[] results = new Object[0]; List<ArticleAuthor> authors; List<String> collabAuthors; List<String> articleTypes; try { DetachedCriteria dc = DetachedCriteria.forClass(Article.class) .setProjection(Projections.projectionList().add(Projections.id()) .add(Projections.property("doi")).add(Projections.property("title"))); if (articleIdentifier instanceof Long) { dc.add(Restrictions.eq("ID", articleIdentifier)); } else if (articleIdentifier instanceof String) { dc.add(Restrictions.eq("doi", articleIdentifier)); } results = (Object[]) hibernateTemplate.findByCriteria(dc, 0, 1).get(0); authors = (List<ArticleAuthor>) hibernateTemplate.find("from ArticleAuthor where articleID = ?", results[0]); collabAuthors = (List<String>) hibernateTemplate.find( "select elements(article.collaborativeAuthors) from Article as article where id = ?", results[0]); articleTypes = (List<String>) hibernateTemplate .find("select elements(article.types) from Article as article where id = ?", results[0]); } catch (IndexOutOfBoundsException e) { throw new NoSuchArticleIdException(articleIdentifier.toString()); } ArticleInfo articleInfo = new ArticleInfo(); articleInfo.setId((Long) results[0]); articleInfo.setDoi((String) results[1]); articleInfo.setTitle((String) results[2]); List<String> authors2 = new ArrayList<String>(authors.size()); for (ArticleAuthor ac : authors) { authors2.add(ac.getFullName()); } articleInfo.setAuthors(authors2); articleInfo.setCollaborativeAuthors(collabAuthors); articleInfo.setAt(new HashSet<String>(articleTypes)); return articleInfo; }
From source file:org.ambraproject.service.trackback.LinkbackServiceImpl.java
License:Apache License
protected List<LinkbackView> getLinkbacksForArticle(Class<? extends Linkback> type, String articleDoi) { if (StringUtils.isEmpty(articleDoi)) { throw new IllegalArgumentException("No Doi specified"); }/* ww w . ja va 2s. c om*/ Long articleId; String articleTitle; try { Object[] articleRow = (Object[]) hibernateTemplate.findByCriteria( DetachedCriteria.forClass(Article.class).add(Restrictions.eq("doi", articleDoi)).setProjection( Projections.projectionList().add(Projections.id()).add(Projections.property("title"))), 0, 1).get(0); articleId = (Long) articleRow[0]; articleTitle = (String) articleRow[1]; } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Doi " + articleDoi + " didn't correspond to an article"); } log.debug("loading up linkbacks for article {}", articleDoi); List<? extends Linkback> linkbacks = (List<? extends Linkback>) hibernateTemplate .findByCriteria(DetachedCriteria.forClass(type).add(Restrictions.eq("articleID", articleId)) .addOrder(Order.desc("created")).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)); List<LinkbackView> results = new ArrayList<LinkbackView>(linkbacks.size()); for (Linkback linkback : linkbacks) { results.add(new LinkbackView(linkback, articleDoi, articleTitle)); } log.info("Loaded {} linkbacks for {}", results.size(), articleDoi); return results; }
From source file:org.ambraproject.service.trackback.LinkbackServiceImpl.java
License:Apache License
protected int countLinkbacksForArticle(Class<? extends Linkback> type, String articleDoi) { if (StringUtils.isEmpty(articleDoi)) { throw new IllegalArgumentException("Didn't specify an article doi"); }//from w w w.j a v a2 s .com Long articleId; try { articleId = (Long) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", articleDoi)).setProjection(Projections.id()), 0, 1).get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("Doi: " + articleDoi + " didn't correspond to an article"); } // Get a list of row counts, one for each subtype. Return their sum. List<? extends Number> counts = (List<? extends Number>) hibernateTemplate.findByCriteria(DetachedCriteria .forClass(type).add(Restrictions.eq("articleID", articleId)).setProjection(Projections.rowCount())); int sum = 0; for (Number count : counts) { sum += count.intValue(); } return sum; }
From source file:org.ambraproject.service.trackback.TrackbackServiceImpl.java
License:Apache License
@Override @SuppressWarnings("unchecked") @Transactional//from w w w. j a v a2 s . com public Long createTrackback(String articleDoi, String url, String title, String blogName, String excerpt) throws DuplicateTrackbackException { if (articleDoi == null) { throw new IllegalArgumentException("No DOI specified"); } else if (url == null || title == null || excerpt == null || blogName == null) { throw new IllegalArgumentException("URL, title, excerpt, and blog name must be provided"); } Long articleId; try { articleId = (Long) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", articleDoi)).setProjection(Projections.id()), 0, 1).get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("DOI: " + articleDoi + " didn't correspond to an article"); } List<Long> existingTrackbacks = (List<Long>) hibernateTemplate.findByCriteria( DetachedCriteria.forClass(Trackback.class).add(Restrictions.eq("articleID", articleId)) .add(Restrictions.eq("url", url)).setProjection(Projections.id())); if (existingTrackbacks.size() > 0) { throw new DuplicateTrackbackException(articleDoi, url); } else { log.debug("Creating trackback for article: {}; url: {}", articleDoi, url); Trackback trackback = new Trackback(); trackback.setArticleID(articleId); trackback.setTitle(title); trackback.setBlogName(blogName); trackback.setUrl(url); trackback.setExcerpt(excerpt); return (Long) hibernateTemplate.save(trackback); } }
From source file:org.ambraproject.testutils.DummyHibernateDataStore.java
License:Apache License
private Serializable getStoredId(Object object) { try {/* w w w . j av a2 s . co m*/ if (object instanceof Article) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("doi", ((Article) object).getDoi())).setProjection(Projections.id())) .get(0); } else if (object instanceof ArticleAsset) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(ArticleAsset.class) .add(Restrictions.eq("doi", ((ArticleAsset) object).getDoi())) .add(Restrictions.eq("extension", ((ArticleAsset) object).getExtension())) .setProjection(Projections.id())).get(0); } else if (object instanceof Category) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(ArticleAsset.class) .add(Restrictions.eq("mainCategory", ((Category) object).getMainCategory())) .add(Restrictions.eq("subCategory", ((Category) object).getSubCategory())) .setProjection(Projections.id())).get(0); } else if (object instanceof UserProfile) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(UserProfile.class) .add(Restrictions.eq("email", ((UserProfile) object).getEmail())) .add(Restrictions.eq("displayName", ((UserProfile) object).getDisplayName())) .setProjection(Projections.id())).get(0); } else if (object instanceof UserRole) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(UserRole.class) .add(Restrictions.eq("roleName", ((UserRole) object).getRoleName())) .setProjection(Projections.id())).get(0); } else if (object instanceof Annotation) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Annotation.class) .add(Restrictions.eq("annotationUri", ((Annotation) object).getAnnotationUri())) .setProjection(Projections.id())).get(0); } else if (object instanceof Trackback) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Trackback.class) .add(Restrictions.eq("articleID", ((Trackback) object).getArticleID())) .add(Restrictions.eq("url", ((Trackback) object).getUrl())).setProjection(Projections.id())) .get(0); } else if (object instanceof Journal) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Journal.class) .add(Restrictions.or(Restrictions.eq("journalKey", ((Journal) object).getJournalKey()), Restrictions.eq("eIssn", ((Journal) object).geteIssn()))) .setProjection(Projections.id())).get(0); } else if (object instanceof Volume) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Volume.class) .add(Restrictions.eq("volumeUri", ((Volume) object).getVolumeUri())) .setProjection(Projections.id())).get(0); } else if (object instanceof ArticleList) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(ArticleList.class) .add(Restrictions.eq("listKey", ((ArticleList) object).getListKey())) .setProjection(Projections.id())).get(0); } else if (object instanceof Issue) { return (Serializable) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Issue.class) .add(Restrictions.eq("issueUri", ((Issue) object).getIssueUri())) .setProjection(Projections.id())).get(0); } else { //check if the object has an id set on it String idPropertyName = allClassMetadata.get(object.getClass().getName()) .getIdentifierPropertyName(); String idGetterName = "get" + idPropertyName.substring(0, 1).toUpperCase() + idPropertyName.substring(1); return (Serializable) object.getClass().getMethod(idGetterName).invoke(object); } } catch (Exception e) { return null; } }