Java Code Examples for com.fasterxml.jackson.databind.node.ObjectNode#toString()
The following examples show how to use
com.fasterxml.jackson.databind.node.ObjectNode#toString() .
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: PinotTableRestletResource.java From incubator-pinot with Apache License 2.0 | 6 votes |
@POST
@Path("/tables/validate")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Validate table config for a table", notes =
"This API returns the table config that matches the one you get from 'GET /tables/{tableName}'."
+ " This allows us to validate table config before apply.")
public String checkTableConfig(String tableConfigStr) {
try {
TableConfig tableConfig = JsonUtils.stringToObject(tableConfigStr, TableConfig.class);
TableConfigUtils.validate(tableConfig);
ObjectNode tableConfigValidateStr = JsonUtils.newObjectNode();
if (tableConfig.getTableType() == TableType.OFFLINE) {
tableConfigValidateStr.set(TableType.OFFLINE.name(), tableConfig.toJsonNode());
} else {
tableConfigValidateStr.set(TableType.REALTIME.name(), tableConfig.toJsonNode());
}
return tableConfigValidateStr.toString();
} catch (Exception e) {
throw new ControllerApplicationException(LOGGER, "Invalid table config", Response.Status.BAD_REQUEST, e);
}
}
Example 2
Source File: NotificationSubjectArgumentResolverTest.java From spring-cloud-aws with Apache License 2.0 | 6 votes |
@Test
void resolveArgument_withValidRequestPayload_shouldReturnNotificationSubject()
throws Exception {
// Arrange
NotificationSubjectArgumentResolver notificationSubjectArgumentResolver = new NotificationSubjectArgumentResolver();
Method methodWithNotificationSubjectArgument = this.getClass()
.getDeclaredMethod("methodWithNotificationSubjectArgument", String.class);
MethodParameter methodParameter = new MethodParameter(
methodWithNotificationSubjectArgument, 0);
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
jsonObject.put("Type", "Notification");
jsonObject.put("Subject", "My subject!");
jsonObject.put("Message", "message");
String payload = jsonObject.toString();
Message<String> message = MessageBuilder.withPayload(payload).build();
// Act
Object result = notificationSubjectArgumentResolver
.resolveArgument(methodParameter, message);
// Assert
assertThat(String.class.isInstance(result)).isTrue();
assertThat(result).isEqualTo("My subject!");
}
Example 3
Source File: InitializrMetadataV2JsonMapper.java From initializr with Apache License 2.0 | 6 votes |
@Override
public String write(InitializrMetadata metadata, String appUrl) {
ObjectNode delegate = nodeFactory.objectNode();
links(delegate, metadata.getTypes().getContent(), appUrl);
dependencies(delegate, metadata.getDependencies());
type(delegate, metadata.getTypes());
singleSelect(delegate, metadata.getPackagings());
singleSelect(delegate, metadata.getJavaVersions());
singleSelect(delegate, metadata.getLanguages());
singleSelect(delegate, metadata.getBootVersions(), this::mapVersionMetadata);
text(delegate, metadata.getGroupId());
text(delegate, metadata.getArtifactId());
text(delegate, metadata.getVersion());
text(delegate, metadata.getName());
text(delegate, metadata.getDescription());
text(delegate, metadata.getPackageName());
return delegate.toString();
}
Example 4
Source File: AppDefinitionExportService.java From flowable-engine with Apache License 2.0 | 6 votes |
protected String createModelEntryJson(Model model) {
ObjectNode modelJson = objectMapper.createObjectNode();
modelJson.put("id", model.getId());
modelJson.put("name", model.getName());
modelJson.put("key", model.getKey());
modelJson.put("description", model.getDescription());
try {
modelJson.set("editorJson", objectMapper.readTree(model.getModelEditorJson()));
} catch (Exception e) {
LOGGER.error("Error exporting model json for id {}", model.getId(), e);
throw new InternalServerErrorException("Error exporting model json for id " + model.getId());
}
return modelJson.toString();
}
Example 5
Source File: GradeUpdateAction.java From sakai with Educational Community License v2.0 | 6 votes |
public String toJson() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode result = mapper.createObjectNode();
ArrayNode courseGradeArray = mapper.createArrayNode();
for (String data : courseGradeData) {
courseGradeArray.add(data);
}
result.put("courseGrade", courseGradeArray);
result.put("categoryScore", categoryScore);
result.put("extraCredit", extraCredit);
ArrayNode catDroppedItemsArray = mapper.createArrayNode();
droppedItems.stream().forEach(i -> catDroppedItemsArray.add(i));
result.put("categoryDroppedItems", catDroppedItemsArray);
return result.toString();
}
Example 6
Source File: CommentController.java From lams with GNU General Public License v2.0 | 6 votes |
/**
* Update the likes/dislikes
*/
private String updateLikeCount(HttpServletRequest request, HttpServletResponse response, boolean isLike)
throws InterruptedException, IOException, ServletException {
SessionMap<String, Object> sessionMap = getSessionMap(request);
Long messageUid = WebUtil.readLongParam(request, CommentConstants.ATTR_COMMENT_ID);
Long externalId = (Long) sessionMap.get(CommentConstants.ATTR_EXTERNAL_ID);
User user = getCurrentUser(request);
if (!learnerInToolSession(externalId, user)) {
throwException(
"Update comment: User does not have the rights to like/dislike the comment " + messageUid + ". ",
user.getLogin(), externalId, (Integer) sessionMap.get(CommentConstants.ATTR_EXTERNAL_TYPE),
(String) sessionMap.get(CommentConstants.ATTR_EXTERNAL_SIG));
}
boolean added = commentService.addLike(messageUid, user, isLike ? CommentLike.LIKE : CommentLike.DISLIKE);
ObjectNode responseJSON = JsonNodeFactory.instance.objectNode();
responseJSON.put(CommentConstants.ATTR_COMMENT_ID, messageUid);
responseJSON.put(CommentConstants.ATTR_STATUS, added);
response.setContentType("application/json;charset=utf-8");
return responseJSON.toString();
}
Example 7
Source File: MonitoringController.java From lams with GNU General Public License v2.0 | 5 votes |
/**
* Get Paged Reflections
*
* @param request
* @return
*/
@RequestMapping(path = "/getReflectionsJSON")
@ResponseBody
public String getReflectionsJSON(HttpServletRequest request, HttpServletResponse response ) throws IOException, ServletException, ToolException {
Long toolSessionId = WebUtil.readLongParam(request, QaAppConstants.TOOL_SESSION_ID);
// paging parameters of tablesorter
int size = WebUtil.readIntParam(request, "size");
int page = WebUtil.readIntParam(request, "page");
Integer sortByName = WebUtil.readIntParam(request, "column[0]", true);
String searchString = request.getParameter("fcol[0]");
int sorting = QaAppConstants.SORT_BY_NO;
if (sortByName != null) {
sorting = sortByName.equals(0) ? QaAppConstants.SORT_BY_USERNAME_ASC : QaAppConstants.SORT_BY_USERNAME_DESC;
}
//return user list according to the given sessionID
List<Object[]> users = qaService.getUserReflectionsForTablesorter(toolSessionId, page, size, sorting,
searchString);
ArrayNode rows = JsonNodeFactory.instance.arrayNode();
ObjectNode responsedata = JsonNodeFactory.instance.objectNode();
responsedata.put("total_rows", qaService.getCountUsersBySessionWithSearch(toolSessionId, searchString));
for (Object[] userAndReflection : users) {
ObjectNode responseRow = JsonNodeFactory.instance.objectNode();
responseRow.put("username", HtmlUtils.htmlEscape((String) userAndReflection[1]));
if (userAndReflection.length > 2 && userAndReflection[2] != null) {
String reflection = HtmlUtils.htmlEscape((String) userAndReflection[2]);
responseRow.put(QaAppConstants.NOTEBOOK, reflection.replaceAll("\n", "<br>"));
}
rows.add(responseRow);
}
responsedata.set("rows", rows);
response.setContentType("application/json;charset=UTF-8");
return responsedata.toString();
}
Example 8
Source File: AltNamesConverter.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
@Override
public String jsonToTinkerpop(JsonNode json) throws IOException {
//convert to personNames as verification
//make the same as the database value
ObjectNode dbJson = jsnO("list", json);
// verify json is an AltNames json
objectMapper.treeToValue(dbJson, AltNames.class);
//if this doesn't throw then it was a good personName apparently
return dbJson.toString();
}
Example 9
Source File: PinotTenantRestletResource.java From incubator-pinot with Apache License 2.0 | 5 votes |
private String getTablesServedFromTenant(String tenantName) {
Set<String> tables = new HashSet<>();
ObjectNode resourceGetRet = JsonUtils.newObjectNode();
for (String table : pinotHelixResourceManager.getAllTables()) {
TableConfig tableConfig = pinotHelixResourceManager.getTableConfig(table);
String tableConfigTenant = tableConfig.getTenantConfig().getServer();
if (tenantName.equals(tableConfigTenant)) {
tables.add(table);
}
}
resourceGetRet.set(TABLES, JsonUtils.objectToJsonNode(tables));
return resourceGetRet.toString();
}
Example 10
Source File: LearningController.java From lams with GNU General Public License v2.0 | 5 votes |
/**
* Rates postings submitted by other learners.
*/
@RequestMapping("/rateMessage")
@ResponseBody
public String rateMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
String sessionMapId = WebUtil.readStrParam(request, ForumConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
.getAttribute(sessionMapId);
Long forumUid = (Long) sessionMap.get(ForumConstants.ATTR_FORUM_UID);
Long userUid = (Long) sessionMap.get(ForumConstants.ATTR_USER_UID);
boolean isAllowRateMessages = (Boolean) sessionMap.get(ForumConstants.ATTR_ALLOW_RATE_MESSAGES);
int forumMaximumRate = (Integer) sessionMap.get(ForumConstants.ATTR_MAXIMUM_RATE);
int forumMinimumRate = (Integer) sessionMap.get(ForumConstants.ATTR_MINIMUM_RATE);
float rating = Float.parseFloat(request.getParameter("rate"));
Long responseId = WebUtil.readLongParam(request, "idBox");
Long toolSessionID = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
UserDTO user = (UserDTO) SessionManager.getSession().getAttribute(AttributeNames.USER);
Long userId = new Long(user.getUserID().intValue());
AverageRatingDTO averageRatingDTO = forumService.rateMessage(responseId, userId, toolSessionID, rating);
//refresh numOfRatings and noMoreRatings
int numOfRatings = forumService.getNumOfRatingsByUserAndForum(userUid, forumUid);
boolean noMoreRatings = (forumMaximumRate != 0) && (numOfRatings >= forumMaximumRate) && isAllowRateMessages;
boolean isMinRatingsCompleted = (forumMinimumRate != 0) && (numOfRatings >= forumMinimumRate)
&& isAllowRateMessages;
sessionMap.put(ForumConstants.ATTR_NO_MORE_RATINGSS, noMoreRatings);
sessionMap.put(ForumConstants.ATTR_IS_MIN_RATINGS_COMPLETED, isMinRatingsCompleted);
sessionMap.put(ForumConstants.ATTR_NUM_OF_RATINGS, numOfRatings);
ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode();
ObjectNode.put("averageRating", averageRatingDTO.getRating());
ObjectNode.put("numberOfVotes", averageRatingDTO.getNumberOfVotes());
ObjectNode.put(ForumConstants.ATTR_NO_MORE_RATINGSS, noMoreRatings);
ObjectNode.put(ForumConstants.ATTR_NUM_OF_RATINGS, numOfRatings);
response.setContentType("application/json;charset=UTF-8");
return ObjectNode.toString();
}
Example 11
Source File: QueueMessageHandlerTest.java From spring-cloud-aws with Apache License 2.0 | 5 votes |
@Test
void receiveMessage_withNotificationMessageAndSubject_shouldResolveThem() {
// Arrange
StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("notificationMessageReceiver",
NotificationMessageReceiver.class);
applicationContext.registerSingleton("queueMessageHandler",
QueueMessageHandler.class);
applicationContext.refresh();
QueueMessageHandler queueMessageHandler = applicationContext
.getBean(QueueMessageHandler.class);
NotificationMessageReceiver notificationMessageReceiver = applicationContext
.getBean(NotificationMessageReceiver.class);
ObjectNode jsonObject = JsonNodeFactory.instance.objectNode();
jsonObject.put("Type", "Notification");
jsonObject.put("Subject", "Hi!");
jsonObject.put("Message", "Hello World!");
String payload = jsonObject.toString();
// Act
queueMessageHandler.handleMessage(MessageBuilder.withPayload(payload)
.setHeader(QueueMessageHandler.LOGICAL_RESOURCE_ID, "testQueue").build());
// Assert
assertThat(notificationMessageReceiver.getSubject()).isEqualTo("Hi!");
assertThat(notificationMessageReceiver.getMessage()).isEqualTo("Hello World!");
}
Example 12
Source File: Response.java From vespa with Apache License 2.0 | 5 votes |
public Response(int code, Optional<ObjectNode> element, Optional<RestUri> restPath) {
super(code);
ObjectNode objectNode = element.orElse(objectMapper.createObjectNode());
if (restPath.isPresent()) {
objectNode.put("id", restPath.get().generateFullId());
objectNode.put("pathId", restPath.get().getRawPath());
}
jsonMessage = objectNode.toString();
}
Example 13
Source File: OrgPasswordChangeController.java From lams with GNU General Public License v2.0 | 4 votes |
@RequestMapping("/getGridUsers")
@ResponseBody
public String getGridUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
Integer organisationID = WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID);
String role = WebUtil.readStrParam(request, AttributeNames.PARAM_ROLE);
UserDTO userDTO = getUserDTO();
Integer currentUserId = userDTO.getUserID();
if (!securityService.isSysadmin(currentUserId, "get grid users for org password change", false)) {
String warning = "User " + currentUserId + " is not a sysadmin";
log.warn(warning);
response.sendError(HttpServletResponse.SC_FORBIDDEN, warning);
return null;
}
int page = WebUtil.readIntParam(request, AdminConstants.PARAM_PAGE);
int rowLimit = WebUtil.readIntParam(request, AdminConstants.PARAM_ROWS);
String sortOrder = WebUtil.readStrParam(request, AdminConstants.PARAM_SORD);
String sortColumn = WebUtil.readStrParam(request, AdminConstants.PARAM_SIDX, true);
// fetch staff or learners
List<UserDTO> users = getUsersByRole(organisationID, role.equalsIgnoreCase("staff"), sortColumn, sortOrder);
// paging
int totalPages = 1;
int totalUsers = users.size();
if (rowLimit < users.size()) {
totalPages = new Double(
Math.ceil(new Integer(users.size()).doubleValue() / new Integer(rowLimit).doubleValue()))
.intValue();
int firstRow = (page - 1) * rowLimit;
int lastRow = firstRow + rowLimit;
if (lastRow > users.size()) {
users = users.subList(firstRow, users.size());
} else {
users = users.subList(firstRow, lastRow);
}
}
ObjectNode resultJSON = JsonNodeFactory.instance.objectNode();
resultJSON.put(AdminConstants.ELEMENT_PAGE, page);
resultJSON.put(AdminConstants.ELEMENT_TOTAL, totalPages);
resultJSON.put(AdminConstants.ELEMENT_RECORDS, totalUsers);
ArrayNode rowsJSON = JsonNodeFactory.instance.arrayNode();
// build rows for grid
for (UserDTO user : users) {
ObjectNode rowJSON = JsonNodeFactory.instance.objectNode();
rowJSON.put(AdminConstants.ELEMENT_ID, user.getUserID());
ArrayNode cellJSON = JsonNodeFactory.instance.arrayNode();
cellJSON.add(user.getFirstName() + " " + user.getLastName());
cellJSON.add(user.getLogin());
cellJSON.add(user.getEmail());
rowJSON.set(AdminConstants.ELEMENT_CELL, cellJSON);
rowsJSON.add(rowJSON);
}
resultJSON.set(AdminConstants.ELEMENT_ROWS, rowsJSON);
response.setContentType("application/json;charset=utf-8");
return resultJSON.toString();
}
Example 14
Source File: TimerChangeProcessDefinitionSuspensionStateJobHandler.java From flowable-engine with Apache License 2.0 | 4 votes |
public static String createJobHandlerConfiguration(boolean includeProcessInstances) {
ObjectNode jsonNode = CommandContextUtil.getProcessEngineConfiguration().getObjectMapper().createObjectNode();
jsonNode.put(JOB_HANDLER_CFG_INCLUDE_PROCESS_INSTANCES, includeProcessInstances);
return jsonNode.toString();
}
Example 15
Source File: LearningController.java From lams with GNU General Public License v2.0 | 4 votes |
/**
* In case validation was successful, we store message and return JSON object back to HTML
*/
@RequestMapping("/replyTopicJSON")
@ResponseBody
public String replyTopicJSON(@ModelAttribute MessageForm messageForm, HttpServletRequest request,
HttpServletResponse response) throws InterruptedException, IOException {
SessionMap<String, Object> sessionMap = getSessionMap(request, messageForm);
Long parentId = (Long) sessionMap.get(ForumConstants.ATTR_PARENT_TOPIC_ID);
Long sessionId = (Long) sessionMap.get(AttributeNames.PARAM_TOOL_SESSION_ID);
Message message = messageForm.getMessage();
boolean isTestHarness = Boolean.valueOf(request.getParameter("testHarness"));
if (isTestHarness) {
message.setBody(request.getParameter("message.body__textarea"));
}
message.setIsAuthored(false);
message.setCreated(new Date());
message.setUpdated(new Date());
message.setLastReplyDate(new Date());
ForumUser forumUser = getCurrentUser(request, sessionId);
message.setCreatedBy(forumUser);
message.setModifiedBy(forumUser);
setAttachment(messageForm, message);
setMonitorMode(sessionMap, message);
// save message into database
MessageSeq newMessageSeq = forumService.replyTopic(parentId, sessionId, message);
// check whether allow more posts for this user
Long rootTopicId = forumService.getRootTopicId(parentId);
ForumToolSession session = forumService.getSessionBySessionId(sessionId);
Forum forum = session.getForum();
int numOfPosts = forumService.getNumOfPostsByTopic(forumUser.getUserId(), rootTopicId);
boolean noMorePosts = forum.getMaximumReply() != 0 && numOfPosts >= forum.getMaximumReply()
&& !forum.isAllowNewTopic() ? Boolean.TRUE : Boolean.FALSE;
ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode();
ObjectNode.put(ForumConstants.ATTR_MESS_ID, newMessageSeq.getMessage().getUid());
ObjectNode.put(ForumConstants.ATTR_NO_MORE_POSTS, noMorePosts);
ObjectNode.put(ForumConstants.ATTR_NUM_OF_POSTS, numOfPosts);
ObjectNode.put(ForumConstants.ATTR_THREAD_ID, newMessageSeq.getThreadMessage().getUid());
ObjectNode.put(ForumConstants.ATTR_SESSION_MAP_ID, messageForm.getSessionMapID());
ObjectNode.put(ForumConstants.ATTR_ROOT_TOPIC_UID, rootTopicId);
ObjectNode.put(ForumConstants.ATTR_PARENT_TOPIC_ID, newMessageSeq.getMessage().getParent().getUid());
response.setContentType("application/json;charset=UTF-8");
return ObjectNode.toString();
}
Example 16
Source File: MoneyFormatterTest.java From template-compiler with Apache License 2.0 | 4 votes |
private static String money(BigDecimal n, CurrencyType code, boolean useCLDR) {
ObjectNode m = moneyBase(code.name(), useCLDR);
m.put("value", n);
return m.toString();
}
Example 17
Source File: MonitoringController.java From lams with GNU General Public License v2.0 | 4 votes |
@RequestMapping("/getUsers")
@ResponseBody
public String getUsers(HttpServletRequest request, HttpServletResponse response) throws IOException {
Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
Long contentId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_CONTENT_ID);
// paging parameters of tablesorter
int size = WebUtil.readIntParam(request, "size");
int page = WebUtil.readIntParam(request, "page");
Integer sortByName = WebUtil.readIntParam(request, "column[0]", true);
Integer sortByMarked = WebUtil.readIntParam(request, "column[1]", true);
String searchString = request.getParameter("fcol[0]");
int sorting = SpreadsheetConstants.SORT_BY_NO;
if (sortByName != null) {
sorting = sortByName.equals(0) ? SpreadsheetConstants.SORT_BY_USERNAME_ASC
: SpreadsheetConstants.SORT_BY_USERNAME_DESC;
} else if (sortByMarked != null) {
sorting = sortByMarked.equals(0) ? SpreadsheetConstants.SORT_BY_MARKED_ASC
: SpreadsheetConstants.SORT_BY_MARKED_DESC;
}
//return user list according to the given sessionID
Spreadsheet spreadsheet = service.getSpreadsheetByContentId(contentId);
List<Object[]> users = service.getUsersForTablesorter(sessionID, page, size, sorting, searchString,
spreadsheet.isReflectOnActivity());
ArrayNode rows = JsonNodeFactory.instance.arrayNode();
ObjectNode responsedata = JsonNodeFactory.instance.objectNode();
responsedata.put("total_rows", service.getCountUsersBySession(sessionID, searchString));
for (Object[] userAndReflection : users) {
ObjectNode responseRow = JsonNodeFactory.instance.objectNode();
SpreadsheetUser user = (SpreadsheetUser) userAndReflection[0];
responseRow.put(SpreadsheetConstants.ATTR_USER_UID, user.getUid());
responseRow.put(SpreadsheetConstants.ATTR_USER_ID, user.getUserId());
responseRow.put(SpreadsheetConstants.ATTR_USER_NAME, HtmlUtils.htmlEscape(user.getFullUsername()));
if (user.getUserModifiedSpreadsheet() != null) {
responseRow.put("userModifiedSpreadsheet", "true");
if (user.getUserModifiedSpreadsheet().getMark() != null) {
responseRow.put("mark",
NumberUtil.formatLocalisedNumber(user.getUserModifiedSpreadsheet().getMark().getMarks(),
request.getLocale(), SpreadsheetConstants.MARK_NUM_DEC_PLACES));
}
}
if (userAndReflection.length > 1 && userAndReflection[1] != null) {
responseRow.put("reflection", HtmlUtils.htmlEscape((String) userAndReflection[1]));
}
rows.add(responseRow);
}
responsedata.set("rows", rows);
response.setContentType("application/json;charset=UTF-8");
return responsedata.toString();
}
Example 18
Source File: CommentController.java From lams with GNU General Public License v2.0 | 4 votes |
/**
* Update a topic.
*
* @throws ServletException
*/
@RequestMapping("/updateTopicInline")
@ResponseBody
public String updateTopicInline(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
SessionMap<String, Object> sessionMap = getSessionMap(request);
Long commentId = WebUtil.readLongParam(request, CommentConstants.ATTR_COMMENT_ID);
Long externalId = (Long) sessionMap.get(CommentConstants.ATTR_EXTERNAL_ID);
Integer externalType = (Integer) sessionMap.get(CommentConstants.ATTR_EXTERNAL_TYPE);
String externalSignature = (String) sessionMap.get(CommentConstants.ATTR_EXTERNAL_SIG);
String commentText = request.getParameter(CommentConstants.ATTR_BODY);
if (commentText != null) {
commentText = commentText.trim();
}
// Don't update anonymous if it is monitoring
boolean isMonitoring = ToolAccessMode.TEACHER
.equals(WebUtil.getToolAccessMode((String) sessionMap.get(AttributeNames.ATTR_MODE)));
Boolean commentAnonymous = isMonitoring ? null
: WebUtil.readBooleanParam(request, CommentConstants.ATTR_COMMENT_ANONYMOUS_EDIT, false);
ObjectNode ObjectNode;
if (!validateText(commentText)) {
ObjectNode = getFailedValidationJSON();
} else {
CommentDTO originalComment = commentService.getComment(commentId);
User user = getCurrentUser(request);
if (!originalComment.getComment().getCreatedBy().equals(user)
&& !monitorInToolSession(externalId, user, sessionMap)) {
throwException(
"Update comment: User does not have the rights to update the comment " + commentId + ". ",
user.getLogin(), externalId, externalType, externalSignature);
}
Comment updatedComment = commentService.updateComment(commentId, commentText, user, commentAnonymous,
isMonitoring);
ObjectNode = JsonNodeFactory.instance.objectNode();
ObjectNode.put(CommentConstants.ATTR_COMMENT_ID, commentId);
ObjectNode.put(CommentConstants.ATTR_SESSION_MAP_ID, sessionMap.getSessionID());
ObjectNode.put(CommentConstants.ATTR_THREAD_ID, updatedComment.getThreadComment().getUid());
ObjectNode.put(CommentConstants.ATTR_PARENT_COMMENT_ID, updatedComment.getParent().getUid());
}
response.setContentType("application/json;charset=utf-8");
return ObjectNode.toString();
}
Example 19
Source File: EmailNotificationsController.java From lams with GNU General Public License v2.0 | 4 votes |
/**
* Method called via Ajax. It either emails selected users or schedules these emails to be sent on specified date.
*/
@RequestMapping(path = "/emailUsers", method = RequestMethod.POST)
@ResponseBody
public String emailUsers(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
ObjectNode ObjectNode = JsonNodeFactory.instance.objectNode();
String emailBody = WebUtil.readStrParam(request, "emailBody");
Long scheduleDateParameter = WebUtil.readLongParam(request, "scheduleDate", true);
String scheduleDateStr = "";
String emailClauseStr = "";
// check if we need to send email instantly
if (scheduleDateParameter == null) {
boolean isSuccessfullySent = true;
String[] userIdStrs = request.getParameterValues("userId");
Set<Integer> userIdInts = new HashSet<>();
for (String userIdStr : userIdStrs) {
int userId = Integer.parseInt(userIdStr);
userIdInts.add(userId);
boolean isHtmlFormat = false;
isSuccessfullySent &= eventNotificationService.sendMessage(null, userId,
IEventNotificationService.DELIVERY_METHOD_MAIL, monitoringService.getMessageService()
.getMessage("event.emailnotifications.email.subject", new Object[] {}),
emailBody, isHtmlFormat);
}
monitoringService.archiveEmailNotification(
WebUtil.readIntParam(request, AttributeNames.PARAM_ORGANISATION_ID, true),
WebUtil.readLongParam(request, AttributeNames.PARAM_LESSON_ID, true),
WebUtil.readIntParam(request, "searchType", true), emailBody, userIdInts);
ObjectNode.put("isSuccessfullySent", isSuccessfullySent);
//prepare data for audit log
scheduleDateStr = "now";
emailClauseStr = "for users (userIds: " + StringUtils.join(userIdStrs, ",") + ")";
} else {
try {
Calendar now = Calendar.getInstance();
// calculate scheduleDate
Date scheduleDateTeacherTimezone = new Date(scheduleDateParameter);
TimeZone teacherTimeZone = getCurrentUser().getTimeZone();
Date scheduleDate = DateUtil.convertFromTimeZoneToDefault(teacherTimeZone, scheduleDateTeacherTimezone);
// build job detail based on the bean class
JobDetail emailScheduleMessageJob = JobBuilder.newJob(EmailScheduleMessageJob.class)
.withIdentity(EmailNotificationsController.JOB_PREFIX_NAME + now.getTimeInMillis())
.withDescription("schedule email message to user(s)").usingJobData("emailBody", emailBody)
.build();
Map<String, Object> searchParameters = new HashMap<>();
copySearchParametersFromRequestToMap(request, searchParameters);
searchParameters.forEach(emailScheduleMessageJob.getJobDataMap()::putIfAbsent);
// create customized triggers
Trigger startLessonTrigger = TriggerBuilder.newTrigger()
.withIdentity(EmailNotificationsController.TRIGGER_PREFIX_NAME + now.getTimeInMillis())
.startAt(scheduleDate).build();
// start the scheduling job
scheduler.scheduleJob(emailScheduleMessageJob, startLessonTrigger);
ObjectNode.put("isSuccessfullyScheduled", true);
//prepare data for audit log
scheduleDateStr = "on " + scheduleDate;
Object lessonIdObj = searchParameters.get(AttributeNames.PARAM_LESSON_ID);
Object lessonIDsObj = searchParameters.get("lessonIDs");
Object organisationIdObj = searchParameters.get(AttributeNames.PARAM_ORGANISATION_ID);
if (lessonIdObj != null) {
emailClauseStr = "for lesson (lessonId: " + lessonIdObj + ")";
} else if (lessonIDsObj != null) {
emailClauseStr = "for lessons (lessonIDs: " + StringUtils.join((String[]) lessonIDsObj, ",") + ")";
} else if (organisationIdObj != null) {
emailClauseStr = "for organisation (organisationId: " + organisationIdObj + ")";
}
} catch (SchedulerException e) {
EmailNotificationsController.log
.error("Error occurred at " + "[emailScheduleMessage]- fail to email scheduling", e);
}
}
//audit log
logEventService.logEvent(LogEvent.TYPE_NOTIFICATION, getCurrentUser().getUserID(), null, null, null,
"User " + getCurrentUser().getLogin() + " set a notification " + emailClauseStr + " " + scheduleDateStr
+ " with the following notice: " + emailBody);
response.setContentType("application/json;charset=utf-8");
return ObjectNode.toString();
}
Example 20
Source File: EmailNotificationsController.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Refreshes user list. */ @RequestMapping("/getUsers") @ResponseBody public String getUsers(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Map<String, Object> map = new HashMap<>(); copySearchParametersFromRequestToMap(request, map); Long lessonId = (Long) map.get(AttributeNames.PARAM_LESSON_ID); Integer orgId = (Integer) map.get(AttributeNames.PARAM_ORGANISATION_ID); if (lessonId != null) { if (!securityService.isLessonMonitor(lessonId, getCurrentUser().getUserID(), "get users for lesson email notifications", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the lesson"); return null; } } else if (orgId != null) { if (!securityService.isGroupMonitor(orgId, getCurrentUser().getUserID(), "get users for course email notifications", false)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "The user is not a monitor in the organisation"); return null; } } int searchType = (Integer) map.get("searchType"); Long activityId = (Long) map.get(AttributeNames.PARAM_ACTIVITY_ID); Integer xDaystoFinish = (Integer) map.get("daysToDeadline"); String[] lessonIds = (String[]) map.get("lessonIDs"); Collection<User> users = monitoringService.getUsersByEmailNotificationSearchType(searchType, lessonId, lessonIds, activityId, xDaystoFinish, orgId); ArrayNode cellarray = JsonNodeFactory.instance.arrayNode(); ObjectNode responseDate = JsonNodeFactory.instance.objectNode(); responseDate.put("total", "" + users.size()); responseDate.put("page", "" + 1); responseDate.put("records", "" + users.size()); for (User user : users) { ArrayNode cell = JsonNodeFactory.instance.arrayNode(); cell.add(new StringBuilder(user.getLastName()).append(", ").append(user.getFirstName()).append(" (") .append(user.getLogin()).append(")").toString()); ObjectNode cellobj = JsonNodeFactory.instance.objectNode(); cellobj.put("id", "" + user.getUserId()); cellobj.set("cell", cell); cellarray.add(cellobj); } responseDate.set("rows", cellarray); response.setContentType("application/json;charset=utf-8"); return responseDate.toString(); }