PageRenderTime 5401ms CodeModel.GetById 36ms RepoModel.GetById 7ms app.codeStats 0ms

/src/main/java/com/todoapp/TodoService.java

https://gitlab.com/vsailakshmi/todoapp-spark
Java | 49 lines | 37 code | 9 blank | 3 comment | 1 complexity | cdfebc31b160603c0440b4b86b7e9788 MD5 | raw file
  1. package com.todoapp;
  2. import com.google.gson.Gson;
  3. import com.mongodb.*;
  4. import org.bson.types.ObjectId;
  5. import java.util.ArrayList;
  6. import java.util.Collections;
  7. import java.util.Date;
  8. import java.util.List;
  9. /**
  10. * Created by shekhargulati on 09/06/14.
  11. */
  12. public class TodoService {
  13. private final DB db;
  14. private final DBCollection collection;
  15. public TodoService(DB db) {
  16. this.db = db;
  17. this.collection = db.getCollection("todos");
  18. }
  19. public List<Todo> findAll() {
  20. List<Todo> todos = new ArrayList<>();
  21. DBCursor dbObjects = collection.find();
  22. while (dbObjects.hasNext()) {
  23. DBObject dbObject = dbObjects.next();
  24. todos.add(new Todo((BasicDBObject) dbObject));
  25. }
  26. return todos;
  27. }
  28. public void createNewTodo(String body) {
  29. Todo todo = new Gson().fromJson(body, Todo.class);
  30. collection.insert(new BasicDBObject("title", todo.getTitle()).append("done", todo.isDone()).append("createdOn", new Date()));
  31. }
  32. public Todo find(String id) {
  33. return new Todo((BasicDBObject) collection.findOne(new BasicDBObject("_id", new ObjectId(id))));
  34. }
  35. public Todo update(String todoId, String body) {
  36. Todo todo = new Gson().fromJson(body, Todo.class);
  37. collection.update(new BasicDBObject("_id", new ObjectId(todoId)), new BasicDBObject("$set", new BasicDBObject("done", todo.isDone())));
  38. return this.find(todoId);
  39. }
  40. }