Java Code Examples for org.springframework.util.MultiValueMap#isEmpty()

The following examples show how to use org.springframework.util.MultiValueMap#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AnnotatedElementUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the annotation attributes of <strong>all</strong> annotations of
 * the specified {@code annotationName} in the annotation hierarchy above
 * the supplied {@link AnnotatedElement} and store the results in a
 * {@link MultiValueMap}.
 * <p>Note: in contrast to {@link #getMergedAnnotationAttributes(AnnotatedElement, String)},
 * this method does <em>not</em> support attribute overrides.
 * <p>This method follows <em>get semantics</em> as described in the
 * {@linkplain AnnotatedElementUtils class-level javadoc}.
 * @param element the annotated element
 * @param annotationName the fully qualified class name of the annotation type to find
 * @param classValuesAsString whether to convert Class references into Strings or to
 * preserve them as Class references
 * @param nestedAnnotationsAsMap whether to convert nested Annotation instances into
 * {@code AnnotationAttributes} maps or to preserve them as Annotation instances
 * @return a {@link MultiValueMap} keyed by attribute name, containing the annotation
 * attributes from all annotations found, or {@code null} if not found
 */
public static MultiValueMap<String, Object> getAllAnnotationAttributes(AnnotatedElement element,
		String annotationName, final boolean classValuesAsString, final boolean nestedAnnotationsAsMap) {

	final MultiValueMap<String, Object> attributesMap = new LinkedMultiValueMap<String, Object>();

	searchWithGetSemantics(element, null, annotationName, new SimpleAnnotationProcessor<Object>() {
		@Override
		public Object process(AnnotatedElement annotatedElement, Annotation annotation, int metaDepth) {
			AnnotationAttributes annotationAttributes = AnnotationUtils.getAnnotationAttributes(
					annotation, classValuesAsString, nestedAnnotationsAsMap);
			for (Map.Entry<String, Object> entry : annotationAttributes.entrySet()) {
				attributesMap.add(entry.getKey(), entry.getValue());
			}
			return CONTINUE;
		}
	});

	return (!attributesMap.isEmpty() ? attributesMap : null);
}
 
Example 2
Source File: PedagogicalPlannerController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping("/saveOrUpdatePedagogicalPlannerForm")
   public String saveOrUpdatePedagogicalPlannerForm(@ModelAttribute MindmapPedagogicalPlannerForm plannerForm,
    HttpServletRequest request, HttpServletResponse response) throws IOException {

MultiValueMap<String, String> errorMap = plannerForm.validate(messageService);
if (errorMap.isEmpty()) {
    String instructions = plannerForm.getInstructions();
    Long toolContentID = plannerForm.getToolContentID();
    Mindmap mindmap = mindmapService.getMindmapByContentId(toolContentID);
    mindmap.setInstructions(instructions);
    mindmapService.saveOrUpdateMindmap(mindmap);
} else {
    request.setAttribute("errorMap", errorMap);
}
return "pages/authoring/pedagogicalPlannerForm";
   }
 
Example 3
Source File: AdminController.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping(value = "/saveContent", method = RequestMethod.POST)
   public String saveContent(@ModelAttribute("scratchieAdminForm") AdminForm scratchieAdminForm,
    HttpServletRequest request) {

MultiValueMap<String, String> errorMap = validateAdminForm(scratchieAdminForm);
if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "pages/admin/config";
}

ScratchieConfigItem isEnabledExtraPointOption = scratchieService
	.getConfigItem(ScratchieConfigItem.KEY_IS_ENABLED_EXTRA_POINT_OPTION);
isEnabledExtraPointOption.setConfigValue("" + scratchieAdminForm.isEnabledExtraPointOption());
scratchieService.saveOrUpdateScratchieConfigItem(isEnabledExtraPointOption);

ScratchieConfigItem presetMarks = scratchieService.getConfigItem(ScratchieConfigItem.KEY_PRESET_MARKS);
presetMarks.setConfigValue(scratchieAdminForm.getPresetMarks());
scratchieService.saveOrUpdateScratchieConfigItem(presetMarks);

request.setAttribute("savedSuccess", true);
return "pages/admin/config";

   }
 
