List of usage examples for org.hibernate.criterion Projections projectionList
public static ProjectionList projectionList()
From source file:org.ambraproject.admin.service.impl.AdminServiceImpl.java
License:Apache License
@Override @Transactional/*from w w w . jav a2s . com*/ public void updateIssue(String issueUri, String imageUri, String displayName, boolean respectOrder, List<String> articleDois) { log.debug("Updating issue '{}'", issueUri); Issue issue; try { issue = (Issue) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Issue.class) .add(Restrictions.eq("issueUri", issueUri)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)) .get(0); } catch (IndexOutOfBoundsException e) { //if the issue doesn't exist, just return return; } //check that we aren't adding or removing an article here for (String oldDoi : issue.getArticleDois()) { if (!articleDois.contains(oldDoi)) { throw new IllegalArgumentException("Removed article '" + oldDoi + "' when updating issue"); } } for (String newDoi : articleDois) { if (!issue.getArticleDois().contains(newDoi)) { throw new IllegalArgumentException("Added article '" + newDoi + "' when updating issue"); } } issue.getArticleDois().clear(); issue.getArticleDois().addAll(articleDois); issue.setDisplayName(displayName); issue.setRespectOrder(respectOrder); issue.setImageUri(imageUri); //pull down title and description from the image article, if it exists try { Object[] titleAndDescription = (Object[]) hibernateTemplate .findByCriteria(DetachedCriteria.forClass(Article.class).add(Restrictions.eq("doi", imageUri)) .setProjection(Projections.projectionList().add(Projections.property("title")) .add(Projections.property("description")))) .get(0); issue.setTitle((String) titleAndDescription[0]); issue.setDescription((String) titleAndDescription[1]); } catch (IndexOutOfBoundsException e) { //it's ok if image article doesn't exist } hibernateTemplate.update(issue); }
From source file:org.ambraproject.annotation.service.AnnotationServiceImpl.java
License:Apache License
@Override @Transactional(readOnly = true)/*from w w w . jav a2 s.com*/ public AnnotationView[] listAnnotations(final Long articleID, final Set<AnnotationType> annotationTypes, final AnnotationOrder order) { //Basic criteria DetachedCriteria criteria = DetachedCriteria.forClass(Annotation.class) .add(Restrictions.eq("articleID", articleID)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); //restrict by type if (annotationTypes != null && !annotationTypes.isEmpty()) { criteria.add(Restrictions.in("type", annotationTypes)); } switch (order) { case OLDEST_TO_NEWEST: criteria.addOrder(Order.asc("created")); break; case MOST_RECENT_REPLY: //Still going to have to sort the results after creating views, because 'Most Recent Reply' isn't something that's stored on the database level //but ordering newest to oldest makes it more likely that the annotations will be in close to the correct order by the time we sort criteria.addOrder(Order.desc("created")); break; } List annotationResults = hibernateTemplate.findByCriteria(criteria); //Don't want to call buildAnnotationView() here because that would involve loading up the reply map for each annotation, // when we only need to do it once. So load up the info we need to build annotation views here Object[] articleTitleAndDoi; try { articleTitleAndDoi = (Object[]) hibernateTemplate .findByCriteria(DetachedCriteria.forClass(Article.class).add(Restrictions.eq("ID", articleID)) .setProjection(Projections.projectionList().add(Projections.property("doi")) .add(Projections.property("title"))), 0, 1) .get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("article " + articleID + " didn't exist"); } String articleDoi = (String) articleTitleAndDoi[0]; String articleTitle = (String) articleTitleAndDoi[1]; Map<Long, List<Annotation>> replyMap = buildReplyMap(articleID); List<AnnotationView> viewResults = new ArrayList<AnnotationView>(annotationResults.size()); for (Object annotation : annotationResults) { viewResults.add(new AnnotationView((Annotation) annotation, articleDoi, articleTitle, replyMap)); } if (order == AnnotationOrder.MOST_RECENT_REPLY) { //Order the results by the most recent reply date Collections.sort(viewResults, new Comparator<AnnotationView>() { @Override public int compare(AnnotationView view1, AnnotationView view2) { return -1 * view1.getLastReplyDate().compareTo(view2.getLastReplyDate()); } }); } return viewResults.toArray(new AnnotationView[viewResults.size()]); }
From source file:org.ambraproject.annotation.service.AnnotationServiceImpl.java
License:Apache License
@Override @Transactional(readOnly = true)/*from w w w . j ava 2s.c om*/ public AnnotationView[] listAnnotationsNoReplies(final Long articleID, final Set<AnnotationType> annotationTypes, final AnnotationOrder order) { if (order == AnnotationOrder.MOST_RECENT_REPLY) { throw new IllegalArgumentException( "Cannot specify Most Recent Reply order type when replies are not being loaded up"); } //Basic criteria DetachedCriteria criteria = DetachedCriteria.forClass(Annotation.class) .add(Restrictions.eq("articleID", articleID)).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); //restrict by type if (annotationTypes != null && !annotationTypes.isEmpty()) { criteria.add(Restrictions.in("type", annotationTypes)); } switch (order) { case OLDEST_TO_NEWEST: criteria.addOrder(Order.asc("created")); break; } List annotationResults = hibernateTemplate.findByCriteria(criteria); //Don't want to call buildAnnotationView() here because that would involve finding the article title and doi for each annotation, // when we only need to do it once. So load up the info we need to build annotation views here Object[] articleTitleAndDoi; try { articleTitleAndDoi = (Object[]) hibernateTemplate .findByCriteria(DetachedCriteria.forClass(Article.class).add(Restrictions.eq("ID", articleID)) .setProjection(Projections.projectionList().add(Projections.property("doi")) .add(Projections.property("title"))), 0, 1) .get(0); } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("article " + articleID + " didn't exist"); } String articleDoi = (String) articleTitleAndDoi[0]; String articleTitle = (String) articleTitleAndDoi[1]; List<AnnotationView> viewResults = new ArrayList<AnnotationView>(annotationResults.size()); for (Object annotation : annotationResults) { viewResults.add(new AnnotationView((Annotation) annotation, articleDoi, articleTitle, null)); } return viewResults.toArray(new AnnotationView[viewResults.size()]); }
From source file:org.ambraproject.annotation.service.AnnotationServiceImpl.java
License:Apache License
@SuppressWarnings("unchecked") private AnnotationView buildAnnotationView(Annotation annotation, boolean loadAllReplies) { Object values[];/*w w w .ja v a2 s.c o m*/ try { values = (Object[]) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("ID", annotation.getArticleID())).setProjection(Projections .projectionList().add(Projections.property("doi")).add(Projections.property("title"))), 0, 1).get(0); } catch (IndexOutOfBoundsException e) { //this should never happen throw new IllegalStateException("Annotation " + annotation.getID() + " pointed to an article that didn't exist;" + " articleID: " + annotation.getArticleID()); } String articleDoi = (String) values[0]; String articleTitle = (String) values[1]; return buildAnnotationView(annotation, articleDoi, articleTitle, loadAllReplies); }
From source file:org.ambraproject.article.service.ArticleServiceImpl.java
License:Apache License
/** * Returns a Map of publishable articles in the order indicated. The key of each element is the DOI (URI) of the * Article. The value of each element is the Article itself. * * @param eIssn eIssn of the Journal that this Article belongs to (no filter if null or empty) * @param orderField field on which to sort the results (no sort if null or empty) Should be one of the * ORDER_BY_FIELD_ constants from this class * @param isOrderAscending controls the sort order (default is "false" so default order is descending) * @return Map of publishable articles sorted as indicated * @throws org.ambraproject.ApplicationException * *//*from www.ja v a 2s . co m*/ public List<ArticleInfo> getPublishableArticles(String eIssn, String orderField, boolean isOrderAscending) throws ApplicationException { List<ArticleInfo> articlesInfo = new ArrayList<ArticleInfo>(); Order order = isOrderAscending ? Order.asc(orderField) : Order.desc(orderField); List<Object[]> results = hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("eIssn", eIssn)).add(Restrictions.eq("state", Article.STATE_UNPUBLISHED)) .addOrder(order).setProjection(Projections.projectionList().add(Projections.property("doi")) .add(Projections.property("date")))); for (Object[] rows : results) { ArticleInfo articleInfo = new ArticleInfo(); articleInfo.setDoi(rows[0].toString()); articleInfo.setDate((Date) rows[1]); articlesInfo.add(articleInfo); } return articlesInfo; }
From source file:org.ambraproject.article.service.ArticleServiceImpl.java
License:Apache License
@Override public ArticleInfo getBasicArticleView(Long articleID) throws NoSuchArticleIdException { if (articleID == null) { throw new NoSuchArticleIdException("Null id"); }//from w w w . j av a 2 s . c om log.debug("loading up title and doi for article: {}", articleID); Object[] results = new Object[0]; try { results = (Object[]) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class) .add(Restrictions.eq("ID", articleID)).setProjection(Projections.projectionList() .add(Projections.property("doi")).add(Projections.property("title"))), 0, 1).get(0); } catch (IndexOutOfBoundsException e) { throw new NoSuchArticleIdException(articleID.toString()); } ArticleInfo articleInfo = new ArticleInfo(); articleInfo.setDoi((String) results[0]); articleInfo.setTitle((String) results[1]); articleInfo.setId(articleID); return articleInfo; }
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"); }//from www . j av a 2 s .c o m 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.rhino.service.impl.ArticleCrudServiceImpl.java
License:Open Source License
@Override public Collection<String> getArticleDoisForDateRange(int pageNumber, int pageSize, SortOrder sortOrder, Optional<LocalDateTime> fromDate, Optional<LocalDateTime> toDate) { final long totalArticles = hibernateTemplate.execute(session -> { final Query query = session.createQuery("select count(*) from Article"); final Long count = (Long) query.uniqueResult(); return count; });/*from w w w . j a v a2s .c om*/ if (totalArticles > 0L) { pageNumber = max(pageNumber, 1); final int maxResults = min(pageSize, MAX_PAGE_SIZE); final int firstResult = (pageNumber - 1) * maxResults; if (LOG.isDebugEnabled()) { LOG.debug("pageNumber: {}, pageSize: {}", pageNumber, pageSize); LOG.debug("firstResult: {}, maxResults: {}", firstResult, maxResults); LOG.debug("sortOrder: {}", sortOrder); } if (firstResult < totalArticles) { final DetachedCriteria criteria = DetachedCriteria.forClass(Article.class); final ProjectionList projections = Projections.projectionList(); projections.add(Projections.property("doi" /* propertyName */)); criteria.setProjection(projections); // Set restrictions for filtering on date range, if any. if (fromDate.isPresent()) { criteria.add(Restrictions.ge("created" /* propertyName */, java.sql.Timestamp.valueOf(fromDate.get()))); } if (toDate.isPresent()) { criteria.add(Restrictions.le("created" /* propertyName */, java.sql.Timestamp.valueOf(toDate.get()))); } if (sortOrder == SortOrder.OLDEST) { criteria.addOrder(Order.asc("created" /* propertyName */)); } else { criteria.addOrder(Order.desc("created" /* propertyName */)); } @SuppressWarnings("unchecked") final List<String> articleDois = (List<String>) hibernateTemplate.findByCriteria(criteria, firstResult, maxResults); return articleDois; } } return ImmutableList.of(); }
From source file:org.ambraproject.search.SavedSearchRetrieverImpl.java
License:Apache License
/** * @inheritDoc/*w w w. j ava 2 s . co m*/ */ @Override @SuppressWarnings("unchecked") public List<SavedSearchJob> retrieveSearchAlerts(AlertType alertType, Date startTime, Date endTime) { List<SavedSearchJob> searchJobs = new ArrayList<SavedSearchJob>(); List<Object[]> paramsList = (List<Object[]>) hibernateTemplate.findByCriteria(DetachedCriteria .forClass(SavedSearch.class).createAlias("searchQuery", "s").add(alertType.getTypeCriterion()) .setFetchMode("searchQuery", FetchMode.JOIN) .setProjection(Projections.distinct(Projections.projectionList().add(Projections.property("s.ID")) .add(Projections.property("s.hash")).add(Projections.property("searchType")) .add(Projections.property("s.searchParams"))))); for (Object[] obj : paramsList) { searchJobs.add(SavedSearchJob.builder().setSavedSearchQueryID((Long) obj[0]).setHash((String) obj[1]) .setType((SavedSearchType) obj[2]).setSearchString((String) obj[3]) .setFrequency(alertType.name()).setStartDate(startTime).setEndDate(endTime).build()); } log.debug("Returning {} saved search(es) for type {}", searchJobs.size(), alertType); return searchJobs; }