Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

CordovaHttpResponse.java 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package com.silkimen.cordovahttp;
  2. import java.nio.ByteBuffer;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.json.JSONException;
  7. import org.json.JSONObject;
  8. import android.text.TextUtils;
  9. import android.util.Log;
  10. import android.util.Base64;
  11. class CordovaHttpResponse {
  12. private int status;
  13. private String url;
  14. private Map<String, List<String>> headers;
  15. private String body;
  16. private byte[] rawData;
  17. private JSONObject fileEntry;
  18. private boolean hasFailed;
  19. private boolean isFileOperation;
  20. private boolean isRawResponse;
  21. private String error;
  22. public void setStatus(int status) {
  23. this.status = status;
  24. }
  25. public void setUrl(String url) {
  26. this.url = url;
  27. }
  28. public void setHeaders(Map<String, List<String>> headers) {
  29. this.headers = headers;
  30. }
  31. public void setBody(String body) {
  32. this.body = body;
  33. }
  34. public void setData(byte[] rawData) {
  35. this.isRawResponse = true;
  36. this.rawData = rawData;
  37. }
  38. public void setFileEntry(JSONObject entry) {
  39. this.isFileOperation = true;
  40. this.fileEntry = entry;
  41. }
  42. public void setErrorMessage(String message) {
  43. this.hasFailed = true;
  44. this.error = message;
  45. }
  46. public boolean hasFailed() {
  47. return this.hasFailed;
  48. }
  49. public JSONObject toJSON() throws JSONException {
  50. JSONObject json = new JSONObject();
  51. json.put("status", this.status);
  52. json.put("url", this.url);
  53. if (this.headers != null && !this.headers.isEmpty()) {
  54. json.put("headers", new JSONObject(getFilteredHeaders()));
  55. }
  56. if (this.hasFailed) {
  57. json.put("error", this.error);
  58. } else if (this.isFileOperation) {
  59. json.put("file", this.fileEntry);
  60. } else if (this.isRawResponse) {
  61. json.put("data", Base64.encodeToString(this.rawData, Base64.DEFAULT));
  62. } else {
  63. json.put("data", this.body);
  64. }
  65. return json;
  66. }
  67. private Map<String, String> getFilteredHeaders() throws JSONException {
  68. Map<String, String> filteredHeaders = new HashMap<String, String>();
  69. for (Map.Entry<String, List<String>> entry : this.headers.entrySet()) {
  70. String key = entry.getKey();
  71. List<String> value = entry.getValue();
  72. if ((key != null) && (!value.isEmpty())) {
  73. filteredHeaders.put(key.toLowerCase(), TextUtils.join(", ", value));
  74. }
  75. }
  76. return filteredHeaders;
  77. }
  78. }