Adding a task comment

Normal and admin users can add comments to an existing task. On opening the task in view mode, the screen provides a facility to add a comment. The code of the controller method for adding task comments looks as follows:

@PostMapping("/addTaskComment")
fun addTask(@RequestParam(name = "taskId",required = true) taskId:Int,
@RequestParam(name = "taskComment",required = true) taskComment:String,
model:Model):String {
val currentTask:Task? = taskRepository?.findById(taskId)?.get()
if(currentTask !=null) {
val principal = SecurityContextHolder.getContext().authentication.principal
if (principal is CustomUserPrinciple) {
val user = principal.getUser()
var existingComments: MutableSet<Comments>? = currentTask.getComments()
var comment:Comments?
if(existingComments == null || existingComments.isEmpty()) {
existingComments = mutableSetOf() // Inmitialize empty hash set
}
comment = Comments()
comment.setTask(currentTask)
if(user !=null) comment.setUser(user)
comment.setComment(taskComment)
comment = commentRepository?.save(comment)
if(comment !=null) {
existingComments.add(comment)
}
currentTask.setComments(existingComments)
taskRepository?.save(currentTask)
}
}
return "redirect:viewTask?taskId=$taskId"
}

In this method, the taskId and taskComment parameters are supplied by the view task screen from where the user can add the comment. We fetch the Task object from taskId and fetch its comments as a mutable set.

Kotlin provides an API collection (list, set, map, and so on) with a clear distinction between mutable and immutable types. This is very handy to ensure you avoid bugs and design clear APIs. When you declare any collection, say, List<out T>, it is immutable by default and Kotlin allows read-only operations, such as size(), get(), and so on. You cannot add any element to it.

If you wish to modify the collection, you need to use mutable types explicitly, such as MutableList<String>, MutableMap<String, String>, and so on. In our case, we need to add a comment in the existing set so we used the MutableSet type. The comment set is empty while adding the first comment so we create an empty set with the mutableSetOf() method. This method is used to create a collection of the Set type on the fly.

We also need to add userId of the currently logged-in user to a comment. To do so, we make a call to SecurityContextHolder.getContext().authentication.principal. The SecurityContextHolder class is provided by Spring Security, and it is used to get various security-related information.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.5.239