PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/test/AjaxTestServer.java

https://github.com/pavlo-sof/jQuery-Validation-Engine
Java | 202 lines | 117 code | 39 blank | 46 comment | 13 complexity | deec484af1354ea703d8a4f5eacaf88f MD5 | raw file
  1. import java.io.IOException;
  2. import java.util.ArrayList;
  3. import java.util.Properties;
  4. /**
  5. * This java class implements a basic HTTP server aimed at testing the
  6. * jQuery.validate AJAX capabilities. Note that this file shouldn't be taken as
  7. * best practice for java back end development. There are much better frameworks
  8. * to do server side processing in Java, for instance, the Play Framework.
  9. *
  10. * @author Olivier Refalo
  11. */
  12. public class AjaxTestServer extends NanoHTTPD {
  13. private static final int PORT = 9173;
  14. public static final String MIME_JSON = "application/json";
  15. public AjaxTestServer() throws IOException {
  16. super(PORT);
  17. }
  18. public class AjaxValidationFieldResponse {
  19. // the html field id
  20. private String id;
  21. // true - field is valid
  22. private Boolean status;
  23. public AjaxValidationFieldResponse(String fieldId, Boolean s) {
  24. id = fieldId;
  25. status = s;
  26. }
  27. public String toString() {
  28. StringBuffer json = new StringBuffer();
  29. json.append("[\"").append(id).append("\",").append(status.toString()).append(']');
  30. return json.toString();
  31. }
  32. }
  33. public class AjaxValidationFormResponse {
  34. // the html field id
  35. private String id;
  36. // true, the field is valid : the client logic displays a green prompt
  37. // false, the field is invalid : the client logic displays a red prompt
  38. private Boolean status;
  39. // either the string to display in the prompt or an error
  40. // selector to pick the error message from the translation.js
  41. private String error;
  42. public AjaxValidationFormResponse(String fieldId, Boolean s, String err) {
  43. id = fieldId;
  44. status = s;
  45. error = err;
  46. }
  47. public String toString() {
  48. StringBuffer json = new StringBuffer();
  49. json.append("[\"").append(id).append("\",").append(status).append(",\"").append(error.toString()).append("\"]");
  50. return json.toString();
  51. }
  52. }
  53. public Response serve(String uri, String method, Properties header, Properties parms) {
  54. // field validation
  55. if ("/ajaxValidateFieldUser".equals(uri)) {
  56. System.out.println("-> " + method + " '" + uri + "'");
  57. // purposely sleep to let the UI display the AJAX loading prompts
  58. sleep(3000);
  59. String fieldId = parms.getProperty("fieldId");
  60. String fieldValue = parms.getProperty("fieldValue");
  61. AjaxValidationFieldResponse result = new AjaxValidationFieldResponse(fieldId, new Boolean(
  62. "karnius".equals(fieldValue)));
  63. // return ["fieldid", true or false]
  64. return new NanoHTTPD.Response(HTTP_OK, MIME_JSON, result.toString());
  65. }
  66. // field validation
  67. else if ("/ajaxValidateFieldName".equals(uri)) {
  68. System.out.println("-> " + method + " '" + uri + "'");
  69. // purposely sleep to let the UI display the AJAX loading prompts
  70. sleep(3000);
  71. String fieldId = parms.getProperty("fieldId");
  72. String fieldValue = parms.getProperty("fieldValue");
  73. AjaxValidationFieldResponse result = new AjaxValidationFieldResponse(fieldId, new Boolean(
  74. "duncan".equals(fieldValue)));
  75. // return ["fieldid", true or false]
  76. return new NanoHTTPD.Response(HTTP_OK, MIME_JSON, result.toString());
  77. }
  78. // form validation, we get the form data (read: all the form fields), we
  79. // return ALL the errors
  80. else if ("/ajaxSubmitForm".equals(uri)) {
  81. System.out.println("-> " + method + " '" + uri + "'");
  82. // purposely sleep to let the UI display the AJAX loading prompts
  83. sleep(1000);
  84. ArrayList<AjaxValidationFormResponse> errors = new ArrayList<AjaxValidationFormResponse>();
  85. String user = parms.getProperty("user");
  86. String firstname = parms.getProperty("firstname");
  87. String email = parms.getProperty("email");
  88. if (!"karnius".equals(user)) {
  89. // error selector: indirection to the error message -> done in
  90. // javascript
  91. errors.add(new AjaxValidationFormResponse("user", false, "ajaxUserCall"));
  92. }
  93. if (!"duncan".equals(firstname)) {
  94. errors.add(new AjaxValidationFormResponse("firstname", false, "Please enter DUNCAN"));
  95. } else {
  96. errors.add(new AjaxValidationFormResponse("firstname", true, "You got it!"));
  97. }
  98. if (!"someone@here.com".equals(email)) {
  99. errors.add(new AjaxValidationFormResponse("email", false, "The email doesn't match someone@here.com"));
  100. }
  101. String json = "true";
  102. if (errors.size() != 0) {
  103. json = genJSON(errors);
  104. }
  105. return new NanoHTTPD.Response(HTTP_OK, MIME_JSON, json);
  106. }
  107. return super.serve(uri, method, header, parms);
  108. }
  109. /**
  110. * Form validation error generation Generates a list of errors
  111. *
  112. * @param errors
  113. * @return [["field1", "this field is required<br/>
  114. * it doesn't match<br/>
  115. * "],["field2","another error"]]
  116. */
  117. private String genJSON(ArrayList<AjaxValidationFormResponse> errors) {
  118. StringBuffer json = new StringBuffer();
  119. json.append('[');
  120. for (int i = 0; i < errors.size(); i++) {
  121. AjaxValidationFormResponse err = errors.get(i);
  122. json.append(err.toString());
  123. if (i < errors.size() - 1) {
  124. json.append(',');
  125. }
  126. }
  127. json.append(']');
  128. return json.toString();
  129. }
  130. /**
  131. * Sleeps the current thread for the given delay
  132. *
  133. * @param duration
  134. * in milliseconds
  135. * */
  136. private void sleep(long duration) {
  137. try {
  138. Thread.sleep(duration);
  139. } catch (InterruptedException e) {
  140. e.printStackTrace();
  141. }
  142. }
  143. /**
  144. * Application start point, starts the httpd server
  145. *
  146. * @param args
  147. * command line arguments
  148. */
  149. public static void main(String[] args) {
  150. try {
  151. new AjaxTestServer();
  152. } catch (IOException ioe) {
  153. System.err.println("Couldn't start server:\n" + ioe);
  154. System.exit(-1);
  155. }
  156. System.out.println("Listening on port " + PORT + ". Hit Enter to stop.\nPlease open your browsers to http://localhost:"
  157. + PORT);
  158. try {
  159. System.in.read();
  160. } catch (Throwable t) {
  161. }
  162. }
  163. }