use of org.ambraproject.rhino.model.ArticleCategoryAssignment in project rhino by PLOS.
the class ArticleCrudServiceImpl method serveCategories.
/**
* {@inheritDoc}
*
* @param articleId
*/
@Override
public ServiceResponse<Collection<CategoryAssignmentView>> serveCategories(final ArticleIdentifier articleId) throws IOException {
Article article = readArticle(articleId);
Collection<ArticleCategoryAssignment> categoryAssignments = taxonomyService.getAssignmentsForArticle(article);
Collection<CategoryAssignmentView> views = categoryAssignments.stream().map(CategoryAssignmentView::new).collect(Collectors.toList());
return ServiceResponse.serveView(views);
}
use of org.ambraproject.rhino.model.ArticleCategoryAssignment in project rhino by PLOS.
the class TaxonomyClassificationServiceImpl method persistCategories.
private void persistCategories(List<WeightedTerm> terms, Article article) {
Set<String> termStrings = terms.stream().map(WeightedTerm::getPath).collect(Collectors.toSet());
Collection<Category> existingCategories = hibernateTemplate.execute(session -> {
Query query = session.createQuery("FROM Category WHERE path IN (:terms)");
query.setParameterList("terms", termStrings);
return (Collection<Category>) query.list();
});
Map<String, Category> existingCategoryMap = Maps.uniqueIndex(existingCategories, Category::getPath);
Collection<ArticleCategoryAssignment> existingAssignments = getAssignmentsForArticle(article);
Map<Category, ArticleCategoryAssignment> assignmentMap = Maps.uniqueIndex(existingAssignments, ArticleCategoryAssignment::getCategory);
// Make it mutable. We will remove assignments as they are updated.
assignmentMap = new HashMap<>(assignmentMap);
for (WeightedTerm term : terms) {
Category category = existingCategoryMap.get(term.getPath());
if (category == null) {
/*
* A new category from the taxonomy server, which is not yet persisted in our system. Create it now.
*
* This risks a race condition if two articles are being populated concurrently and both have the same new
* category, which can cause a "MySQLIntegrityConstraintViolationException: Duplicate entry" error.
*/
category = new Category();
category.setPath(term.getPath());
hibernateTemplate.save(category);
}
ArticleCategoryAssignment assignment = assignmentMap.remove(category);
if (assignment == null) {
hibernateTemplate.save(new ArticleCategoryAssignment(category, article, term.getWeight()));
} else {
assignment.setWeight(term.getWeight());
hibernateTemplate.update(assignment);
}
}
// Each assignment that was not removed from assignmentMap is not among the new terms, so it should be deleted.
assignmentMap.values().forEach(hibernateTemplate::delete);
}
Aggregations