Example 4
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * This method will get necessary information from imageGallery item form and save or update into
    * <code>HttpSession</code> ImageGalleryItemList. Notice, this save is not persist them into database, just save
    * <code>HttpSession</code> temporarily. Only they will be persist when the entire authoring page is being
    * persisted.
    */
   @RequestMapping("/saveOrUpdateImage")
   public String saveOrUpdateImage(@ModelAttribute ImageGalleryItemForm imageGalleryItemForm,
    HttpServletRequest request, HttpServletResponse response) {

MultiValueMap<String, String> errorMap = ImageGalleryUtils.validateImageGalleryItem(imageGalleryItemForm, true,
	messageService);

try {
    if (errorMap.isEmpty()) {
	extractFormToImageGalleryItem(request, imageGalleryItemForm);
    }
} catch (Exception e) {
    // any upload exception will display as normal error message rather then throw exception directly
    errorMap.add("GLOBAL", messageService.getMessage(ImageGalleryConstants.ERROR_MSG_UPLOAD_FAILED,
	    new Object[] { e.getMessage() }));
}

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "pages/authoring/parts/addimage";
}

// set session map ID so that itemlist.jsp can get sessionMAP
request.setAttribute(ImageGalleryConstants.ATTR_SESSION_MAP_ID, imageGalleryItemForm.getSessionMapID());
// return null to close this window
return "pages/authoring/parts/itemlist";
   }
 
Example 5
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * This method will get necessary information from imageGallery item form and save or update into
    * <code>HttpSession</code> ImageGalleryItemList. Notice, this save is not persist them into database, just save
    * <code>HttpSession</code> temporarily. Only they will be persist when the entire authoring page is being
    * persisted.
    */
   @RequestMapping("/saveMultipleImages")
   public String saveMultipleImages(@ModelAttribute MultipleImagesForm multipleImagesForm, HttpServletRequest request,
    HttpServletResponse response) {

MultiValueMap<String, String> errorMap = ImageGalleryUtils.validateMultipleImages(multipleImagesForm, true,
	messageService);

try {
    if (errorMap.isEmpty()) {
	extractMultipleFormToImageGalleryItems(request, multipleImagesForm);
    }
} catch (Exception e) {
    // any upload exception will display as normal error message rather then throw exception directly
    errorMap.add("GLOBAL", messageService.getMessage(ImageGalleryConstants.ERROR_MSG_UPLOAD_FAILED,
	    new Object[] { e.getMessage() }));
}

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "pages/authoring/parts/addmultipleimages";
}

// set session map ID so that itemlist.jsp can get sessionMAP
request.setAttribute(ImageGalleryConstants.ATTR_SESSION_MAP_ID, multipleImagesForm.getSessionMapID());
// return null to close this window
return "pages/authoring/parts/itemlist";
   }
 
Example 6
Source File: MockServerHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
private URI getUrlToUse() {
	MultiValueMap<String, String> params =
			this.queryParamsBuilder.buildAndExpand().encode().getQueryParams();

	if (!params.isEmpty()) {
		return UriComponentsBuilder.fromUri(this.url).queryParams(params).build(true).toUri();
	}

	return this.url;
}
 
Example 7
Source File: MongoConnectionRepositoryImpl.java    From JiwhizBlogWeb with Apache License 2.0 5 votes vote down vote up
public MultiValueMap<String, Connection<?>> findConnectionsToUsers(MultiValueMap<String, String> providerUsers) {
    if (providerUsers == null || providerUsers.isEmpty()) {
        throw new IllegalArgumentException("Unable to execute find: no providerUsers provided");
    }

    MultiValueMap<String, Connection<?>> connectionsForUsers = new LinkedMultiValueMap<String, Connection<?>>();
    
    for (Iterator<Entry<String, List<String>>> it = providerUsers.entrySet().iterator(); it.hasNext();) {
        Entry<String, List<String>> entry = it.next();
        String providerId = entry.getKey();
        List<String> providerUserIds = entry.getValue();
        List<UserSocialConnection> userSocialConnections = 
                this.userSocialConnectionRepository.findByProviderIdAndProviderUserIdIn(providerId, providerUserIds);
        List<Connection<?>> connections = new ArrayList<Connection<?>>(providerUserIds.size());
        for (int i = 0; i < providerUserIds.size(); i++) {
            connections.add(null);
        }
        connectionsForUsers.put(providerId, connections);

        for (UserSocialConnection userSocialConnection : userSocialConnections) {
            String providerUserId = userSocialConnection.getProviderUserId();
            int connectionIndex = providerUserIds.indexOf(providerUserId);
            connections.set(connectionIndex, buildConnection(userSocialConnection));
        }

    }
    return connectionsForUsers;
}
 
Example 8
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * This method will get necessary information from commonCartridge item form and save or update into
    * <code>HttpSession</code> CommonCartridgeItemList. Notice, this save is not persist them into database, just save
    * <code>HttpSession</code> temporarily. Only they will be persist when the entire authoring page is being
    * persisted.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   @RequestMapping(path = "/saveOrUpdateItem", method = RequestMethod.POST)
   private String saveOrUpdateItem(
    @ModelAttribute("commonCartridgeItemForm") CommonCartridgeItemForm commonCartridgeItemForm,
    HttpServletRequest request) {
MultiValueMap<String, String> errorMap = validateCommonCartridgeItem(commonCartridgeItemForm);

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return findForward(commonCartridgeItemForm.getItemType());
}

