@Test
  public void purgeFortressRemovesConcepts() throws Exception {
    try {
      logger.debug("### uniqueRelationshipByDocType");
      setSecurity();

      engineConfig.setConceptsEnabled(true);
      engineConfig.setTestMode(true);

      Transaction t;

      SystemUser su = registerSystemUser("relationshipWorkForMultipleDocuments", mike_admin);
      assertNotNull(su);

      Fortress fortress =
          fortressService.registerFortress(
              su.getCompany(), new FortressInputBean("relationshipWorkForMultipleDocuments", true));

      t = beginManualTransaction();
      DocumentType claim = conceptService.resolveByDocCode(fortress, "Claim", true);
      commitManualTransaction(t);

      EntityInputBean promoInput =
          new EntityInputBean(fortress, "jinks", claim.getName(), new DateTime());
      promoInput.addTag(new TagInputBean("a1065", "Claim", "identifier").setLabel("Claim"));

      mediationFacade.trackEntity(su.getCompany(), promoInput).getEntity();

      Collection<String> docs = new ArrayList<>();
      docs.add(claim.getName());
      validateConcepts(docs, su, 1);
      docs.clear();
      docs.add(claim.getName());
      Set<DocumentResultBean> foundDocs = validateConcepts(docs, su, 1);
      for (DocumentResultBean foundDoc : foundDocs) {
        assertEquals("Claim", foundDoc.getName());
        Collection<ConceptResultBean> concepts = foundDoc.getConcepts();
        assertEquals(1, concepts.size());
        boolean claimFound = false;
        for (ConceptResultBean concept : concepts) {
          if (concept.getName().equalsIgnoreCase("Claim")) {
            claimFound = true;
            assertEquals(1, concept.getRelationships().size());
          }
        }

        assertEquals(true, claimFound);
        logger.info(foundDoc.toString());
      }
      mediationFacade.purge(fortress);
      waitAWhile("Waiting for Async processing to complete");
      assertEquals(0, conceptService.getDocumentsInUse(fortress.getCompany()).size());
    } finally {
      cleanUpGraph();
    }
  }
  @Test
  public void testEntityConceptsLink() throws Exception {
    // Initial setup
    cleanUpGraph();

    engineConfig.setConceptsEnabled(true);
    engineConfig.setTestMode(true);

    SystemUser su = registerSystemUser("testEntityConceptsLink", mike_admin);
    Fortress fortress =
        fortressService.registerFortress(
            su.getCompany(), new FortressInputBean("testEntityConceptsLink", true));

    EntityInputBean staff =
        new EntityInputBean(fortress, "wally", "Staff", new DateTime(), "ABC123");

    mediationFacade.trackEntity(su.getCompany(), staff);
    assertEquals(1, conceptService.getDocumentsInUse(su.getCompany()).size());

    // Checking that the entity is linked when part of the track request
    EntityInputBean workRecord =
        new EntityInputBean(fortress, "wally", "Work", new DateTime(), "ABC321")
            .addTag(new TagInputBean("someTag", "SomeLabel", "somerlx"))
            .addEntityLink(
                "worked",
                new EntityKeyBean("Staff", fortress.getName(), "ABC123")
                    .setRelationshipName("worked"));

    mediationFacade.trackEntity(su.getCompany(), workRecord);
    assertEquals(2, conceptService.getDocumentsInUse(su.getCompany()).size());

    Collection<String> docs = new ArrayList<>();
    docs.add("Staff");
    docs.add("Work");
    Set<DocumentResultBean> documentResults =
        conceptService.findConcepts(su.getCompany(), docs, true);
    assertEquals(2, documentResults.size());
    for (DocumentResultBean documentResultBean : documentResults) {
      switch (documentResultBean.getName()) {
        case "Staff":
          break;
        case "Work":
          // nothing to assert yet
          assertEquals(1, documentResultBean.getConcepts().size());
          assertEquals("SomeLabel", documentResultBean.getConcepts().iterator().next().getName());
          break;
        default:
          fail("Unexpected Document Type " + documentResultBean);
          break;
      }
    }

    // We should be able to find that a Staff entity has a worked link to a Timesheet
  }
  @Test
  public void testEntityConceptsLinkProperties() throws Exception {
    // Initial setup
    cleanUpGraph();

    engineConfig.setConceptsEnabled(true);
    engineConfig.setTestMode(true);

    SystemUser su = registerSystemUser("testEntityConceptsLinkProperties", mike_admin);
    Fortress fortress =
        fortressService.registerFortress(
            su.getCompany(), new FortressInputBean("testEntityConceptsLinkProperties", true));

    EntityInputBean staff =
        new EntityInputBean(fortress, "wally", "Staff", new DateTime(), "ABC123");

    mediationFacade.trackEntity(su.getCompany(), staff);
    assertEquals(1, conceptService.getDocumentsInUse(su.getCompany()).size());

    // Checking that the entity is linked when part of the track request
    EntityInputBean workRecord =
        new EntityInputBean(fortress, "wally", "Work", new DateTime(), "ABC321")
            .addTag(new TagInputBean("someTag", "SomeLabel", "somerlx"))
            .addEntityLink(
                "worked",
                new EntityKeyBean("Staff", fortress.getName(), "ABC123")
                    .setRelationshipName("worked")
                    .setParent(true));

    mediationFacade.trackEntity(su.getCompany(), workRecord);
    assertEquals(2, conceptService.getDocumentsInUse(su.getCompany()).size());

    Collection<String> docs = new ArrayList<>();
    docs.add("Staff");
    docs.add("Work");
    Set<DocumentResultBean> documentResults =
        conceptService.findConcepts(su.getCompany(), docs, true);
    assertEquals(2, documentResults.size());
    MatrixResults structure =
        conceptService.getContentStructure(su.getCompany(), fortress.getName());
    assertEquals(3, structure.getNodes().size());
    assertEquals(2, structure.getEdges().size());
    for (EdgeResult edgeResult : structure.getEdges()) {
      if (edgeResult.getRelationship().equals("worked")) { // EntityLink relationship
        assertTrue("parent property was not set", edgeResult.getData().containsKey("parent"));
        assertTrue(
            "Parent not true", Boolean.parseBoolean(edgeResult.getData().get("parent").toString()));
      }
    }
    // We should be able to find that a Staff entity has a worked link to a Timesheet
  }
  @Test
  public void documentType_InputThroughToDb() throws Exception {
    // DAT-540
    DocumentTypeInputBean documentTypeInputBean =
        new DocumentTypeInputBean("DTIB")
            .getVersionStrategy(DocumentType.VERSION.DISABLE)
            .setTagStructure(EntityService.TAG_STRUCTURE.TAXONOMY)
            .setGeoQuery("Testing GeoQuery");

    String json = JsonUtils.toJson(documentTypeInputBean);
    documentTypeInputBean = JsonUtils.toObject(json.getBytes(), DocumentTypeInputBean.class);

    Fortress fortress = new Fortress(new FortressInputBean("DocTypes"), new Company("Testing"));
    DocumentType documentType =
        new DocumentType(fortress.getDefaultSegment(), documentTypeInputBean);
    TestCase.assertEquals(EntityService.TAG_STRUCTURE.TAXONOMY, documentType.getTagStructure());
    TestCase.assertEquals(DocumentType.VERSION.DISABLE, documentType.getVersionStrategy());
    TestCase.assertEquals("Testing GeoQuery", documentType.getGeoQuery());
  }
  //    @Test
  // @Repeat(value = 1)
  public void entitiesUnderLoad() throws Exception {
    // This test suffered under DAT-348 and was quarantined.
    String companyName = "entitiesUnderLoad";
    setSecurity();
    SystemUser su = registerSystemUser(companyName, "entitiesUnderLoad");

    Fortress fortress =
        fortressService.registerFortress(
            su.getCompany(), new FortressInputBean("entitiesUnderLoad", true));
    String docType = "entitiesUnderLoad";

    int tagCount = 1; // unique tags per entity - tags are shared across the entities
    int docCount = 1; // how many entities to create per thread
    // Tried reducing threadMax
    int threadMax = 3; // Each thread will create a unique document type
    ArrayList<TagInputBean> tags = getTags(tagCount, false);

    Collection<Tag> createdTags =
        tagService.findTags(fortress.getCompany(), tags.get(0).getLabel());
    assertEquals("Database is not in a cleared down state", 0, createdTags.size());

    Map<Integer, EntityRunner> runners = new HashMap<>();

    CountDownLatch latch = new CountDownLatch(threadMax);
    CountDownLatch startSignal = new CountDownLatch(1);
    for (int thread = 0; thread < threadMax; thread++) {
      EntityRunner runner =
          addEntityRunner(
              thread + 1,
              su,
              fortress,
              docType,
              "ABC" + thread,
              docCount,
              tags,
              latch,
              startSignal);
      runners.put(thread, runner);
    }
    startSignal.countDown();
    latch.await();
    Tag found = null;

    for (int thread = 0; thread < threadMax; thread++) {
      assertEquals("Thread " + (thread + 1), true, runners.get(thread).isWorked());
      for (int count = 0; count < docCount; count++) {
        // Thread.sleep(2000);
        Entity entity =
            entityService.findByCode(
                su.getCompany(), fortress.getName(), docType, "ABC" + thread + "" + count);
        assertNotNull(entity);
        Collection<EntityTag> entityTags = entityTagService.findEntityTags(entity);
        if (entityTags.size() == 0) {
          logger.debug("Why is this 0?");
        }
        assertEquals(tagCount, entityTags.size());
        // Make sure every thread's tags point to the same tag
        if (found == null) found = entityTags.iterator().next().getTag();
        else
          assertEquals(
              found.toString() + " / " + entityTags.iterator().next().getTag().toString(),
              found.getId(),
              entityTags.iterator().next().getTag().getId());
      }
    }
    assertNotNull(
        tagService.findTag(fortress.getCompany(), "Deadlock", null, tags.get(0).getCode()));

    createdTags = tagService.findTags(fortress.getCompany(), "Deadlock");
    assertEquals(false, createdTags.isEmpty());
    if (createdTags.size() != tagCount) {

      for (Tag createdTag : createdTags) {
        // logger.info(createdTag.toString());
        logger.info("Finding... {}", createdTag.toString());
        Tag xtra =
            tagService.findTag(su.getCompany(), createdTag.getLabel(), null, createdTag.getCode());

        logger.info(xtra.toString());
      }
    }
    assertEquals(tagCount, createdTags.size());
  }