Application.java 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package hello;
  2. import com.blade.Blade;
  3. import com.blade.server.netty.HttpConst;
  4. import hello.model.Message;
  5. import hello.model.World;
  6. import io.netty.buffer.ByteBuf;
  7. import io.netty.buffer.Unpooled;
  8. import io.netty.util.AsciiString;
  9. import io.netty.util.CharsetUtil;
  10. import java.util.Optional;
  11. import java.util.Random;
  12. import java.util.concurrent.ThreadLocalRandom;
  13. /**
  14. * Blade Application
  15. *
  16. * @author biezhi
  17. * @date 2017/9/22
  18. */
  19. public class Application {
  20. private static final int DB_ROWS = 308;
  21. private static final byte[] STATIC_PLAINTEXT = "Hello, World!".getBytes(CharsetUtil.UTF_8);
  22. private static final ByteBuf PLAINTEXT_CONTENT_BUFFER = Unpooled.unreleasableBuffer(Unpooled.directBuffer().writeBytes(STATIC_PLAINTEXT));
  23. private static final CharSequence PLAINTEXT_CLHEADER_VALUE = AsciiString.cached(String.valueOf(STATIC_PLAINTEXT.length));
  24. private static int getQueries(Optional<String> queryCount) {
  25. if (!queryCount.isPresent()) {
  26. return 1;
  27. }
  28. int count;
  29. try {
  30. count = Integer.parseInt(queryCount.get());
  31. } catch (NumberFormatException ignored) {
  32. return 1;
  33. }
  34. count = count < 1 ? 1 : count;
  35. count = count > 500 ? 500 : count;
  36. return count;
  37. }
  38. public static void main(String[] args) {
  39. Blade.me()
  40. .get("/json", (request, response) -> {
  41. response.contentType(HttpConst.getContentType("application/json"));
  42. response.json(new Message());
  43. })
  44. .get("/db", (request, response) -> {
  45. final Random random = ThreadLocalRandom.current();
  46. response.contentType(HttpConst.getContentType("application/json"));
  47. response.json(new World().find(random.nextInt(DB_ROWS) + 1));
  48. })
  49. .get("/queries", (request, response) -> {
  50. int queries = getQueries(request.query("queries"));
  51. final World[] worlds = new World[queries];
  52. final Random random = ThreadLocalRandom.current();
  53. for (int i = 0; i < queries; i++) {
  54. worlds[i] = new World().find(random.nextInt(DB_ROWS) + 1);
  55. }
  56. response.contentType(HttpConst.getContentType("application/json"));
  57. response.json(worlds);
  58. })
  59. .get("/plaintext", (request, response) -> {
  60. response.contentType(HttpConst.getContentType("text/plain"));
  61. response.header(HttpConst.CONTENT_LENGTH, PLAINTEXT_CLHEADER_VALUE);
  62. response.body(PLAINTEXT_CONTENT_BUFFER.duplicate());
  63. })
  64. .disableSession()
  65. .start(Application.class, args);
  66. }
  67. }