short type = commonCartridgeItemForm.getItemType();
try {
    if (type == CommonCartridgeConstants.RESOURCE_TYPE_COMMON_CARTRIDGE) {
	uploadCommonCartridge(request, commonCartridgeItemForm);
    } else {
	extractFormToCommonCartridgeItem(request, commonCartridgeItemForm);
    }
} catch (Exception e) {
    // any upload exception will display as normal error message rather then throw exception directly
    errorMap.add("GLOBAL", messageService.getMessage(CommonCartridgeConstants.ERROR_MSG_UPLOAD_FAILED,
	    new Object[] { e.getMessage() }));
    if (!errorMap.isEmpty()) {
	request.setAttribute("errorMap", errorMap);
	return findForward(commonCartridgeItemForm.getItemType());
    }
}
// set session map ID so that itemlist.jsp can get sessionMAP
request.setAttribute(CommonCartridgeConstants.ATTR_SESSION_MAP_ID, commonCartridgeItemForm.getSessionMapID());
// return null to close this window

if (type == CommonCartridgeConstants.RESOURCE_TYPE_COMMON_CARTRIDGE) {
    return "pages/authoring/parts/selectResources";
} else {
    return "pages/authoring/parts/itemlist";
}
   }
 
Example 9
Source File: LearningController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Finish learning session.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   @RequestMapping("/finish")
   protected String finish(@ModelAttribute("recordForm") RecordForm recordForm, HttpServletRequest request) {

// get back SessionMap
String sessionMapID = request.getParameter(DacoConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap) request.getSession().getAttribute(sessionMapID);

// get mode and ToolSessionID from sessionMAP
ToolAccessMode mode = (ToolAccessMode) sessionMap.get(AttributeNames.ATTR_MODE);
Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);

MultiValueMap<String, String> errorMap = validateBeforeFinish(request, sessionMapID);
if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    request.setAttribute(DacoConstants.ATTR_DISPLAYED_RECORD_NUMBER,
	    request.getParameter(DacoConstants.ATTR_DISPLAYED_RECORD_NUMBER));
    return "pages/learning/learning";
}

// get sessionId from HttpServletRequest
String nextActivityUrl = null;
try {
    HttpSession httpSession = SessionManager.getSession();
    UserDTO user = (UserDTO) httpSession.getAttribute(AttributeNames.USER);
    Long userUid = new Long(user.getUserID().longValue());

    nextActivityUrl = dacoService.finishToolSession(sessionId, userUid);
    request.setAttribute(DacoConstants.ATTR_NEXT_ACTIVITY_URL, nextActivityUrl);
} catch (DacoApplicationException e) {

    LearningController.log.error("Failed get next activity url:" + e.getMessage());
}

return "pages/learning/finish";
   }
 
Example 10
Source File: LearningController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Create a replayed topic for a parent topic.
    */
   @RequestMapping("/replyTopic")
   public String replyTopic(@ModelAttribute MessageForm messageForm, HttpServletRequest request,
    HttpServletResponse response) throws InterruptedException, IOException {
//validate form
MultiValueMap<String, String> errorMap = messageForm.validate(request, messageService);
if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "jsps/learning/reply";
}

return "forward:/learning/replyTopicJSON.do";
   }
 
Example 11
Source File: LearningController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping(value = "/previousQuestion")
   private String previousQuestion(@ModelAttribute("surveyForm") AnswerForm surveyForm,
    MultiValueMap<String, String> errorMap, HttpServletRequest request) {
Integer questionSeqID = surveyForm.getQuestionSeqID();
String sessionMapID = surveyForm.getSessionMapID();

SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
SortedMap<Integer, AnswerDTO> surveyItemMap = getQuestionList(sessionMap);

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "pages/learning/learning";
}

SortedMap<Integer, AnswerDTO> subMap = surveyItemMap.headMap(questionSeqID);
if (subMap.isEmpty()) {
    questionSeqID = surveyItemMap.firstKey();
} else {
    questionSeqID = subMap.lastKey();
}

// get current question index of total questions
int currIdx = new ArrayList<>(surveyItemMap.keySet()).indexOf(questionSeqID) + 1;
surveyForm.setCurrentIdx(currIdx);

