org.sakaiproject.tool.assessment.facade.AssessmentGradingFacadeQueries Maven / Gradle / Ivy
/*
* Copyright (c) 2016, The Apereo Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/ecl2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.sakaiproject.tool.assessment.facade;
import java.io.File;
import java.text.Collator;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.collections4.comparators.NullComparator;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.NullPrecedence;
import org.hibernate.query.Query;
import org.sakaiproject.antivirus.api.VirusFoundException;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.cover.EventTrackingService;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.samigo.util.SamigoConstants;
import org.sakaiproject.service.gradebook.shared.GradebookExternalAssessmentService;
import org.sakaiproject.spring.SpringBeanLocator;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAssessmentData;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedItemData;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedSectionData;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingAttachment;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.GradingAttachmentData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingAttachment;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.MediaData;
import org.sakaiproject.tool.assessment.data.dao.grading.StudentGradingSummaryData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAttachmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AttachmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.EvaluationModelIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.PublishedAssessmentIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.grading.StudentGradingSummaryIfc;
import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc;
import org.sakaiproject.tool.assessment.integration.context.IntegrationContextFactory;
import org.sakaiproject.tool.assessment.services.ItemService;
import org.sakaiproject.tool.assessment.services.PersistenceHelper;
import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService;
import org.sakaiproject.user.api.UserDirectoryService;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.tool.assessment.services.PersistenceService;
@Slf4j
public class AssessmentGradingFacadeQueries extends HibernateDaoSupport implements AssessmentGradingFacadeQueriesAPI {
/**
* Default empty Constructor
*/
public AssessmentGradingFacadeQueries() {
}
/**
* Injected Services
*/
private ContentHostingService contentHostingService;
public void setContentHostingService(ContentHostingService contentHostingService) {
this.contentHostingService = contentHostingService;
}
private SecurityService securityService;
public void setSecurityService(SecurityService securityService) {
this.securityService = securityService;
}
private UserDirectoryService userDirectoryService;
public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
this.userDirectoryService = userDirectoryService;
}
private PersistenceHelper persistenceHelper;
public void setPersistenceHelper(PersistenceHelper persistenceHelper) {
this.persistenceHelper = persistenceHelper;
}
public List getTotalScores(final Long publishedId, final String which, final boolean getSubmittedOnly) {
if (publishedId == null) return Collections.emptyList();
try {
final HibernateCallback> hcb = session -> {
Criteria q = session.createCriteria(AssessmentGradingData.class)
.add(Restrictions.eq("publishedAssessmentId", publishedId))
.add(Restrictions.gt("status", AssessmentGradingData.REMOVED))
.addOrder(Order.asc("agentId").nulls(NullPrecedence.LAST))
.addOrder(Order.desc("finalScore").nulls(NullPrecedence.LAST))
.addOrder(Order.desc("submittedDate").nulls(NullPrecedence.LAST));
if (getSubmittedOnly) {
q.add(Restrictions.eq("forGrade", true));
} else {
q.add(Restrictions.or(
Restrictions.eq("forGrade", true),
Restrictions.and(
Restrictions.eq("forGrade", false),
Restrictions.eq("status", AssessmentGradingData.NO_SUBMISSION))));
}
return q.list();
};
List list = getHibernateTemplate().execute(hcb);
Map> attachmentMap = getAssessmentGradingAttachmentMap(publishedId);
for (AssessmentGradingData data : list) {
if (attachmentMap.get(data.getAssessmentGradingId()) != null) {
data.setAssessmentGradingAttachmentList(attachmentMap.get(data.getAssessmentGradingId()));
} else {
data.setAssessmentGradingAttachmentList(new ArrayList<>());
}
}
// last submission
if (which.equals(EvaluationModelIfc.LAST_SCORE.toString())) {
final HibernateCallback> hcb2 = session -> {
Criteria q = session.createCriteria(AssessmentGradingData.class)
.add(Restrictions.eq("publishedAssessmentId", publishedId))
.add(Restrictions.gt("status", AssessmentGradingData.REMOVED))
.addOrder(Order.asc("agentId").nulls(NullPrecedence.LAST))
.addOrder(Order.desc("submittedDate").nulls(NullPrecedence.LAST));
if (getSubmittedOnly) {
q.add(Restrictions.eq("forGrade", true));
} else {
q.add(Restrictions.or(
Restrictions.eq("forGrade", true),
Restrictions.and(
Restrictions.eq("forGrade", false),
Restrictions.eq("status", AssessmentGradingData.NO_SUBMISSION))));
}
return q.list();
};
list = getHibernateTemplate().execute(hcb2);
}
if (which.equals(EvaluationModelIfc.ALL_SCORE.toString()) || which.equals(EvaluationModelIfc.AVERAGE_SCORE.toString())) {
return list;
} else {
if (list.isEmpty()) {
return Collections.emptyList();
}
AssessmentGradingData first = list.get(0);
if (first != null) {
// TODO while refactoring noticed this only sets published assessment id on the first one and not the rest?
first.setPublishedAssessmentId(Long.valueOf(publishedId));
}
return new ArrayList<>(list.stream()
.collect(Collectors.toMap(AssessmentGradingData::getAgentId, p -> p, (p, q) -> p))
.values());
}
} catch (Exception e) {
log.warn(e.getMessage(), e);
return Collections.emptyList();
}
}
@SuppressWarnings("unchecked")
public List getAllSubmissions(final String publishedId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.forGrade = :forgrade and a.status > :status");
q.setParameter("id", Long.parseLong(publishedId));
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public List getAllAssessmentGradingData(final Long publishedId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.status <> :status and a.status <> :removed order by a.agentId asc, a.submittedDate desc");
q.setParameter("id", publishedId);
q.setParameter("status", AssessmentGradingData.NO_SUBMISSION);
q.setParameter("removed", AssessmentGradingData.REMOVED);
return q.list();
};
List list = getHibernateTemplate().execute(hcb);
list.forEach(agd -> agd.setItemGradingSet(getItemGradingSet(agd.getAssessmentGradingId())));
return list;
}
public Map> getItemScores(Long publishedId, final Long itemId, String which) {
List scores = getTotalScores(publishedId, which, true);
return getItemScores(itemId, scores, false);
}
public Map> getItemScores(Long publishedId, final Long itemId, String which, boolean loadItemGradingAttachment) {
List scores = getTotalScores(publishedId, which, true);
return getItemScores(itemId, scores, loadItemGradingAttachment);
}
public Map> getItemScores(final Long itemId, List scores, boolean loadItemGradingAttachment) {
try {
HashMap> map = new HashMap<>();
HibernateCallback> hcb = session -> {
Criteria criteria = session.createCriteria(ItemGradingData.class);
Disjunction disjunction = Expression.disjunction();
/** make list from AssessmentGradingData ids */
List gradingIdList = scores.stream()
.map(AssessmentGradingData::getAssessmentGradingId)
.collect(Collectors.toList());
/** create or disjunctive expression for (in clauses) */
List tempList;
for (int i = 0; i < gradingIdList.size(); i += 50) {
if (i + 50 > gradingIdList.size()) {
tempList = gradingIdList.subList(i, gradingIdList.size());
disjunction.add(Expression.in("assessmentGradingId", tempList));
} else {
tempList = gradingIdList.subList(i, i + 50);
disjunction.add(Expression.in("assessmentGradingId", tempList));
}
}
if (itemId.equals(Long.valueOf(0))) {
criteria.add(disjunction);
//criteria.add(Expression.isNotNull("submittedDate"));
} else {
/** create logical and between the pubCriterion and the disjunction criterion */
//Criterion pubCriterion = Expression.eq("publishedItem.itemId", itemId);
Criterion pubCriterion = Expression.eq("publishedItemId", itemId);
criteria.add(Expression.and(pubCriterion, disjunction));
//criteria.add(Expression.isNotNull("submittedDate"));
}
criteria.addOrder(Order.asc("agentId").nulls(NullPrecedence.LAST));
criteria.addOrder(Order.desc("submittedDate").nulls(NullPrecedence.LAST));
return criteria.list();
//large list cause out of memory error (java heap space)
//return criteria.setMaxResults(10000).list();
};
List temp = getHibernateTemplate().execute(hcb);
Map> attachmentMap = new HashMap<>();
if (loadItemGradingAttachment) {
attachmentMap = getItemGradingAttachmentMap(itemId);
}
for (ItemGradingData data : temp) {
if (loadItemGradingAttachment) {
if (attachmentMap.get(data.getItemGradingId()) != null) {
data.setItemGradingAttachmentSet(attachmentMap.get(data.getItemGradingId()));
} else {
data.setItemGradingAttachmentSet(new HashSet<>());
}
}
List thisone = map.get(data.getPublishedItemId());
if (thisone == null) {
thisone = new ArrayList<>();
}
thisone.add(data);
map.put(data.getPublishedItemId(), thisone);
}
map.forEach((k, v) -> {
Collections.sort(v, new Comparator() {
public int compare(ItemGradingData itg1, ItemGradingData itg2) {
return new NullComparator().compare(itg1.getPublishedAnswerId(), itg2.getPublishedAnswerId());
}
});
});
return map;
} catch (Exception e) {
log.warn(e.getMessage(), e);
return new HashMap<>();
}
}
/**
* This returns a hashmap of all the latest item entries, keyed by
* item id for easy retrieval.
*
* @param publishedId
* @param agentId
* @return
*/
public Map> getLastItemGradingData(final Long publishedId, final String agentId) {
try {
final HibernateCallback> hcb = session -> {
// I am debating should I use (a.forGrade=false and a.status=NO_SUBMISSION) or attemptDate is not null
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id " +
"and a.agentId = :agent and a.forGrade = :forgrade and a.status <> :status and a.status <> :removed " +
"order by a.submittedDate DESC");
q.setParameter("id", publishedId);
q.setParameter("agent", agentId);
q.setParameter("forgrade", false);
q.setParameter("status", AssessmentGradingData.NO_SUBMISSION);
q.setParameter("removed", AssessmentGradingData.REMOVED);
return q.list();
};
List scores = getHibernateTemplate().execute(hcb);
if (scores.isEmpty()) {
return new HashMap<>();
}
HashMap> map = new HashMap<>();
AssessmentGradingData gdata = scores.get(0);
// initialize itemGradingSet
gdata.setItemGradingSet(getItemGradingSet(gdata.getAssessmentGradingId()));
if (gdata.getForGrade()) {
return new HashMap<>();
}
for (ItemGradingData data : gdata.getItemGradingSet()) {
List thisone = map.get(data.getPublishedItemId());
if (thisone == null) {
thisone = new ArrayList<>();
}
thisone.add(data);
map.put(data.getPublishedItemId(), thisone);
}
return map;
} catch (Exception e) {
log.warn(e.getMessage(), e);
return new HashMap<>();
}
}
/**
* This returns a hashmap of all the submitted items, keyed by
* item id for easy retrieval.
*
* @param assessmentGradingId
* @return
*/
public HashMap getStudentGradingData(String assessmentGradingId) {
return getStudentGradingData(assessmentGradingId, true);
}
public HashMap getStudentGradingData(String assessmentGradingId, boolean loadGradingAttachment) {
try {
HashMap map = new HashMap();
AssessmentGradingData gdata = load(new Long(assessmentGradingId), loadGradingAttachment);
log.debug("****#6, gdata=" + gdata);
for (ItemGradingData data : gdata.getItemGradingSet()) {
ArrayList thisone = (ArrayList)
map.get(data.getPublishedItemId());
if (thisone == null)
thisone = new ArrayList();
thisone.add(data);
map.put(data.getPublishedItemId(), thisone);
}
return map;
} catch (Exception e) {
log.warn(e.getMessage(), e);
return new HashMap();
}
}
public Map> getSubmitData(final Long publishedId, final String agentId, final Integer scoringoption, final Long assessmentGradingId) {
try {
final HibernateCallback> hcb = session -> {
log.debug("scoringoption = " + scoringoption);
if (EvaluationModelIfc.LAST_SCORE.equals(scoringoption)) {
// last submission
Query q;
if (assessmentGradingId == null) {
q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status > :status order by a.submittedDate DESC");
q.setParameter("id", publishedId);
q.setParameter("agent", agentId);
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
} else {
q = session.createQuery("from AssessmentGradingData a where a.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
}
return q.list();
} else {
//highest submission
Query q1 = null;
if (assessmentGradingId == null) {
q1 = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status > :status order by a.finalScore DESC, a.submittedDate DESC");
q1.setParameter("id", publishedId);
q1.setParameter("agent", agentId);
q1.setParameter("forgrade", true);
q1.setParameter("status", AssessmentGradingData.REMOVED);
} else {
q1 = session.createQuery("from AssessmentGradingData a where a.assessmentGradingId = :id");
q1.setParameter("id", assessmentGradingId);
}
return q1.list();
}
};
List scores = getHibernateTemplate().execute(hcb);
HashMap> map = new HashMap<>();
if (scores.isEmpty()) {
return new HashMap<>();
}
AssessmentGradingData gdata = scores.get(0);
Map> attachmentMap = getItemGradingAttachmentMapByAssessmentGradingId(
gdata.getAssessmentGradingId());
gdata.setItemGradingSet(getItemGradingSet(gdata.getAssessmentGradingId()));
for (ItemGradingData data : gdata.getItemGradingSet()) {
if (attachmentMap.get(data.getItemGradingId()) != null) {
data.setItemGradingAttachmentSet(attachmentMap.get(data.getItemGradingId()));
} else {
data.setItemGradingAttachmentSet(new HashSet<>());
}
List thisone = map.get(data.getPublishedItemId());
if (thisone == null) {
thisone = new ArrayList<>();
}
thisone.add(data);
map.put(data.getPublishedItemId(), thisone);
}
return map;
} catch (Exception e) {
log.warn(e.getMessage(), e);
return new HashMap<>();
}
}
public Long add(AssessmentGradingData a) {
int retryCount = persistenceHelper.getRetryCount();
while (retryCount > 0) {
try {
getHibernateTemplate().save(a);
retryCount = 0;
} catch (Exception e) {
log.warn("problem adding assessmentGrading: " + e.getMessage());
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
return a.getAssessmentGradingId();
}
public int getSubmissionSizeOfPublishedAssessment(Long publishedAssessmentId) {
Number size = (Number) getHibernateTemplate().execute(session -> session.createCriteria(AssessmentGradingData.class)
.add(Restrictions.eq("publishedAssessmentId", publishedAssessmentId))
.add(Restrictions.eq("forGrade", true))
.setProjection(Projections.rowCount())
.uniqueResult());
return size.intValue();
}
public Long saveMedia(byte[] media, String mimeType) {
MediaData mediaData = new MediaData(media, mimeType);
mediaData.setFileSize((long) media.length);
return saveMedia(mediaData);
}
protected SecurityAdvisor pushAdvisor() {
SecurityAdvisor samigoAdvisor = new SecurityAdvisor() {
public SecurityAdvice isAllowed(String userId, String function, String reference) {
return SecurityAdvice.ALLOWED;
}
};
securityService.pushAdvisor(samigoAdvisor);
return samigoAdvisor;
}
protected void popAdvisor(SecurityAdvisor sa) {
if (sa != null) {
securityService.popAdvisor(sa);
}
else {
throw new IllegalArgumentException("popAdvisor was called with a null SecurityAdvisor");
}
}
protected boolean checkMediaCollection(String id) {
SecurityAdvisor resourceAdvisor = pushAdvisor();
try {
contentHostingService.checkCollection(id);
} catch (IdUnusedException | TypeException | PermissionException e) {
return false;
} finally {
popAdvisor(resourceAdvisor);
}
return true;
}
protected boolean ensureMediaCollection(String id) {
SecurityAdvisor resourceAdvisor = pushAdvisor();
try {
ContentCollection coll = contentHostingService.getCollection(id);
} catch (IdUnusedException ie) {
log.debug("Creating collection: " + id);
String name = id;
if (name.endsWith("/")) {
name = id.substring(0, id.length() - 1);
}
name = name.substring(name.lastIndexOf('/') + 1);
try {
ContentCollectionEdit edit = contentHostingService.addCollection(id);
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
contentHostingService.commitCollection(edit);
} catch (IdUsedException | IdInvalidException | PermissionException | InconsistentException collex) {
log.warn("[Samigo Media Attachments] Exception while creating collection (" + id + "): " + collex.toString());
return false;
}
} catch (TypeException | PermissionException e) {
log.warn("[Samigo Media Attachments] General exception while ensuring collection: " + e.toString());
} finally {
popAdvisor(resourceAdvisor);
}
return true;
}
protected boolean ensureMediaPath(String path) {
if (!path.startsWith("/")) {
throw new IllegalArgumentException("[Samigo Media Attachments] Relative media paths are not acceptable. (" + path + ")");
}
int lastSlash = path.lastIndexOf("/");
// Fast track already existing collections
if (lastSlash != 0 && checkMediaCollection(path.substring(0, lastSlash + 1))) {
return true;
}
// Ensure everything exists from the root
int slash = 1;
while (slash != lastSlash) {
slash = path.indexOf("/", slash + 1);
if (!ensureMediaCollection(path.substring(0, slash + 1))) {
return false;
}
}
return true;
}
/**
* Create or update a ContentResource for the media payload of this MediaData.
*
* @param mediaData the complete MediaData item to save if the media byte array is not null
* @return the ID in Content Hosting of the stored item; null on failure
*/
protected String saveMediaToContent(MediaData mediaData) {
String mediaPath = getMediaPath(mediaData);
if (mediaData.getMedia() != null && ensureMediaPath(mediaPath)) {
log.debug("=====> Saving media: " + mediaPath);
SecurityAdvisor resourceAdvisor = pushAdvisor();
boolean newResource = true;
try {
contentHostingService.checkResource(mediaPath);
newResource = false;
} catch (PermissionException | IdUnusedException | TypeException e) {
// Just a check, no handling
}
try {
ContentResource chsMedia;
if (newResource) {
ContentResourceEdit edit = contentHostingService.addResource(mediaPath);
edit.setContentType(mediaData.getMimeType());
edit.setContent(mediaData.getMedia());
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, mediaData.getFilename());
contentHostingService.commitResource(edit);
chsMedia = contentHostingService.getResource(mediaPath);
} else {
chsMedia = contentHostingService.updateResource(mediaPath,
mediaData.getMimeType(),
mediaData.getMedia());
}
mediaData.setContentResource(chsMedia);
return mediaPath;
} catch (PermissionException | IdUsedException | IdInvalidException | InconsistentException | ServerOverloadException | OverQuotaException | VirusFoundException | IdUnusedException | TypeException | InUseException e) {
log.warn("Exception while saving media to content: " + e.toString());
} finally {
popAdvisor(resourceAdvisor);
}
}
return null;
}
protected ContentResource getMediaContentResource(MediaData mediaData) {
if (mediaData.getContentResource() != null) {
return mediaData.getContentResource();
}
String id = getMediaPath(mediaData);
log.debug("=====> Reading media: " + id);
if (id != null) {
SecurityAdvisor resourceAdvisor = pushAdvisor();
try {
ContentResource res = contentHostingService.getResource(id);
return res;
} catch (IdUnusedException ie) {
log.info("Nonexistent resource when trying to load media (id: " + mediaData.getMediaId() + "): " + id);
} catch (PermissionException | TypeException e) {
log.debug("Exception while reading media from content (" + mediaData.getMediaId() + "):" + e.toString());
} finally {
popAdvisor(resourceAdvisor);
}
}
return null;
}
protected String getMediaPath(MediaData mediaData) {
String mediaBase = "/private/samigo/";
String mediaPath = null;
ItemGradingData itemGrading = mediaData.getItemGradingData();
if (itemGrading != null) {
PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService();
PublishedAssessmentIfc assessment = getPublishedAssessmentByAssessmentGradingId(
itemGrading.getAssessmentGradingId());
String assessmentId = assessment.getPublishedAssessmentId().toString();
String siteId = publishedAssessmentService.getPublishedAssessmentSiteId(assessmentId);
String userId = itemGrading.getAgentId();
String questionId = itemGrading.getPublishedItemId().toString();
if (questionId != null && assessmentId != null) {
mediaPath = mediaBase + siteId + "/" + assessmentId + "/" + userId + "/" + questionId + "_"
+ mediaData.getFilename();
}
}
return mediaPath;
}
public Long saveMedia(MediaData mediaData) {
log.debug("****" + mediaData.getFilename() + " saving media...size=" + mediaData.getFileSize() + " " + (new Date()));
int retryCount = persistenceHelper.getRetryCount();
getMediaPath(mediaData);
while (retryCount > 0) {
try {
saveMediaToContent(mediaData);
getHibernateTemplate().saveOrUpdate(mediaData);
retryCount = 0;
} catch (Exception e) {
log.warn("problem saving media: " + e.getMessage());
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
log.debug("****" + mediaData.getFilename() + " saved media." + (new Date()));
return mediaData.getMediaId();
}
public void removeMediaById(Long mediaId) {
removeMediaById(mediaId, null);
}
public void removeMediaById(Long mediaId, Long itemGradingId) {
String mediaLocation = null;
String mediaFilename = null;
int retryCount = persistenceHelper.getRetryCount();
while (retryCount > 0) {
try {
MediaData mediaData = this.getMedia(mediaId);
mediaLocation = mediaData.getLocation();
mediaFilename = mediaData.getFilename();
getHibernateTemplate().delete(mediaData);
retryCount = 0;
} catch (Exception e) {
log.warn("Problem deleting media with Id {}", mediaId);
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
if (mediaLocation != null) {
File mediaFile = new File(mediaLocation);
if (mediaFile.delete()) {
log.warn("problem removing file. mediaLocation = {}", mediaLocation);
}
}
if (itemGradingId != null) {
ItemGradingData itemGradingData = getItemGrading(itemGradingId);
itemGradingData.setAutoScore(Double.valueOf(0));
saveItemGrading(itemGradingData);
EventTrackingService.post(EventTrackingService.newEvent(SamigoConstants.EVENT_ASSESSMENT_ATTACHMENT_DELETE, "itemGradingId=" + itemGradingData.getItemGradingId() + ", " + mediaFilename, null, true, NotificationService.NOTI_REQUIRED));
}
}
public MediaData getMedia(Long mediaId) {
MediaData mediaData = (MediaData) getHibernateTemplate().load(MediaData.class, mediaId);
// Only try to read from Content Hosting if this isn't a link and
// there is no media content in the database
if (mediaData.getLocation() == null) {
mediaData.setContentResource(getMediaContentResource(mediaData));
}
return mediaData;
}
public List getMediaArray(final Long itemGradingId) {
log.debug("*** itemGradingId =" + itemGradingId);
List a = new ArrayList<>();
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("from MediaData m where m.itemGradingData.itemGradingId = :id");
q.setParameter("id", itemGradingId);
return q.list();
};
List list = getHibernateTemplate().execute(hcb);
for (MediaData mediaData : list) {
mediaData.setContentResource(getMediaContentResource(mediaData));
a.add(mediaData);
}
log.debug("*** no. of media = {}", a.size());
return a;
}
public List getMediaArray2(final Long itemGradingId) {
log.debug("*** itemGradingId =" + itemGradingId);
List a = new ArrayList<>();
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select new MediaData(m.mediaId, m.filename, m.fileSize, m.duration, m.createdDate) " +
" from MediaData m where m.itemGradingData.itemGradingId = :id");
q.setParameter("id", itemGradingId);
return q.list();
};
List list = getHibernateTemplate().execute(hcb);
for (MediaData mediaData : list) {
mediaData.setContentResource(getMediaContentResource(mediaData));
a.add(mediaData);
}
log.debug("*** no. of media = {}", a.size());
return a;
}
public Map> getMediaItemGradingHash(final Long assessmentGradingId) {
log.debug("*** assessmentGradingId = {}", assessmentGradingId);
Map> map = new HashMap<>();
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select i from MediaData m, ItemGradingData i " +
"where m.itemGradingData.itemGradingId = i.itemGradingId " +
"and i.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
return q.list();
};
List list = getHibernateTemplate().execute(hcb);
for (ItemGradingData itemGradingData : list) {
List al = new ArrayList<>();
al.add(itemGradingData);
// There might be duplicate. But we just overwrite it with the same itemGradingData
map.put(itemGradingData.getPublishedItemId(), al);
}
log.debug("*** no. of media = {}", map.size());
return map;
}
public ArrayList getMediaArray(ItemGradingData item) {
ArrayList a = new ArrayList();
List list = getHibernateTemplate().findByNamedParam(
"from MediaData m where m.itemGradingData = :id", "id", item);
for (int i = 0; i < list.size(); i++) {
MediaData mediaData = (MediaData) list.get(i);
mediaData.setContentResource(getMediaContentResource(mediaData));
a.add(mediaData);
}
log.debug("*** no. of media = {}", a.size());
return a;
}
public List getMediaArray(Long publishedId, final Long publishedItemId, String which) {
try {
Map> itemScores = getItemScores(publishedId, publishedItemId, which);
final List list = itemScores.get(publishedItemId);
log.debug("list size list.size() = " + list.size());
HibernateCallback> hcb = session -> {
Criteria criteria = session.createCriteria(MediaData.class);
Disjunction disjunction = Expression.disjunction();
/** make list from AssessmentGradingData ids */
List itemGradingIdList = list.stream()
.map(ItemGradingData::getItemGradingId)
.collect(Collectors.toList());
/** create or disjunctive expression for (in clauses) */
List tempList;
for (int i = 0; i < itemGradingIdList.size(); i += 50) {
if (i + 50 > itemGradingIdList.size()) {
tempList = itemGradingIdList.subList(i, itemGradingIdList.size());
disjunction.add(Expression.in("itemGradingData.itemGradingId", tempList));
} else {
tempList = itemGradingIdList.subList(i, i + 50);
disjunction.add(Expression.in("itemGradingData.itemGradingId", tempList));
}
}
criteria.add(disjunction);
return criteria.list();
//large list cause out of memory error (java heap space)
//return criteria.setMaxResults(10000).list();
};
List a = new ArrayList<>();
List hbmList = getHibernateTemplate().execute(hcb);
for (MediaData mediaData : hbmList) {
mediaData.setContentResource(getMediaContentResource(mediaData));
a.add(mediaData);
}
return a;
} catch (Exception e) {
log.warn(e.getMessage(), e);
return new ArrayList<>();
}
}
public List getMediaConversionBatch() {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("SELECT id FROM MediaData WHERE dbMedia IS NOT NULL AND location IS NULL");
q.setMaxResults(10);
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public boolean markMediaForConversion(final List mediaIds) {
final HibernateCallback hcb = session -> {
Query q = session.createQuery("UPDATE MediaData SET location = 'CONVERTING' WHERE id in (:ids)");
q.setParameterList("ids", mediaIds);
return q.executeUpdate();
};
return getHibernateTemplate().execute(hcb).equals(mediaIds.size());
}
public List getMediaWithDataAndLocation() {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("SELECT id FROM MediaData WHERE dbMedia IS NOT NULL AND location IS NOT NULL");
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public List getMediaInConversion() {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("SELECT id FROM MediaData WHERE location = 'CONVERTING'");
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public ItemGradingData getLastItemGradingDataByAgent(final Long publishedItemId, final String agentId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("from ItemGradingData i where i.publishedItemId = :id and i.agentId = :agent");
q.setParameter("id", publishedItemId);
q.setParameter("agent", agentId);
return q.list();
};
List itemGradings = getHibernateTemplate().execute(hcb);
if (itemGradings.isEmpty()) {
return null;
}
return itemGradings.get(0);
}
public ItemGradingData getItemGradingData(final Long itemGradingId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("from ItemGradingData i where i.itemGradingId = :id");
q.setParameter("id", itemGradingId);
return q.list();
};
List itemGradings = getHibernateTemplate().execute(hcb);
if (itemGradings.isEmpty()) {
return null;
}
;
return itemGradings.get(0);
}
public ItemGradingData getItemGradingData(final Long assessmentGradingId, final Long publishedItemId) {
log.debug("****assessmentGradingId={}", assessmentGradingId);
log.debug("****publishedItemId={}", publishedItemId);
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from ItemGradingData i where i.assessmentGradingId = :gradingid and i.publishedItemId = :itemid");
q.setParameter("gradingid", assessmentGradingId);
q.setParameter("itemid", publishedItemId);
return q.list();
};
List itemGradings = getHibernateTemplate().execute(hcb);
if (itemGradings.isEmpty()) {
return null;
}
return itemGradings.get(0);
}
public AssessmentGradingData load(Long id) {
return load(id, true);
}
public AssessmentGradingData load(Long id, boolean loadGradingAttachment) {
AssessmentGradingData gdata = (AssessmentGradingData) getHibernateTemplate().load(AssessmentGradingData.class,
id);
Set itemGradingSet = new HashSet();
// Get (ItemGradingId, ItemGradingData) pair
Map itemGradingMap = getItemGradingMap(gdata.getAssessmentGradingId());
if (itemGradingMap.keySet().size() > 0) {
Collection itemGradingCollection = itemGradingMap.values();
if (loadGradingAttachment) {
// Get (ItemGradingId, ItemGradingAttachment) pair
Map> attachmentMap = getItemGradingAttachmentMap(itemGradingMap.keySet());
Iterator iter = itemGradingCollection.iterator();
while (iter.hasNext()) {
ItemGradingData itemGradingData = iter.next();
if (attachmentMap.get(itemGradingData.getItemGradingId()) != null) {
itemGradingData.setItemGradingAttachmentSet(attachmentMap.get(itemGradingData.getItemGradingId()));
} else {
itemGradingData.setItemGradingAttachmentSet(new HashSet<>());
}
itemGradingSet.add(itemGradingData);
}
} else {
itemGradingSet.addAll(itemGradingCollection);
}
}
gdata.setItemGradingSet(itemGradingSet);
return gdata;
}
public ItemGradingData getItemGrading(Long id) {
return (ItemGradingData) getHibernateTemplate().load(ItemGradingData.class, id);
}
public AssessmentGradingData getLastSavedAssessmentGradingByAgentId(final Long publishedAssessmentId, final String agentIdString) {
AssessmentGradingData ag = null;
// don't pick the assessmentGradingData that is created by instructor entering comments/scores
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status not in (:status1, :status2) order by a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("agent", agentIdString);
q.setParameter("forgrade", false);
q.setParameter("status1", AssessmentGradingData.NO_SUBMISSION);
q.setParameter("status2", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
if (!assessmentGradings.isEmpty()) {
ag = assessmentGradings.get(0);
ag.setItemGradingSet(getItemGradingSet(ag.getAssessmentGradingId()));
}
return ag;
}
public AssessmentGradingData getLastSubmittedAssessmentGradingByAgentId(final Long publishedAssessmentId, final String agentIdString, Long assessmentGradingId) {
AssessmentGradingData ag = null;
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status > :status order by a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("agent", agentIdString);
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
if (assessmentGradingId == null) {
if (assessmentGradings.size() > 0) {
ag = assessmentGradings.get(0);
}
} else {
for (int i = 0; i < assessmentGradings.size(); i++) {
AssessmentGradingData agd = assessmentGradings.get(i);
if (agd.getAssessmentGradingId().compareTo(assessmentGradingId) == 0) {
ag = agd;
ag.setItemGradingSet(getItemGradingSet(agd.getAssessmentGradingId()));
break;
}
}
}
if (ag != null) {
// get AssessmentGradingAttachments
Map> map = getAssessmentGradingAttachmentMap(publishedAssessmentId);
List attachments = map.get(ag.getAssessmentGradingId());
if (attachments != null) {
ag.setAssessmentGradingAttachmentList(attachments);
} else {
ag.setAssessmentGradingAttachmentList(new ArrayList());
}
}
return ag;
}
public AssessmentGradingData getLastAssessmentGradingByAgentId(final Long publishedAssessmentId, final String agentIdString) {
AssessmentGradingData ag = null;
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.status > :status order by a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("agent", agentIdString);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
if (!assessmentGradings.isEmpty()) {
ag = assessmentGradings.get(0);
ag.setItemGradingSet(getItemGradingSet(ag.getAssessmentGradingId()));
}
return ag;
}
public void saveItemGrading(ItemGradingData item) {
int retryCount = persistenceHelper.getRetryCount();
while (retryCount > 0) {
try {
getHibernateTemplate().saveOrUpdate(item);
retryCount = 0;
} catch (Exception e) {
log.warn("problem saving itemGrading: " + e.getMessage());
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
}
public boolean saveOrUpdateAssessmentGrading(AssessmentGradingData assessment) {
int retryCount = persistenceHelper.getRetryCount();
boolean success = false;
while (retryCount > 0) {
try {
if (assessment.getAssessmentGradingId() != null) {
getHibernateTemplate().merge((AssessmentGradingData) assessment);
}
else {
getHibernateTemplate().save((AssessmentGradingData) assessment);
}
retryCount = 0;
success = true;
} catch (Exception e) {
log.warn("problem inserting/updating assessmentGrading: {}", e.getMessage());
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
return success;
}
public List getAssessmentGradingIds(final Long publishedItemId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select g.assessmentGradingId from ItemGradingData g where g.publishedItemId = :id");
q.setParameter("id", publishedItemId);
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public AssessmentGradingData getHighestAssessmentGrading(final Long publishedAssessmentId, final String agentId) {
AssessmentGradingData ag = null;
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and " +
" a.agentId = :agent and a.status > :status order by a.finalScore desc, a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("agent", agentId);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
if (!assessmentGradings.isEmpty()) {
ag = assessmentGradings.get(0);
ag.setItemGradingSet(getItemGradingSet(ag.getAssessmentGradingId()));
}
return ag;
}
public AssessmentGradingData getHighestSubmittedAssessmentGrading(final Long publishedAssessmentId, final String agentId, Long assessmentGradingId) {
AssessmentGradingData ag = null;
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and " +
" a.forGrade = :forgrade and a.status > :status order by a.finalScore desc, a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("agent", agentId);
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
if (assessmentGradingId == null) {
if (assessmentGradings.size() > 0) {
ag = assessmentGradings.get(0);
}
} else {
for (int i = 0; i < assessmentGradings.size(); i++) {
AssessmentGradingData agd = assessmentGradings.get(i);
if (agd.getAssessmentGradingId().compareTo(assessmentGradingId) == 0) {
ag = agd;
ag.setItemGradingSet(getItemGradingSet(agd.getAssessmentGradingId()));
break;
}
}
}
// get AssessmentGradingAttachments
List attachments = new ArrayList();
if (ag != null) {
Map> map = getAssessmentGradingAttachmentMap(publishedAssessmentId);
if (map != null && map.containsKey(ag.getAssessmentGradingId())) {
attachments = map.get(ag.getAssessmentGradingId());
}
ag.setAssessmentGradingAttachmentList(attachments);
}
return ag;
}
public List getLastAssessmentGradingList(final Long publishedAssessmentId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.status > :status order by a.agentId asc, a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
return new ArrayList<>(assessmentGradings.stream()
.collect(Collectors.toMap(AssessmentGradingData::getAgentId, p -> p, (p, q) -> p))
.values());
}
public List getLastSubmittedAssessmentGradingList(final Long publishedAssessmentId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select a from AssessmentGradingData a left join fetch a.assessmentGradingAttachmentSet " +
"where a.publishedAssessmentId = :id and a.forGrade = :forgrade and a.status > :status order by a.agentId asc, a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
return new ArrayList<>(assessmentGradings.stream()
.collect(Collectors.toMap(AssessmentGradingData::getAgentId, p -> p, (p, q) -> p))
.values());
}
public List getLastSubmittedOrGradedAssessmentGradingList(final Long publishedAssessmentId) {
final HibernateCallback> hcb = session -> session.createCriteria(
AssessmentGradingData.class)
.add(Restrictions.eq("publishedAssessmentId", publishedAssessmentId))
.add(Restrictions.or(
Restrictions.eq("forGrade", true),
Restrictions.and(
Restrictions.eq("forGrade", false),
Restrictions.eq("status", AssessmentGradingData.NO_SUBMISSION))))
.addOrder(Order.asc("agentId").nulls(NullPrecedence.LAST))
.addOrder(Order.desc("submittedDate").nulls(NullPrecedence.LAST))
.list();
List assessmentGradings = getHibernateTemplate().execute(hcb);
return new ArrayList<>(assessmentGradings.stream()
.collect(Collectors.toMap(AssessmentGradingData::getAgentId, p -> p, (p, q) -> p))
.values());
}
public List getHighestAssessmentGradingList(final Long publishedAssessmentId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.status > :status order by a.agentId asc, a.finalScore desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
return new ArrayList<>(assessmentGradings.stream()
.collect(Collectors.toMap(AssessmentGradingData::getAgentId, p -> p, (p, q) -> p))
.values());
}
public List getHighestSubmittedOrGradedAssessmentGradingList(final Long publishedAssessmentId) {
final HibernateCallback> hcb = session -> session.createCriteria(
AssessmentGradingData.class)
.add(Restrictions.eq("publishedAssessmentId", publishedAssessmentId))
.add(Restrictions.gt("status", AssessmentGradingData.REMOVED))
.add(Restrictions.or(
Restrictions.eq("forGrade", true),
Restrictions.and(
Restrictions.eq("forGrade", false),
Restrictions.eq("status", AssessmentGradingData.NO_SUBMISSION))))
.addOrder(Order.asc("agentId").nulls(NullPrecedence.LAST))
.addOrder(Order.desc("finalScore").nulls(NullPrecedence.LAST))
.list();
List assessmentGradings = getHibernateTemplate().execute(hcb);
return new ArrayList<>(assessmentGradings.stream()
.collect(Collectors.toMap(AssessmentGradingData::getAgentId, p -> p, (p, q) -> p))
.values());
}
// build a Hashmap (Long publishedItemId, ArrayList assessmentGradingIds)
// containing the item submission of the last AssessmentGrading
// (regardless of users who submitted it) of a given published assessment
public Map> getLastAssessmentGradingByPublishedItem(final Long publishedAssessmentId) {
Map> h = new HashMap<>();
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select new AssessmentGradingData(" +
" a.assessmentGradingId, p.itemId, " +
" a.agentId, a.finalScore, a.submittedDate) " +
" from ItemGradingData i, AssessmentGradingData a," +
" PublishedItemData p where " +
" i.assessmentGradingId = a.assessmentGradingId and i.publishedItemId = p.itemId and " +
" a.publishedAssessmentId = :id and a.status > :status " +
" order by a.agentId asc, a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
String currentAgent = "";
Date submittedDate = null;
for (int i = 0; i < assessmentGradings.size(); i++) {
AssessmentGradingData g = assessmentGradings.get(i);
Long itemId = g.getPublishedItemId();
Long gradingId = g.getAssessmentGradingId();
log.debug("**** itemId=" + itemId + ", gradingId=" + gradingId + ", agentId=" + g.getAgentId() + ", score=" + g
.getFinalScore());
if (i == 0) {
currentAgent = g.getAgentId();
submittedDate = g.getSubmittedDate();
}
if (currentAgent.equals(g.getAgentId())
&& ((submittedDate == null && g.getSubmittedDate() == null)
|| (submittedDate != null && submittedDate.equals(g.getSubmittedDate())))) {
List o = h.get(itemId);
if (o != null) {
o.add(gradingId);
} else {
List gradingIds = new ArrayList<>();
gradingIds.add(gradingId);
h.put(itemId, gradingIds);
}
}
if (!currentAgent.equals(g.getAgentId())) {
currentAgent = g.getAgentId();
submittedDate = g.getSubmittedDate();
}
}
return h;
}
// build a Hashmap (Long publishedItemId, ArrayList assessmentGradingIds)
// containing the item submission of the highest AssessmentGrading
// (regardless of users who submitted it) of a given published assessment
public Map> getHighestAssessmentGradingByPublishedItem(final Long publishedAssessmentId) {
Map> h = new HashMap<>();
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select new AssessmentGradingData(" +
" a.assessmentGradingId, p.itemId, " +
" a.agentId, a.finalScore, a.submittedDate) " +
" from ItemGradingData i, AssessmentGradingData a, " +
" PublishedItemData p where " +
" i.assessmentGradingId = a.assessmentGradingId and i.publishedItemId = p.itemId and " +
" a.publishedAssessmentId = :id and a.status > :status " +
" order by a.agentId asc, a.finalScore desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List assessmentGradings = getHibernateTemplate().execute(hcb);
String currentAgent = "";
Double finalScore = null;
for (int i = 0; i < assessmentGradings.size(); i++) {
AssessmentGradingData g = (AssessmentGradingData) assessmentGradings.get(i);
Long itemId = g.getPublishedItemId();
Long gradingId = g.getAssessmentGradingId();
log.debug("**** itemId=" + itemId + ", gradingId=" + gradingId + ", agentId=" + g.getAgentId() + ", score=" + g
.getFinalScore());
if (i == 0) {
currentAgent = g.getAgentId();
finalScore = g.getFinalScore();
}
if (currentAgent.equals(g.getAgentId())
&& ((finalScore == null && g.getFinalScore() == null)
|| (finalScore != null && finalScore.equals(g.getFinalScore())))) {
List o = h.get(itemId);
if (o != null) {
o.add(gradingId);
} else {
List gradingIds = new ArrayList<>();
gradingIds.add(gradingId);
h.put(itemId, gradingIds);
}
}
if (!currentAgent.equals(g.getAgentId())) {
currentAgent = g.getAgentId();
finalScore = g.getFinalScore();
}
}
return h;
}
public Set getItemGradingSet(final Long assessmentGradingId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("from ItemGradingData i where i.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
return q.list();
};
List itemGradings = getHibernateTemplate().execute(hcb);
return new HashSet<>(itemGradings);
}
public Map getItemGradingMap(final Long assessmentGradingId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("from ItemGradingData i where i.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
return q.list();
};
List itemGradingList = getHibernateTemplate().execute(hcb);
return itemGradingList.stream().collect(Collectors.toMap(ItemGradingData::getItemGradingId, p -> p));
}
public Map getAssessmentGradingByItemGradingId(final Long publishedAssessmentId) {
Map submissionDataMap = getAllSubmissions(publishedAssessmentId.toString()).stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(AssessmentGradingData::getAssessmentGradingId, a -> a));
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select new ItemGradingData(i.itemGradingId, a.assessmentGradingId) " +
" from ItemGradingData i, AssessmentGradingData a " +
" where i.assessmentGradingId = a.assessmentGradingId " +
" and a.publishedAssessmentId = :id " +
" and a.forGrade = :forgrade and a.status > :status ");
q.setParameter("id", publishedAssessmentId);
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List l = getHibernateTemplate().execute(hcb);
return l.stream().filter(i -> Objects.nonNull(submissionDataMap.get(i.getAssessmentGradingId())))
.collect(Collectors.toMap(ItemGradingData::getItemGradingId, g -> submissionDataMap.get(g.getAssessmentGradingId())));
}
public void deleteAll(Collection c) {
int retryCount = persistenceHelper.getRetryCount();
while (retryCount > 0) {
try {
c.stream().filter(Objects::nonNull).map(getHibernateTemplate()::merge).forEach(getHibernateTemplate()::delete);
retryCount = 0;
} catch (Exception e) {
log.warn("problem inserting assessmentGrading: {}", e.toString());
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
}
public void saveOrUpdateAll(Collection c) {
int retryCount = persistenceHelper.getRetryCount();
c.removeAll(Collections.singleton(null));
while (retryCount > 0) {
try {
for (ItemGradingData itemGradingData : c) {
getHibernateTemplate().merge(itemGradingData);
}
retryCount = 0;
} catch (Exception e) {
log.warn("problem inserting assessmentGrading: " + e.getMessage());
retryCount = persistenceHelper.retryDeadlock(e, retryCount);
}
}
}
public PublishedAssessmentIfc getPublishedAssessmentByAssessmentGradingId(final Long assessmentGradingId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select p from PublishedAssessmentData p, AssessmentGradingData a where a.publishedAssessmentId = p.publishedAssessmentId and a.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
return q.list();
};
List pubList = getHibernateTemplate().execute(hcb);
if (pubList != null && !pubList.isEmpty()) {
return pubList.get(0);
}
return null;
}
public PublishedAssessmentIfc getPublishedAssessmentByPublishedItemId(final Long publishedItemId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select p from PublishedAssessmentData p, PublishedItemData i where p.publishedAssessmentId = i.section.assessment.publishedAssessmentId and i.itemId = :id");
q.setParameter("id", publishedItemId);
return q.list();
};
List pubList = getHibernateTemplate().execute(hcb);
if (pubList != null && !pubList.isEmpty()) {
return pubList.get(0);
}
return null;
}
public List getLastItemGradingDataPosition(final Long assessmentGradingId, final String agentId) {
List position = new ArrayList<>();
try {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery("select s.sequence " +
" from ItemGradingData i, PublishedItemData pi, PublishedSectionData s " +
" where i.agentId = :agent and i.assessmentGradingId = :id " +
" and pi.itemId = i.publishedItemId " +
" and pi.section.id = s.id " +
" group by i.publishedItemId, s.sequence, pi.sequence " +
" order by s.sequence desc , pi.sequence desc");
q.setParameter("agent", agentId);
q.setParameter("id", assessmentGradingId);
return q.list();
};
List list = getHibernateTemplate().execute(hcb);
if (list.isEmpty()) {
position.add(0);
position.add(0);
} else {
Integer sequence = list.get(0);
Integer nextSequence;
int count = 1;
for (int i = 1; i < list.size(); i++) {
log.debug("i = {}", i);
nextSequence = list.get(i);
if (sequence.equals(nextSequence)) {
log.debug("equal");
count++;
} else {
break;
}
}
log.debug("sequence = " + sequence);
log.debug("count = " + count);
position.add(sequence);
position.add(count);
}
return position;
} catch (Exception e) {
log.warn(e.getMessage(), e);
position.add(0);
position.add(0);
return position;
}
}
public List getPublishedItemIds(final Long assessmentGradingId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select i.publishedItemId from ItemGradingData i where i.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public List getItemGradingIds(final Long assessmentGradingId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select i.itemGradingId from ItemGradingData i where i.assessmentGradingId = :id");
q.setParameter("id", assessmentGradingId);
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public Set getItemSet(final Long publishedAssessmentId, final Long sectionId) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select distinct p.itemId " +
"from PublishedItemData p, AssessmentGradingData a, ItemGradingData i " +
"where a.publishedAssessmentId = :id and a.forGrade = :forgrade and p.section.id = :sectionid " +
"and i.assessmentGradingId = a.assessmentGradingId " +
"and p.itemId = i.publishedItemId and a.status > :status ");
q.setParameter("id", publishedAssessmentId);
q.setParameter("forgrade", true);
q.setParameter("sectionid", sectionId);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
List itemIds = getHibernateTemplate().execute(hcb);
if (itemIds.isEmpty()) {
return new HashSet<>();
}
final HibernateCallback> hcb2 = session -> {
final Criteria criteria = session.createCriteria(PublishedItemData.class);
if (itemIds.size() > 1000) {
final Set ids = new HashSet<>();
Disjunction disjunction = Restrictions.disjunction();
for (Long id : itemIds) {
if (ids.size() < 1000) {
ids.add(id);
} else {
criteria.add(disjunction.add(Restrictions.in("itemId", ids)));
ids.clear();
}
}
} else {
criteria.add(Restrictions.in("itemId", itemIds));
}
return criteria.list();
};
List publishedItems = getHibernateTemplate().execute(hcb2);
return new HashSet<>(publishedItems);
}
public Long getTypeId(final Long itemGradingId) {
Long typeId = Long.valueOf(-1);
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"select p.typeId " +
"from PublishedItemData p, ItemGradingData i " +
"where i.itemGradingId = :id " +
"and p.itemId = i.publishedItemId ");
q.setParameter("id", itemGradingId);
return q.list();
};
List typeIds = getHibernateTemplate().execute(hcb);
if (typeIds != null) {
for (Long id : typeIds) {
typeId = id;
log.debug("typeId = {}", typeId);
}
}
return typeId;
}
public List getAllAssessmentGradingByAgentId(final Long publishedAssessmentId, final String agentIdString) {
final HibernateCallback> hcb = session -> {
Query q = session.createQuery(
"from AssessmentGradingData a where a.publishedAssessmentId = :id and a.agentId = :agent and a.forGrade = :forgrade and a.status > :status order by a.submittedDate desc");
q.setParameter("id", publishedAssessmentId);
q.setParameter("agent", agentIdString);
q.setParameter("forgrade", true);
q.setParameter("status", AssessmentGradingData.REMOVED);
return q.list();
};
return getHibernateTemplate().execute(hcb);
}
public List getAllItemGradingDataForItemInGrading(final Long assesmentGradingId, final Long publishedItemId) {
if (assesmentGradingId == null) {
throw new IllegalArgumentException("assesmentGradingId cant' be null");
}
if (publishedItemId == null) {
throw new IllegalArgumentException("publishedItemId cant' be null");
}
return getHibernateTemplate().execute(session -> session.createCriteria(ItemGradingData.class)
.add(Restrictions.eq("assessmentGradingId", assesmentGradingId))
.add(Restrictions.eq("publishedItemId", publishedItemId))
.list());
}
public Map> getSiteSubmissionCountHash(final String siteId) {
Map> siteSubmissionCountHash = new HashMap<>();
final HibernateCallback> hcb = session -> session.createQuery(
"select a.publishedAssessmentId, a.agentId, count(*) " +
"from AssessmentGradingData a, AuthorizationData au " +
"where a.forGrade = :forgrade and au.functionId = :fid and au.agentIdString = :agent and a.publishedAssessmentId = au.qualifierId and a.status > :status " +
"group by a.publishedAssessmentId, a.agentId " +
"order by a.publishedAssessmentId, a.agentId ")
.setParameter("forgrade", true)
.setParameter("fid", "OWN_PUBLISHED_ASSESSMENT")
.setParameter("agent", siteId)
.setParameter("status", AssessmentGradingData.REMOVED)
.setCacheable(true)
.list();
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy