AsynchronousTasksRunner.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /***************************************************************************************
  2. * IBM Confidential
  3. *
  4. * OCO Source Materials
  5. *
  6. * IBM Cognos Products: Moser
  7. *
  8. * (C) Copyright IBM Corp. 2020
  9. *
  10. * The source code for this program is not published or otherwise
  11. * divested of its trade secrets, irrespective of what has been
  12. * deposited with the U.S. Copyright Office.
  13. *
  14. ***************************************************************************************/
  15. package com.ibm.bi.platform.modeling.sdk.examples;
  16. import com.ibm.bi.platform.modeling.sdk.examples.internal.ModelingHelper;
  17. import com.ibm.bi.platform.moser.core.tasks.TaskState;
  18. import com.ibm.json.java.JSONObject;
  19. /**
  20. * Abstract class providing an ability to poll for asynchronous tasks execution
  21. *
  22. */
  23. public abstract class AsynchronousTasksRunner extends ModelingHelper {
  24. /**
  25. * @param origin
  26. */
  27. public AsynchronousTasksRunner(String origin) {
  28. super(origin);
  29. }
  30. /**
  31. * Poll for execution status of asynchronous task
  32. *
  33. * @param taskJson
  34. * json string representing asynchronous task, e.g.
  35. * {"href":"\/tasks\/task11588762627068","taskID":"task11588762627068"}
  36. * @return final response object after task execution is complete
  37. */
  38. protected JSONObject executeAsychronousTask(String taskJson) {
  39. try {
  40. JSONObject task = JSONObject.parse(taskJson);
  41. String asynchronousTaskId = task.get("taskID").toString();
  42. // start polling
  43. String url = getOrigin() + getTasksURL() + asynchronousTaskId;
  44. JSONObject response = stringToJson(executeGetRequest(url, Integer.valueOf(200), null));
  45. while (response != null && inProgress(response.get("state").toString())) {
  46. try {
  47. Thread.sleep(3000);
  48. } catch (Exception e) {
  49. }
  50. response = stringToJson(executeGetRequest(url, Integer.valueOf(200), null));
  51. }
  52. return response;
  53. } catch (Exception e) {
  54. e.printStackTrace();
  55. }
  56. return null;
  57. }
  58. /**
  59. * @return url to obtain asynchronous task status
  60. */
  61. public abstract String getTasksURL();
  62. /**
  63. * @param state
  64. * asynchronous task state see <code>TaskState</code>
  65. * @return true if task is not finished
  66. */
  67. private static boolean inProgress(String state) {
  68. if(state == null){
  69. return false;
  70. }
  71. switch (state) {
  72. case TaskState.EXECUTING:
  73. case TaskState.PENDING:
  74. case TaskState.NOT_CANCELLABLE:
  75. return true;
  76. default:
  77. return false;
  78. }
  79. }
  80. }