if (questionSeqID.equals(surveyItemMap.firstKey())) {
    surveyForm.setPosition(SurveyConstants.POSITION_FIRST);
} else {
    surveyForm.setPosition(SurveyConstants.POSITION_INSIDE);
}
surveyForm.setQuestionSeqID(questionSeqID);
request.setAttribute("surveyForm", surveyForm);
return "pages/learning/learning";
   }
 
Example 12
Source File: MockServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private URI getUrlToUse() {
	MultiValueMap<String, String> params =
			this.queryParamsBuilder.buildAndExpand().encode().getQueryParams();

	if (!params.isEmpty()) {
		return UriComponentsBuilder.fromUri(this.url).queryParams(params).build(true).toUri();
	}

	return this.url;
}
 
Example 13
Source File: PathPattern.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public void set(String key, String value, MultiValueMap<String,String> parameters) {
	if (this.extractedUriVariables == null) {
		this.extractedUriVariables = new HashMap<>();
	}
	this.extractedUriVariables.put(key, value);

	if (!parameters.isEmpty()) {
		if (this.extractedMatrixVariables == null) {
			this.extractedMatrixVariables = new HashMap<>();
		}
		this.extractedMatrixVariables.put(key, CollectionUtils.unmodifiableMultiValueMap(parameters));
	}
}
 
Example 14
Source File: LearningController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Save file or url resource item into database.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   @RequestMapping(value = "/saveOrUpdateItem", method = RequestMethod.POST)
   private String saveOrUpdateItem(ResourceItemForm resourceItemForm, HttpServletRequest request) {
// get back SessionMap
String sessionMapID = request.getParameter(ResourceConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
request.setAttribute(ResourceConstants.ATTR_SESSION_MAP_ID, sessionMapID);

Long sessionId = (Long) sessionMap.get(ResourceConstants.ATTR_TOOL_SESSION_ID);

String mode = request.getParameter(AttributeNames.ATTR_MODE);
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();
validateResourceItem(resourceItemForm, errorMap);

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    switch (resourceItemForm.getItemType()) {
	case 1:
	    return "pages/authoring/parts/addurl";
	case 2:
	    return "pages/authoring/parts/addfile";
	default:
	    throw new IllegalArgumentException("Unknown item type" + resourceItemForm.getItemType());
    }
}
short type = resourceItemForm.getItemType();

// create a new ResourceItem
ResourceItem item = new ResourceItem();
ResourceUser resourceUser = getCurrentUser(resourceService, sessionId);
item.setType(type);
item.setTitle(resourceItemForm.getTitle());
item.setDescription(resourceItemForm.getDescription());
item.setCreateDate(new Timestamp(new Date().getTime()));
item.setCreateByAuthor(false);
item.setCreateBy(resourceUser);

// special attribute for URL or FILE
if (type == ResourceConstants.RESOURCE_TYPE_FILE) {
    try {
	resourceService.uploadResourceItemFile(item, resourceItemForm.getFile());
    } catch (UploadResourceFileException e) {
	LearningController.log.error("Failed upload Resource File " + e.toString());
	return "error";
    }
    item.setOpenUrlNewWindow(resourceItemForm.isOpenUrlNewWindow());

} else if (type == ResourceConstants.RESOURCE_TYPE_URL) {
    item.setUrl(resourceItemForm.getUrl());
    item.setOpenUrlNewWindow(resourceItemForm.isOpenUrlNewWindow());
}
// save and update session

ResourceSession resSession = resourceService.getResourceSessionBySessionId(sessionId);
if (resSession == null) {
    LearningController.log.error("Failed update ResourceSession by ID[" + sessionId + "]");
    return "error";
}
Set<ResourceItem> items = resSession.getResourceItems();
if (items == null) {
    items = new HashSet<>();
    resSession.setResourceItems(items);
}
items.add(item);
resourceService.saveOrUpdateResourceSession(resSession);

// update session value
SortedSet<ResourceItem> resourceItemList = getResourceItemList(sessionMap);
resourceItemList.add(item);

// URL or file upload
request.setAttribute(ResourceConstants.ATTR_ADD_RESOURCE_TYPE, new Short(type));
request.setAttribute(AttributeNames.ATTR_MODE, mode);

Resource resource = resSession.getResource();
if (resource.isNotifyTeachersOnAssigmentSumbit()) {
    resourceService.notifyTeachersOnAssigmentSumbit(sessionId, resourceUser);
}

if (resource.isNotifyTeachersOnFileUpload() && (type == ResourceConstants.RESOURCE_TYPE_FILE)) {
    resourceService.notifyTeachersOnFileUpload(resource.getContentId(), sessionId, sessionMapID,
	    resourceUser.getFirstName() + " " + resourceUser.getLastName(), item.getUid(),
	    resourceItemForm.getFile().getOriginalFilename());
}

return "pages/learning/success";
   }
 
