MongodbController.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package hello.controller;
  2. import hello.controller.persistence.WorldsMongodbRepository;
  3. import hello.domain.World;
  4. import java.util.Random;
  5. import java.util.concurrent.ThreadLocalRandom;
  6. import com.strategicgains.restexpress.Request;
  7. import com.strategicgains.restexpress.Response;
  8. public class MongodbController
  9. {
  10. // Database details.
  11. private static final int DB_ROWS = 10000;
  12. private WorldsMongodbRepository worldRepo;
  13. public MongodbController(WorldsMongodbRepository worldsRepository)
  14. {
  15. super();
  16. this.worldRepo = worldsRepository;
  17. }
  18. public World[] read(Request request, Response response)
  19. {
  20. // Get the count of queries to run.
  21. int count = 1;
  22. String value = request.getHeader("queries");
  23. if (value != null)
  24. {
  25. count = Integer.parseInt(value);
  26. }
  27. // Bounds check.
  28. if (count > 500)
  29. {
  30. count = 500;
  31. }
  32. else if (count < 1)
  33. {
  34. count = 1;
  35. }
  36. // Fetch some rows from the database.
  37. final World[] worlds = new World[count];
  38. final Random random = ThreadLocalRandom.current();
  39. for (int i = 0; i < count; i++)
  40. {
  41. worlds[i] = worldRepo.find(random.nextInt(DB_ROWS) + 1);
  42. }
  43. return worlds;
  44. }
  45. }