public void contextInitialized(ServletContextEvent sce) {
    try {
      ServletContext ctx = sce.getServletContext();

      // If the DATA_DIR directory doesn't exist no migration check will be done.
      // This is a normal situation for Vitro.
      File updateDirectory = new File(ctx.getRealPath(DATA_DIR));
      if (!updateDirectory.exists()) {
        log.debug(
            "Directory "
                + ctx.getRealPath(DATA_DIR)
                + " does not exist, no migration check will be attempted.");
        return;
      }

      String logFileName = DATA_DIR + LOG_DIR + timestampedFileName("knowledgeBaseUpdate", "log");
      String errorLogFileName =
          DATA_DIR + LOG_DIR + timestampedFileName("knowledgeBaseUpdate.error", "log");

      UpdateSettings settings = new UpdateSettings();
      settings.setAskUpdatedQueryFile(getAskUpdatedQueryPath(ctx));
      settings.setDataDir(ctx.getRealPath(DATA_DIR));
      settings.setSparqlConstructAdditionsDir(ctx.getRealPath(SPARQL_CONSTRUCT_ADDITIONS_DIR));
      settings.setSparqlConstructDeletionsDir(ctx.getRealPath(SPARQL_CONSTRUCT_DELETIONS_DIR));
      settings.setDiffFile(ctx.getRealPath(DIFF_FILE));
      settings.setSuccessAssertionsFile(ctx.getRealPath(SUCCESS_ASSERTIONS_FILE));
      settings.setSuccessRDFFormat(SUCCESS_RDF_FORMAT);
      settings.setLogFile(ctx.getRealPath(logFileName));
      settings.setErrorLogFile(ctx.getRealPath(errorLogFileName));
      settings.setAddedDataFile(ctx.getRealPath(ADDED_DATA_FILE));
      settings.setRemovedDataFile(ctx.getRealPath(REMOVED_DATA_FILE));
      WebappDaoFactory wadf = (WebappDaoFactory) ctx.getAttribute("webappDaoFactory");
      settings.setDefaultNamespace(wadf.getDefaultNamespace());
      settings.setAssertionOntModelSelector(ModelContext.getBaseOntModelSelector(ctx));
      settings.setInferenceOntModelSelector(ModelContext.getInferenceOntModelSelector(ctx));
      settings.setUnionOntModelSelector(ModelContext.getUnionOntModelSelector(ctx));
      boolean tryMigrateDisplay = true;
      try {
        settings.setDisplayModel(ModelContext.getDisplayModel(ctx));
        OntModel oldTBoxModel = loadModelFromDirectory(ctx.getRealPath(OLD_TBOX_MODEL_DIR));
        settings.setOldTBoxModel(oldTBoxModel);
        OntModel newTBoxModel = loadModelFromDirectory(ctx.getRealPath(NEW_TBOX_MODEL_DIR));
        settings.setNewTBoxModel(newTBoxModel);
        OntModel oldTBoxAnnotationsModel =
            loadModelFromDirectory(ctx.getRealPath(OLD_TBOX_ANNOTATIONS_DIR));
        settings.setOldTBoxAnnotationsModel(oldTBoxAnnotationsModel);
        OntModel newTBoxAnnotationsModel =
            loadModelFromDirectory(ctx.getRealPath(NEW_TBOX_ANNOTATIONS_DIR));
        settings.setNewTBoxAnnotationsModel(newTBoxAnnotationsModel);
        // Display model tbox and display metadata
        // old display model tbox model
        OntModel oldDisplayModelTboxModel =
            loadModelFromFile(ctx.getRealPath(OLD_DISPLAYMODEL_TBOX_PATH));
        settings.setOldDisplayModelTboxModel(oldDisplayModelTboxModel);
        // new display model tbox model
        OntModel newDisplayModelTboxModel =
            loadModelFromFile(ctx.getRealPath(NEW_DISPLAYMODEL_TBOX_PATH));
        settings.setNewDisplayModelTboxModel(newDisplayModelTboxModel);
        // old display model display model metadata
        OntModel oldDisplayModelDisplayMetadataModel =
            loadModelFromFile(ctx.getRealPath(OLD_DISPLAYMODEL_DISPLAYMETADATA_PATH));
        settings.setOldDisplayModelDisplayMetadataModel(oldDisplayModelDisplayMetadataModel);
        // new display model display model metadata
        OntModel newDisplayModelDisplayMetadataModel =
            loadModelFromFile(ctx.getRealPath(NEW_DISPLAYMODEL_DISPLAYMETADATA_PATH));
        settings.setNewDisplayModelDisplayMetadataModel(newDisplayModelDisplayMetadataModel);
        // Get new display model
        OntModel newDisplayModelFromFile =
            loadModelFromFile(ctx.getRealPath(NEW_DISPLAYMODEL_PATH));
        settings.setNewDisplayModelFromFile(newDisplayModelFromFile);
        OntModel loadedAtStartupFiles =
            loadModelFromDirectory(ctx.getRealPath(LOADED_STARTUPT_DISPLAYMODEL_DIR));
        settings.setLoadedAtStartupDisplayModel(loadedAtStartupFiles);
        OntModel oldDisplayModelVivoListView =
            loadModelFromFile(ctx.getRealPath(OLD_DISPLAYMODEL_VIVOLISTVIEW_PATH));
        settings.setVivoListViewConfigDisplayModel(oldDisplayModelVivoListView);
      } catch (Exception e) {
        log.info(
            "unable to read display model migration files, display model not migrated. "
                + e.getMessage());
        tryMigrateDisplay = false;
      }

      try {
        KnowledgeBaseUpdater ontologyUpdater = new KnowledgeBaseUpdater(settings);

        try {
          if (ontologyUpdater.updateRequired(ctx)) {
            ctx.setAttribute(KBM_REQURIED_AT_STARTUP, Boolean.TRUE);
            ontologyUpdater.update(ctx);
            if (tryMigrateDisplay) {
              try {
                migrateDisplayModel(settings);
                log.info("Migrated display model");
              } catch (Exception e) {
                log.warn("unable to successfully update display model: " + e.getMessage());
              }
            }
          }
        } catch (Exception ioe) {
          String errMsg = "Exception updating knowledge base " + "for ontology changes: ";
          // Tomcat doesn't always seem to print exceptions thrown from
          // context listeners
          System.out.println(errMsg);
          ioe.printStackTrace();
          throw new RuntimeException(errMsg, ioe);
        }
      } catch (Throwable t) {
        log.warn("warning", t);
      }
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    try {
      // set up Pellet reasoning for the TBox

      OntModelSelector assertionsOms =
          ModelContext.getBaseOntModelSelector(sce.getServletContext());
      OntModelSelector inferencesOms =
          ModelContext.getInferenceOntModelSelector(sce.getServletContext());
      OntModelSelector unionOms = ModelContext.getUnionOntModelSelector(sce.getServletContext());

      WebappDaoFactoryJena wadf =
          (WebappDaoFactoryJena) sce.getServletContext().getAttribute("webappDaoFactory");

      if (!assertionsOms
          .getTBoxModel()
          .getProfile()
          .NAMESPACE()
          .equals(OWL.NAMESPACE.getNameSpace())) {
        log.error("Not connecting Pellet reasoner - the TBox assertions model is not an OWL model");
        return;
      }

      // Set various Pellet options for incremental consistency checking, etc.
      PelletOptions.DL_SAFE_RULES = true;
      PelletOptions.USE_COMPLETION_QUEUE = true;
      PelletOptions.USE_TRACING = true;
      PelletOptions.TRACK_BRANCH_EFFECTS = true;
      PelletOptions.USE_INCREMENTAL_CONSISTENCY = true;
      PelletOptions.USE_INCREMENTAL_DELETION = true;

      PelletListener pelletListener =
          new PelletListener(
              unionOms.getTBoxModel(),
              assertionsOms.getTBoxModel(),
              inferencesOms.getTBoxModel(),
              ReasonerConfiguration.DEFAULT);
      sce.getServletContext().setAttribute("pelletListener", pelletListener);
      sce.getServletContext().setAttribute("pelletOntModel", pelletListener.getPelletModel());

      if (wadf != null) {
        wadf.setPelletListener(pelletListener);
      }

      log.info("Pellet reasoner connected for the TBox");

      // set up simple reasoning for the ABox

      ServletContext ctx = sce.getServletContext();
      BasicDataSource bds = JenaDataSourceSetupBase.getApplicationDataSource(ctx);
      String dbType =
          ConfigurationProperties.getBean(ctx)
              .getProperty( // database type
                  "VitroConnection.DataSource.dbtype", "MySQL");

      Model rebuildModel =
          JenaDataSourceSetupBase.makeDBModel(
              bds,
              JENA_INF_MODEL_REBUILD,
              JenaDataSourceSetupBase.DB_ONT_MODEL_SPEC,
              TripleStoreType.SDB,
              dbType,
              ctx);
      Model scratchModel =
          JenaDataSourceSetupBase.makeDBModel(
              bds,
              JENA_INF_MODEL_SCRATCHPAD,
              JenaDataSourceSetupBase.DB_ONT_MODEL_SPEC,
              TripleStoreType.SDB,
              dbType,
              ctx);

      // the simple reasoner will register itself as a listener to the ABox assertions
      SimpleReasoner simpleReasoner =
          new SimpleReasoner(
              unionOms.getTBoxModel(),
              assertionsOms.getABoxModel(),
              inferencesOms.getABoxModel(),
              rebuildModel,
              scratchModel);
      sce.getServletContext().setAttribute(SimpleReasoner.class.getName(), simpleReasoner);

      StartupStatus ss = StartupStatus.getBean(ctx);
      List<ReasonerPlugin> pluginList = new ArrayList<ReasonerPlugin>();
      List<String> pluginClassnameList = this.readFileOfListeners(ctx);
      for (String classname : pluginClassnameList) {
        try {
          ReasonerPlugin plugin =
              (ReasonerPlugin) Class.forName(classname).getConstructors()[0].newInstance();
          pluginList.add(plugin);
        } catch (Throwable t) {
          ss.info(this, "Could not instantiate reasoner plugin " + classname);
        }
      }
      simpleReasoner.setPluginList(pluginList);

      if (isRecomputeRequired(sce.getServletContext())) {
        log.info("ABox inference recompute required.");
        waitForTBoxReasoning(pelletListener);
        if (JenaDataSourceSetupBase.isFirstStartup()) {
          simpleReasoner.recompute();
        } else {
          log.info("starting ABox inference recompute in a separate thread.");
          new Thread(new ABoxRecomputer(simpleReasoner), "ABoxRecomputer").start();
        }

      } else if (isMSTComputeRequired(sce.getServletContext())) {
        log.info("mostSpecificType computation required. It will be done in a separate thread.");
        waitForTBoxReasoning(pelletListener);
        new Thread(new MostSpecificTypeRecomputer(simpleReasoner), "MostSpecificTypeComputer")
            .start();
      }

      SimpleReasonerTBoxListener simpleReasonerTBoxListener =
          new SimpleReasonerTBoxListener(simpleReasoner);
      sce.getServletContext()
          .setAttribute(SimpleReasonerTBoxListener.class.getName(), simpleReasonerTBoxListener);
      assertionsOms.getTBoxModel().register(simpleReasonerTBoxListener);
      inferencesOms.getTBoxModel().register(simpleReasonerTBoxListener);

      log.info("Simple reasoner connected for the ABox");

    } catch (Throwable t) {
      t.printStackTrace();
    }
  }