Example 15
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@RequestMapping(path = "/updateContent", method = RequestMethod.POST)
   public String updateContent(@ModelAttribute("authoringForm") AuthoringForm authoringForm,
    HttpServletRequest request) throws PixlrException {
// TODO need error checking.

// get authForm and session map.
SessionMap<String, Object> map = getSessionMap(request, authoringForm);
ToolAccessMode mode = (ToolAccessMode) map.get(AuthoringController.KEY_MODE);

// get pixlr content.
Pixlr pixlr = pixlrService.getPixlrByContentId((Long) map.get(AuthoringController.KEY_TOOL_CONTENT_ID));
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();

try {
    // TODO: Need to check if this is an edit, if so, delete the old image
    if (authoringForm.getExistingImageFileName().equals(PixlrConstants.DEFAULT_IMAGE_FILE_NAME)
	    || authoringForm.getExistingImageFileName().trim().equals("")) {
	errorMap = validateImageFile(authoringForm);

	if (!errorMap.isEmpty()) {
	    request.setAttribute("errorMap", errorMap);
	    updateAuthForm(authoringForm, pixlr);
	    if (mode != null) {
		authoringForm.setMode(mode.toString());
	    } else {
		authoringForm.setMode("");
	    }
	    return "pages/authoring/authoring";
	}
	uploadFormImage(authoringForm, pixlr);
    }
} catch (Exception e) {
    logger.error("Problem uploading image", e);
    errorMap.add("GLOBAL", messageService.getMessage(PixlrConstants.ERROR_MSG_FILE_UPLOAD));
    //throw new PixlrException("Problem uploading image", e);
}

// update pixlr content using form inputs.
updatePixlr(pixlr, authoringForm);

// set the update date
pixlr.setUpdateDate(new Date());

// releasing defineLater flag so that learner can start using the tool.
pixlr.setDefineLater(false);

pixlrService.saveOrUpdatePixlr(pixlr);

request.setAttribute(CommonConstants.LAMS_AUTHORING_SUCCESS_FLAG, Boolean.TRUE);

// add the sessionMapID to form
authoringForm.setSessionMapID(map.getSessionID());

request.setAttribute(PixlrConstants.ATTR_SESSION_MAP, map);

updateAuthForm(authoringForm, pixlr);
if (mode != null) {
    authoringForm.setMode(mode.toString());
} else {
    authoringForm.setMode("");
}

return "pages/authoring/authoring";
   }
 
Example 16
Source File: MonitoringController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@RequestMapping(path = "/saveMark", method = RequestMethod.POST)
   public String saveMark(@ModelAttribute MarkForm markForm, HttpServletRequest request,
    HttpServletResponse response) {

Float markFloat = null;
String markComment = null;

// get the mark details, validating as we go.
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();
String markStr = markForm.getMarks();
if (StringUtils.isBlank(markStr)) {
    errorMap.add("GLOBAL", messageService.getMessage("error.summary.marks.blank"));
} else {
    try {
	markFloat = NumberUtil.getLocalisedFloat(markStr, request.getLocale());
    } catch (Exception e) {
	errorMap.add("GLOBAL", messageService.getMessage("error.summary.marks.invalid.number"));
    }
}

markComment = markForm.getComments();
if (StringUtils.isBlank(markComment)) {
    errorMap.add("GLOBAL", messageService.getMessage("error.summary.comments.blank"));
}

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    return "pages/monitoring/parts/editmark";
}

// passed validation so proceed to save
Long userUid = markForm.getUserUid();
SpreadsheetUser user = service.getUser(userUid);
if (user != null && user.getUserModifiedSpreadsheet() != null) {
    //check whether it is "edit(old item)" or "add(new item)"
    SpreadsheetMark mark;
    if (user.getUserModifiedSpreadsheet().getMark() == null) { //new mark
	mark = new SpreadsheetMark();
	user.getUserModifiedSpreadsheet().setMark(mark);
    } else { //edit
	mark = user.getUserModifiedSpreadsheet().getMark();
    }

    mark.setMarks(markFloat);
    mark.setComments(markComment);

    service.saveOrUpdateUserModifiedSpreadsheet(user.getUserModifiedSpreadsheet());
}

request.setAttribute("mark", NumberUtil.formatLocalisedNumber(markFloat, request.getLocale(),
	SpreadsheetConstants.MARK_NUM_DEC_PLACES)); // reduce it to the standard number of decimal places for redisplay
request.setAttribute("userUid", userUid);

