ConditionWatcher.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (C) 2016 Azimo
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.azimolabs.conditionwatcher;
  17. public class ConditionWatcher {
  18. public static final int CONDITION_NOT_MET = 0;
  19. public static final int CONDITION_MET = 1;
  20. public static final int TIMEOUT = 2;
  21. public static final int DEFAULT_TIMEOUT_LIMIT = 1000 * 60;
  22. public static final int DEFAULT_INTERVAL = 250;
  23. private int timeoutLimit = DEFAULT_TIMEOUT_LIMIT;
  24. private int watchInterval = DEFAULT_INTERVAL;
  25. private static ConditionWatcher conditionWatcher;
  26. private ConditionWatcher() {
  27. super();
  28. }
  29. public static ConditionWatcher getInstance() {
  30. if (conditionWatcher == null) {
  31. conditionWatcher = new ConditionWatcher();
  32. }
  33. return conditionWatcher;
  34. }
  35. public static void waitForCondition(Instruction instruction) throws Exception {
  36. int status = CONDITION_NOT_MET;
  37. int elapsedTime = 0;
  38. do {
  39. if (instruction.checkCondition()) {
  40. status = CONDITION_MET;
  41. } else {
  42. elapsedTime += getInstance().watchInterval;
  43. Thread.sleep(getInstance().watchInterval);
  44. }
  45. if (elapsedTime == getInstance().timeoutLimit) {
  46. status = TIMEOUT;
  47. break;
  48. }
  49. } while (status != CONDITION_MET);
  50. if (status == TIMEOUT)
  51. throw new Exception(instruction.getDescription() + " - took more than " + getInstance().timeoutLimit / 1000 + " seconds. Test stopped.");
  52. }
  53. public static void setWatchInterval(int watchInterval) {
  54. getInstance().watchInterval = watchInterval;
  55. }
  56. public static void setTimeoutLimit(int ms) {
  57. getInstance().timeoutLimit = ms;
  58. }
  59. }