/** Uses the classes from the DB to write the RDF files based on those. */
  public static void writeSemanticModelFiles() {
    logger.debug("Writing the context model to a file");

    // TODO: Complement the model with the other required entities
    OntModel usersModel = writeUserEntries();
    OntModel projectsModel = writeProjectEntries();
    OntModel metadataModel = writeMetaDataModelEntries();

    //	uqModel.write(System.out, "RDF/XML");
    //	RDFDataMgr.write(System.out, uqModel, RDFFormat.RDFXML_PRETTY);

    // Write the individual models to a single file
    // holding all the triples
    final OntModel combined = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    for (final OntModel part : new OntModel[] {usersModel, projectsModel, metadataModel}) {
      combined.add(part);
    }
    try {
      String dataDir = UQasarUtil.getDataDirPath();
      // TODO: Find out why this does not work in Linux
      //			String modelPath = "file:///" + dataDir + ONTOLOGYFILE;
      String modelPath = dataDir + ONTOLOGYFILE;

      combined.write(new FileOutputStream(modelPath, false));
      logger.debug("Context Model written to file " + modelPath);
      UQasarUtil.setUqModel(combined);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** Read the RDF model from files. */
  public static void readSemanticModelFiles() {
    logger.debug("Reading the model from a file");
    // Read the model to an existing model
    String dataDir = UQasarUtil.getDataDirPath();
    String modelPath = "file:///" + dataDir + ONTOLOGYFILE;
    //		String modelPath =
    // "file:///C:/nyrhinen/Programme/jboss-as-7.1.1.Final/standalone/data/uq-ontology-model.rdf";

    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    RDFDataMgr.read(model, modelPath);
    // Test output to standard output
    //		RDFDataMgr.write(System.out, uqModel, RDFFormat.RDFXML_PRETTY);
    logger.debug("Model read from file " + modelPath);
    UQasarUtil.setUqModel(model);
    System.out.println("Reading done.");
  }
  @Deployment
  public static JavaArchive createDefaultArchive() {
    JavaArchive archive =
        SeamCronSchedulingTCKTestLong.createSchedulingTckTestArchive()
            .addPackages(true, QuartzScheduleProvider.class.getPackage());

    log.debug(archive.toString(true));
    return archive;
  }
  /**
   * Traverse the tree in postorder and update tree values
   *
   * @param node
   */
  private static void postorderWithParticularNode(TreeNode node, TreeNode projectTreeNode) {

    if (node == null) {
      return;
    }

    if (projectTreeNode == null) {
      return;
    }

    logger.debug("------------postorder: " + projectTreeNode.getName() + "---------------");

    logger.debug("Traversing project tree in postorder..." + projectTreeNode.toString());
    // Update the value
    try {
      InitialContext ic = new InitialContext();
      AdapterDataService adapterDataService = new AdapterDataService();
      TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");

      if (projectTreeNode instanceof Metric) {
        Metric metric = (Metric) projectTreeNode;
        logger.debug("Recomputing the value of the Metric " + projectTreeNode);
        Float value = null;
        if (metric.getMetricSource() == MetricSource.Manual) {
          metric.updateQualityStatus();
        } else {
          value =
              adapterDataService.getMetricValue(
                  metric.getMetricSource(), metric.getMetricType(), metric.getProject());
          metric.setValue(value);
        }
        metric.setLastUpdated(getLatestTreeUpdateDate());
        metric.addHistoricValue();
        // End Metric node treatment
      } else if (projectTreeNode instanceof QualityIndicator) {
        logger.info("Recomputing the value of the Quality Indicator " + projectTreeNode);
        QualityIndicator qi = (QualityIndicator) projectTreeNode;
        if (qi.getUseFormula()) {
          String formulaToEval = Formula.parseFormula(qi.getViewFormula());
          if (formulaToEval != null && !formulaToEval.isEmpty()) {

            Float computedValue = Formula.evalFormula(formulaToEval);
            if (computedValue != null && !computedValue.isNaN()) {
              qi.setValue(computedValue);
              qi.setLastUpdated(getLatestTreeUpdateDate());
              treeNodeService.update(qi);
            }
          }
        } else {
          float achieved = 0;
          float denominator = 0;
          for (final TreeNode me : qi.getChildren()) {
            float weight = ((Metric) me).getWeight();
            if (me.getQualityStatus() == QualityStatus.Green) {
              achieved += weight;
            }
            denominator += weight;
          }
          if (denominator == 0) qi.getChildren().size();
          qi.setValue(achieved * 100 / denominator);
        }
        qi.setLastUpdated(getLatestTreeUpdateDate());
        qi.addHistoricValue();
        // End Q.Indicator node treatment
      } else if (projectTreeNode instanceof QualityObjective) {
        logger.info("Recomputing the value of the Quality Objective " + projectTreeNode);
        QualityObjective qo = (QualityObjective) projectTreeNode;
        if (qo.getUseFormula()) {
          String formulaToEval = Formula.parseFormula(qo.getViewFormula());
          if (formulaToEval != null && !formulaToEval.isEmpty()) {

            Float computedValue = Formula.evalFormula(formulaToEval);
            if (computedValue != null && !computedValue.isNaN()) {
              qo.setValue(computedValue);
              qo.setLastUpdated(getLatestTreeUpdateDate());
            }
          }
        } else {
          float denominator = 0;
          float achieved = 0;
          for (final TreeNode qi : qo.getChildren()) {
            float weight = ((QualityIndicator) qi).getWeight();
            if (qi.getQualityStatus() == QualityStatus.Green) {
              achieved += weight;
            }
            denominator += weight;
          }
          qo.setValue(achieved * 100 / denominator);
        }
        qo.setLastUpdated(getLatestTreeUpdateDate());
        qo.addHistoricValue();
        // End Quality Objective node treatment
      } else if (projectTreeNode instanceof Project) {
        logger.info("Recomputing the value of the Project " + projectTreeNode);
        Project prj = (Project) projectTreeNode;
        double qoValueSum = 0;
        double denominator = 0;
        for (Object o : projectTreeNode.getChildren()) {
          QualityObjective qo = (QualityObjective) o;
          if (qo.getWeight() == 0) {
            continue;
          }
          qoValueSum += qo.getValue() * (prj.isFormulaAverage() ? qo.getWeight() : 1);
          denominator += prj.isFormulaAverage() ? qo.getWeight() : 1;
        }

        // bad idea to divide something under 0
        if (denominator == 0) {
          denominator = 1;
        }

        Double computedValue = qoValueSum / denominator;

        if (computedValue != null && !computedValue.isNaN() && !computedValue.isInfinite()) {
          prj.setValue(computedValue);
        }

        prj.setLastUpdated(getLatestTreeUpdateDate());
        prj.addHistoricValue();
        logger.debug(" [" + qoValueSum + "] denominator [" + denominator + "] " + computedValue);
        // End Project node treatment
      }

      // Get a (possible) suggestion for the tree node
      Multimap<?, ?> suggestions = getSuggestionForNode(projectTreeNode);
      // TODO: take all the suggestions into account
      Object[] types = suggestions.keys().toArray();
      Object[] suggestionsValues = suggestions.values().toArray();
      if (types.length > 0) {
        // for now use the first item as suggestion
        SuggestionType stype = (SuggestionType) types[0];
        projectTreeNode.setSuggestionType(stype);
        if (suggestionsValues[0] != null && !suggestionsValues[0].equals("")) {
          projectTreeNode.setSuggestionValue((String) suggestionsValues[0]);
        }
      }

      treeNodeService.update(projectTreeNode);

    } catch (NamingException e) {
      e.printStackTrace();
    }

    // Iterate the node children
    TreeNode nodeChild = projectTreeNode.getParent();
    UQasarUtil.postorderWithParticularNode(projectTreeNode, nodeChild);

    return;
  }