//set session map ID so that itemlist.jsp can get sessionMAP
request.setAttribute(SpreadsheetConstants.ATTR_SESSION_MAP_ID, markForm.getSessionMapID());

return "pages/monitoring/parts/updatemarkaftersave";
   }
 
Example 17
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@RequestMapping(path = "/saveOrUpdatePedagogicalPlannerForm", method = RequestMethod.POST)
   public String saveOrUpdatePedagogicalPlannerForm(
    @ModelAttribute("pedagogicalPlannerForm") CommonCartridgePedagogicalPlannerForm pedagogicalPlannerForm,
    HttpServletRequest request) throws IOException {
MultiValueMap<String, String> errorMap = pedagogicalPlannerForm.validate();
if (errorMap.isEmpty()) {
    CommonCartridge taskList = commonCartridgeService
	    .getCommonCartridgeByContentId(pedagogicalPlannerForm.getToolContentID());
    taskList.setInstructions(pedagogicalPlannerForm.getInstructions());

    int itemIndex = 0;
    String title = null;
    CommonCartridgeItem commonCartridgeItem = null;
    List<CommonCartridgeItem> newItems = new LinkedList<>();
    Set<CommonCartridgeItem> commonCartridgeItems = taskList.getCommonCartridgeItems();
    Iterator<CommonCartridgeItem> taskListItemIterator = commonCartridgeItems.iterator();
    // We need to reverse the order, since the items are delivered newest-first
    LinkedList<CommonCartridgeItem> reversedCommonCartridgeItems = new LinkedList<>();
    while (taskListItemIterator.hasNext()) {
	reversedCommonCartridgeItems.addFirst(taskListItemIterator.next());
    }
    taskListItemIterator = reversedCommonCartridgeItems.iterator();
    do {
	title = pedagogicalPlannerForm.getTitle(itemIndex);
	if (StringUtils.isEmpty(title)) {
	    pedagogicalPlannerForm.removeItem(itemIndex);
	} else {
	    if (taskListItemIterator.hasNext()) {
		commonCartridgeItem = taskListItemIterator.next();
	    } else {
		commonCartridgeItem = new CommonCartridgeItem();
		commonCartridgeItem.setCreateByAuthor(true);
		Date currentDate = new Date();
		commonCartridgeItem.setCreateDate(currentDate);

		HttpSession session = SessionManager.getSession();
		UserDTO user = (UserDTO) session.getAttribute(AttributeNames.USER);
		CommonCartridgeUser taskListUser = commonCartridgeService.getUserByIDAndContent(
			new Long(user.getUserID().intValue()), pedagogicalPlannerForm.getToolContentID());
		commonCartridgeItem.setCreateBy(taskListUser);

		newItems.add(commonCartridgeItem);
	    }
	    commonCartridgeItem.setTitle(title);
	    Short type = pedagogicalPlannerForm.getType(itemIndex);
	    commonCartridgeItem.setType(type);
	    boolean hasFile = commonCartridgeItem.getFileUuid() != null;
	    if (type.equals(CommonCartridgeConstants.RESOURCE_TYPE_BASIC_LTI)) {
		commonCartridgeItem.setUrl(pedagogicalPlannerForm.getUrl(itemIndex));
		if (hasFile) {
		    commonCartridgeItem.setFileName(null);
		    commonCartridgeItem.setFileUuid(null);
		    commonCartridgeItem.setFileVersionId(null);
		    commonCartridgeItem.setFileType(null);
		}
	    } else if (type.equals(CommonCartridgeConstants.RESOURCE_TYPE_COMMON_CARTRIDGE)) {
		MultipartFile file = pedagogicalPlannerForm.getFile(itemIndex);
		commonCartridgeItem.setUrl(null);
		if (file != null) {
		    try {
			if (hasFile) {
			    // delete the old file
			    commonCartridgeService.deleteFromRepository(commonCartridgeItem.getFileUuid(),
				    commonCartridgeItem.getFileVersionId());
			}
			commonCartridgeService.uploadCommonCartridgeFile(commonCartridgeItem, file);
		    } catch (Exception e) {
			AuthoringController.log.error(e);
			errorMap.add("GLOBAL", messageService.getMessage("error.msg.io.exception"));
			request.setAttribute("erroeMap", errorMap);
			pedagogicalPlannerForm.setValid(false);
			return "pages/authoring/pedagogicalPlannerForm";
		    }
		}
		pedagogicalPlannerForm.setFileName(itemIndex, commonCartridgeItem.getFileName());
		pedagogicalPlannerForm.setFileUuid(itemIndex, commonCartridgeItem.getFileUuid());
		pedagogicalPlannerForm.setFileVersion(itemIndex, commonCartridgeItem.getFileVersionId());
		pedagogicalPlannerForm.setFile(itemIndex, null);
	    }
	    itemIndex++;
	}

    } while (title != null);
    // we need to clear it now, otherwise we get Hibernate error (item re-saved by cascade)
    taskList.getCommonCartridgeItems().clear();
    while (taskListItemIterator.hasNext()) {
	commonCartridgeItem = taskListItemIterator.next();
	taskListItemIterator.remove();
	commonCartridgeService.deleteCommonCartridgeItem(commonCartridgeItem.getUid());
    }
    reversedCommonCartridgeItems.addAll(newItems);

    taskList.getCommonCartridgeItems().addAll(reversedCommonCartridgeItems);
    commonCartridgeService.saveOrUpdateCommonCartridge(taskList);
} else {
    request.setAttribute("eerorMap", errorMap);
}
return "pages/authoring/pedagogicalPlannerForm";
   }
 
