<commit_before>package okapi;

import guru.nidi.ramltester.RamlDefinition;
import guru.nidi.ramltester.RamlLoaders;
import guru.nidi.ramltester.restassured3.RestAssuredClient;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import java.util.LinkedList;
import org.folio.okapi.MainVerticle;
import org.folio.okapi.common.Messages;
import org.folio.okapi.common.OkapiLogger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@java.lang.SuppressWarnings({"squid:S1166", "squid:S1192"})
@RunWith(VertxUnitRunner.class)
public class DockerTest {

  private final Logger logger = OkapiLogger.get();
  private Vertx vertx;
  private final int port = 9230;
  private static final String LS = System.lineSeparator();
  private final LinkedList<String> locations;
  private boolean haveDocker = false;
  private HttpClient client;
  private Messages messages = Messages.getInstance();

  public DockerTest() {
    this.locations = new LinkedList<>();
  }

  @Before
  public void setUp(TestContext context) {
    Async async = context.async();
    VertxOptions options = new VertxOptions();
    options.setBlockedThreadCheckInterval(60000); // in ms
    options.setWarningExceptionTime(60000); // in ms
    vertx = Vertx.vertx(options);
    RestAssured.port = port;
    client = vertx.createHttpClient();

    checkDocker(res2 -> {
      haveDocker = res2.succeeded();
      logger.info("haveDocker = " + haveDocker);

      DeploymentOptions opt = new DeploymentOptions()
        .setConfig(new JsonObject().put("port", Integer.toString(port)));

      vertx.deployVerticle(MainVerticle.class.getName(),
        opt, res -> async.complete());
    });
  }

  @After
  public void tearDown(TestContext context) {
    logger.info("tearDown");
    td(context, context.async());
  }

  private void td(TestContext context, Async async) {
    if (locations.isEmpty()) {
      vertx.close(x -> {
        async.complete();
      });
    } else {
      String l = locations.removeFirst();
      HttpClientRequest req = client.delete(port, "localhost", l, res -> {
        td(context, async);
      });
      req.end();
    }
  }

  private void checkDocker(Handler<AsyncResult<Void>> future) {
    final String dockerUrl = "http://localhost:4243";
    final String url = dockerUrl + "/images/json?all=1";
    HttpClientRequest req = client.getAbs(url, res -> {
      Buffer body = Buffer.buffer();
      res.handler(d -> {
        body.appendBuffer(d);
      });
      res.endHandler(d -> {
        if (res.statusCode() == 200) {
          boolean gotIt = false;
          try {
            JsonArray ar = body.toJsonArray();
            for (int i = 0; i < ar.size(); i++) {
              JsonObject ob = ar.getJsonObject(i);
              JsonArray ar1 = ob.getJsonArray("RepoTags");
              if (ar1 != null) {
                for (int j = 0; j < ar1.size(); j++) {
                  String tag = ar1.getString(j);
                  if (tag != null && tag.startsWith("okapi-test-module")) {
                    gotIt = true;
                  }
                }
              }
            }
          } catch (Exception ex) {
            logger.warn(ex);
          }
          if (gotIt) {
            future.handle(Future.succeededFuture());
          } else {
            future.handle(Future.failedFuture(messages.getMessage("11700")));
          }
        } else {
          String m = messages.getMessage("11701",
            Integer.toString(res.statusCode()), body.toString());
          logger.error(m);
          future.handle(Future.failedFuture(m));
        }
      });
    });
    req.exceptionHandler(d -> {
      future.handle(Future.failedFuture(d.getMessage()));
    });
    req.end();
  }
<commit_msg>Fix Docker test hangs OKAPI-689 (#733)<commit_after>package okapi;

import guru.nidi.ramltester.RamlDefinition;
import guru.nidi.ramltester.RamlLoaders;
import guru.nidi.ramltester.restassured3.RestAssuredClient;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.vertx.core.AsyncResult;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import java.util.LinkedList;
import org.folio.okapi.MainVerticle;
import org.folio.okapi.common.OkapiLogger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@java.lang.SuppressWarnings({"squid:S1166", "squid:S1192"})
@RunWith(VertxUnitRunner.class)
public class DockerTest {

  private final Logger logger = OkapiLogger.get();
  private Vertx vertx;
  private final int port = 9230;
  private static final String LS = System.lineSeparator();
  private final LinkedList<String> locations;
  private boolean haveDocker = false;
  private HttpClient client;

  public DockerTest() {
    this.locations = new LinkedList<>();
  }

  @Before
  public void setUp(TestContext context) {
    Async async = context.async();
    VertxOptions options = new VertxOptions();
    options.setBlockedThreadCheckInterval(60000); // in ms
    options.setWarningExceptionTime(60000); // in ms
    vertx = Vertx.vertx(options);
    RestAssured.port = port;
    client = vertx.createHttpClient();

    checkDocker(res2 -> {
      haveDocker = res2.succeeded();
      logger.info("haveDocker = " + haveDocker);

      DeploymentOptions opt = new DeploymentOptions()
        .setConfig(new JsonObject().put("port", Integer.toString(port)));

      vertx.deployVerticle(MainVerticle.class.getName(),
        opt, res -> async.complete());
    });
  }

  @After
  public void tearDown(TestContext context) {
    logger.info("tearDown");
    td(context, context.async());
  }

  private void td(TestContext context, Async async) {
    if (locations.isEmpty()) {
      vertx.close(x -> {
        async.complete();
      });
    } else {
      String l = locations.removeFirst();
      HttpClientRequest req = client.delete(port, "localhost", l, res -> {
        td(context, async);
      });
      req.end();
    }
  }

  private void checkDocker(Handler<AsyncResult<Void>> future) {
    final String dockerUrl = "http://localhost:4243";
    final String url = dockerUrl + "/images/json?all=1";
    HttpClientRequest req = client.getAbs(url, res -> {
      Buffer body = Buffer.buffer();
      res.handler(d -> {
        body.appendBuffer(d);
      });
      res.endHandler(d -> {
        if (res.statusCode() == 200) {
          boolean gotIt = false;
          try {
            JsonArray ar = body.toJsonArray();
            for (int i = 0; i < ar.size(); i++) {
              JsonObject ob = ar.getJsonObject(i);
              JsonArray ar1 = ob.getJsonArray("RepoTags");
              if (ar1 != null) {
                for (int j = 0; j < ar1.size(); j++) {
                  String tag = ar1.getString(j);
                  if (tag != null && tag.startsWith("okapi-test-module")) {
                    gotIt = true;
                  }
                }
              }
            }
          } catch (Exception ex) {
            logger.warn(ex);
          }
          if (gotIt) {
            future.handle(Future.succeededFuture());
          } else {
            future.handle(Future.failedFuture("okapi-test-module not found"));
          }
        } else {
          String m = "checkDocker HTTP error " + res.statusCode() + "\n"
            + body.toString();
          logger.error(m);
          future.handle(Future.failedFuture(m));
        }
      });
    });
    req.exceptionHandler(d -> {
      future.handle(Future.failedFuture(d.getMessage()));
    });
    req.end();
  }

{'fraction_non_alphanumeric': 0.13177483135612933, 'fraction_numerical': 0.010932775063968364, 'mean_word_length': 2.66538789428815, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '125870', 'n_tokens_mistral': 2731, 'n_tokens_neox': 2634, 'n_words': 522}