Example 18
Source File: LessonConditionsController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Sets lesson finish date, either for individuals or lesson as a whole. If days<=0, schedule is removed.
    *
    * @throws IOException
    */
   @RequestMapping(path = "/setDaysToLessonFinish", method = RequestMethod.POST)
   public String setDaysToLessonFinish(HttpServletRequest request, HttpServletResponse response) throws IOException {
Long lessonId = WebUtil.readLongParam(request, CentralConstants.PARAM_LESSON_ID, false);
if (!securityService.isLessonOwner(lessonId, getUser().getUserID(), "set days to lesson finish", false)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User is not the owner of the lesson");
    return null;
}

int daysToLessonFinish = WebUtil.readIntParam(request, LessonConditionsController.PARAM_LESSON_DAYS_TO_FINISH,
	false);
boolean individualFinish = WebUtil.readBooleanParam(request, LessonConditionsController.PARAM_INDIVIDUAL_FINISH,
	false);
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();

Lesson lesson = lessonService.getLesson(lessonId);
HttpSession session = SessionManager.getSession();
UserDTO currentUser = (UserDTO) session.getAttribute(AttributeNames.USER);
try {
    // (re)schedule the lesson or remove it when set for individual finish of daysToLessonFinish=0
    monitoringService.finishLessonOnSchedule(lessonId, individualFinish ? 0 : daysToLessonFinish,
	    currentUser.getUserID());
    // if finish date is individual, the field below is filled
    lesson.setScheduledNumberDaysToLessonFinish(
	    individualFinish && (daysToLessonFinish > 0) ? daysToLessonFinish : null);

    // iterate through each GroupLearner and set/remove individual lesson finish date, if needed
    Group learnerGroup = lesson.getLessonClass().getLearnersGroup();
    if (learnerGroup != null) {
	for (User learner : learnerGroup.getUsers()) {
	    GroupUser groupUser = groupUserDAO.getGroupUser(lesson, learner.getUserId());
	    if (groupUser != null) {

		if (individualFinish && (daysToLessonFinish > 0)) {
		    // set individual finish date based on start date
		    LearnerProgress learnerProgress = lessonService
			    .getUserProgressForLesson(learner.getUserId(), lessonId);
		    if ((learnerProgress == null) || (learnerProgress.getStartDate() == null)) {
			if (groupUser.getScheduledLessonEndDate() != null) {
			    LessonConditionsController.logger.warn("Improper DB value: User with ID "
				    + learner.getUserId()
				    + " has scheduledLessonEndDate set but has not started the lesson yet.");
			}
		    } else {
			// set new finish date according to moment when user joined the lesson
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(learnerProgress.getStartDate());
			calendar.add(Calendar.DATE, daysToLessonFinish);
			Date endDate = calendar.getTime();
			groupUser.setScheduledLessonEndDate(endDate);

			if (LessonConditionsController.logger.isDebugEnabled()) {
			    LessonConditionsController.logger
				    .debug("Reset time limit for user: " + learner.getLogin() + " in lesson: "
					    + lesson.getLessonId() + " to " + endDate);
			}
		    }
		} else if (groupUser.getScheduledLessonEndDate() != null) {
		    // remove individual finish date
		    groupUser.setScheduledLessonEndDate(null);

		    if (LessonConditionsController.logger.isDebugEnabled()) {
			LessonConditionsController.logger.debug("Remove time limit for user: "
				+ learner.getLogin() + " in lesson: " + lesson.getLessonId());
		    }
		}
	    }
	}
    }
} catch (Exception e) {
    LessonConditionsController.logger.error(e);
    errorMap.add("GLOBAL",
	    messageService.getMessage("error.conditions.box.finish.date", new Object[] { e.getMessage() }));
}

if (!errorMap.isEmpty()) {
    request.setAttribute("errorMap", errorMap);
    ;
}

// after operation, display contents again
return getIndexLessonConditions(request, response);
   }
 
Example 19
Source File: LearningController.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
    * Get the answer from the form and copy into DTO. Set up the next question. If the current question is required and
    * the answer is blank, then just persist the error and don't change questions.
    */
   private Object[] storeSequentialAnswer(QaLearningForm qaLearningForm, HttpServletRequest request,
    GeneralLearnerFlowDTO generalLearnerFlowDTO, boolean getNextQuestion) {
String httpSessionID = qaLearningForm.getHttpSessionID();
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(httpSessionID);

String currentQuestionIndex = qaLearningForm.getCurrentQuestionIndex();

Map<String, String> mapAnswers = (Map<String, String>) sessionMap.get(QaAppConstants.MAP_ALL_RESULTS_KEY);
if (mapAnswers == null) {
    mapAnswers = new TreeMap<String, String>(new QaComparator());
}

String newAnswer = qaLearningForm.getAnswer();
Map<String, String> mapSequentialAnswers = (Map<String, String>) sessionMap
	.get(QaAppConstants.MAP_SEQUENTIAL_ANSWERS_KEY);
if (mapSequentialAnswers.size() >= new Integer(currentQuestionIndex).intValue()) {
    mapSequentialAnswers.remove(new Long(currentQuestionIndex).toString());
}
mapSequentialAnswers.put(new Long(currentQuestionIndex).toString(), newAnswer);
mapAnswers.put(currentQuestionIndex, newAnswer);

int nextQuestionOffset = getNextQuestion ? 1 : -1;

// validation only if trying to go to the next question
MultiValueMap<String, String> errorMap = new LinkedMultiValueMap<>();
if (getNextQuestion) {
    errorMap = validateQuestionAnswer(newAnswer, new Integer(currentQuestionIndex), generalLearnerFlowDTO);
}

// store
if (errorMap.isEmpty()) {
    qaService.updateResponseWithNewAnswer(newAnswer, qaLearningForm.getToolSessionID(),
	    new Integer(currentQuestionIndex), false);
} else {
    request.setAttribute("errorMap", errorMap);
    nextQuestionOffset = 0;
}

int intCurrentQuestionIndex = new Integer(currentQuestionIndex).intValue() + nextQuestionOffset;
String currentAnswer = "";
if (mapAnswers.size() >= intCurrentQuestionIndex) {
    currentAnswer = mapAnswers.get(new Long(intCurrentQuestionIndex).toString());
}
generalLearnerFlowDTO.setCurrentAnswer(currentAnswer);

// currentQuestionIndex will be:
generalLearnerFlowDTO.setCurrentQuestionIndex(new Integer(intCurrentQuestionIndex));

String totalQuestionCount = qaLearningForm.getTotalQuestionCount();

int remainingQuestionCount = new Long(totalQuestionCount).intValue()
	- new Integer(currentQuestionIndex).intValue();
String userFeedback = "";
if (remainingQuestionCount != 0) {
    userFeedback = "Remaining question count: " + remainingQuestionCount;
} else {
    userFeedback = "End of the questions.";
}
generalLearnerFlowDTO.setUserFeedback(userFeedback);
generalLearnerFlowDTO.setRemainingQuestionCount("" + remainingQuestionCount);

qaLearningForm.resetUserActions(); /* resets all except submitAnswersContent */

sessionMap.put(QaAppConstants.MAP_ALL_RESULTS_KEY, mapAnswers);
sessionMap.put(QaAppConstants.MAP_SEQUENTIAL_ANSWERS_KEY, mapSequentialAnswers);
request.getSession().setAttribute(sessionMap.getSessionID(), sessionMap);
qaLearningForm.setHttpSessionID(sessionMap.getSessionID());
generalLearnerFlowDTO.setHttpSessionID(sessionMap.getSessionID());

request.setAttribute(QaAppConstants.GENERAL_LEARNER_FLOW_DTO, generalLearnerFlowDTO);

return new Object[] { mapSequentialAnswers, errorMap };
   }
 
Example 20
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 4 votes vote down vote up
/**
 * Add cookies to the request that is being built
 * @param cookies The cookies to add
 * @param requestBuilder The current request
 */
protected void addCookiesToRequest(MultiValueMap<String, String> cookies, BodyBuilder requestBuilder) {
    if (!cookies.isEmpty()) {
        requestBuilder.header("Cookie", buildCookieHeader(cookies));
    }
}