/** 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();
    }
  }
  @Override
  public void doSearch() {
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<QuestionType> cquery = builder.createQuery(QuestionType.class);
    Root<QuestionType> rqt = cquery.from(QuestionType.class);

    cquery
        .select(rqt)
        .where(
            builder.like(
                builder.lower(rqt.get(QuestionType_.name)), searchCriteria.getSearchPattern()));

    List<QuestionType> results =
        em.createQuery(cquery)
            .setMaxResults(searchCriteria.getFetchSize())
            .setFirstResult(searchCriteria.getFetchOffset())
            .getResultList();

    nextPageAvailable = results.size() > searchCriteria.getPageSize();
    if (nextPageAvailable) {
      // NOTE create new ArrayList since subList creates unserializable list
      questionTypes = new ArrayList<QuestionType>(results.subList(0, searchCriteria.getPageSize()));
    } else {
      questionTypes = results;
    }
    log.info(
        messageBuilder
            .get()
            .text("Found {0} hotel(s) matching search term [ {1} ] (limit {2})")
            .textParams(
                questionTypes.size(), searchCriteria.getQuery(), searchCriteria.getPageSize())
            .build()
            .getText());
  }
 /** Test a null formula */
 @Test
 public void testNullFormula() {
   logger.info("Test null Formula");
   String formula = null;
   Object resObject = Formula.evalFormula(formula);
   Assert.assertNull(resObject);
 }
 /**
  * Takes care of computing the tree values (update metrics and compute QO/QI values based on that)
  * starting from the root node.
  *
  * @param projectRoot Node
  */
 public static void updateTreeWithParticularNode(TreeNode projectRoot, TreeNode projectTreeNode) {
   // Create a timestamp at the start of the tree update so that
   // all the updated entities have the same value for the date.
   setLatestTreeUpdateDate(new Date());
   logger.info("Updating the QA Project tree...");
   postorderWithParticularNode(projectRoot, projectTreeNode);
 }
public class FormulaTest {

  private static Logger logger = Logger.getLogger(FormulaTest.class);

  /** Test evaluation of a valid formula string. */
  @Test
  public void testEvalFormulaStr() {

    logger.info("Test eval formula String");

    Double expected = 15.0;
    String evalStr = "5*3";
    Object resObject = Formula.evalFormulaStr(evalStr);
    Assert.assertNotNull(resObject);
    Double result = (Double) resObject;
    Assert.assertEquals(expected, result);
  }

  /** Test a null formula */
  @Test
  public void testNullFormula() {
    logger.info("Test null Formula");
    String formula = null;
    Object resObject = Formula.evalFormula(formula);
    Assert.assertNull(resObject);
  }

  /** Test an invalid formula; should return null value */
  public void testInvalidFormula() {
    logger.info("Test invalid Formula");
    String formula = "ax";
    Object resObject = Formula.evalFormula(formula);
    Assert.assertNull(resObject);
  }
}
  /** 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.");
  }
/**
 * Provide CDI injection to SystemEventListener artifacts by delegating through this class.
 *
 * @author <a href="mailto:[email protected]>Lincoln Baxter, III</a>
 */
public class DelegatingSystemEventListener extends AbstractListener<SystemEventListener>
    implements SystemEventListener {
  private final transient Logger log = Logger.getLogger(DelegatingSystemEventListener.class);

  @Override
  public boolean isListenerForSource(final Object source) {
    return true;
  }

  @Override
  public void processEvent(final SystemEvent event) throws AbortProcessingException {
    if (event instanceof PreDestroyApplicationEvent && !isBeanManagerAvailable()) {
      log.info(
          "BeanManager no longer available; Cannot notify CDI-managed listeners of "
              + PreDestroyApplicationEvent.class.getSimpleName());
      return;
    }

    for (SystemEventListener l : getEventListeners()) {
      if (l.isListenerForSource(event.getSource())) {
        l.processEvent(event);
      }
    }
  }

  @SuppressWarnings("unchecked")
  private List<SystemEventListener> getEventListeners() {
    return getListeners(SystemEventBridge.class);
  }
}
  private DataView<LdapUser> newGroupMembersListView(LdapGroup group) {
    List<LdapUser> users;
    try {
      users = group.getMembers();
    } catch (NamingException e) {
      logger.warn(e.getMessage(), e);
      users = new ArrayList<>(0);
    }
    DataView<LdapUser> members =
        new DataView<LdapUser>("membersList", new LdapGroupUsersProvider(users)) {

          @Override
          protected void populateItem(Item<LdapUser> item) {
            LdapUser user = item.getModelObject();
            WebMarkupContainer container = new WebMarkupContainer("member");
            ExternalLink mail =
                new ExternalLink(
                    "mail", Model.of("mailto:" + user.getMail()), new PropertyModel(user, "mail"));
            Label userName = new Label("username", new PropertyModel(user, "userName"));
            final String fullName = user.getFullName();
            Label fullNameLabel = new Label("fullname", Model.of(fullName));
            fullNameLabel.setVisible(fullName != null);
            container.add(mail);
            container.add(userName);
            container.add(fullNameLabel);
            item.add(container);
          }
        };
    members.setOutputMarkupId(true);
    return members;
  }
  @Deployment
  public static JavaArchive createDefaultArchive() {
    JavaArchive archive =
        SeamCronSchedulingTCKTestLong.createSchedulingTckTestArchive()
            .addPackages(true, QuartzScheduleProvider.class.getPackage());

    log.debug(archive.toString(true));
    return archive;
  }
 /**
  * Handles the exception thrown at the end of a conversation redirecting the flow to a pretty page
  * instead of printing a stacktrace on the screen.
  *
  * @param event
  * @param log
  */
 public void conversationEndedExceptionHandler(
     @Handles CaughtException<NonexistentConversationException> event, Logger log) {
   log.info("Conversation ended: " + event.getException().getMessage());
   try {
     facesContext.getExternalContext().redirect("conversation_ended");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Esempio n. 11
0
 @End
 public String confirmOrder() {
   order.setCreationDate(new Date());
   for (Pizza pizza : order.getPizzas()) em.persist(pizza);
   em.persist(order);
   log.infov(
       "Order {0} placed by {1} with {2} pizzas",
       order.getId(), user.getUsername(), order.getPizzas().size());
   return "completed";
 }
  /**
   * Construct a formula string to be evaluated.
   *
   * @param varsAndOpers
   * @return
   */
  public static String constructFormula(List<Object> varsAndOpers) {
    String formula = "";

    for (Object object : varsAndOpers) {
      formula += object;
    }

    logger.info("Constructed formula to be evaluated: " + formula);
    return formula;
  }
  // Injecting HttpServletRequest instead of HttpSession as the latter conflicts with a Weld bean on
  // GlassFish 3.0.1
  public void onLogin(@Observes @Authenticated UserLogin user, HttpServletRequest request) {
    currentUser = user;
    log.infov(
        "set current UserLogin,userId={0},loginName={1},userName={2}",
        currentUser.getUserId(), currentUser.getLoginName(), currentUser.getUserName());

    checkPermission(currentUser.getUserId());
    // reward authenticated users with a longer session
    // default is kept short to prevent search engines from driving up # of sessions
    // request.getSession().setMaxInactiveInterval(3600);
  }
  /** Test evaluation of a valid formula string. */
  @Test
  public void testEvalFormulaStr() {

    logger.info("Test eval formula String");

    Double expected = 15.0;
    String evalStr = "5*3";
    Object resObject = Formula.evalFormulaStr(evalStr);
    Assert.assertNotNull(resObject);
    Double result = (Double) resObject;
    Assert.assertEquals(expected, result);
  }
  public void upload() {

    try {
      byte[] buffer = new byte[(int) file.getSize()];
      this.getInstance().setRadiografiaDental(buffer);
      FacesMessage msg =
          new FacesMessage("Ok", "Fichero " + file.getFileName() + " subido correctamente.");
      FacesContext.getCurrentInstance().addMessage(null, msg);
    } catch (Exception e) {
      log.info("Consulta Odont: Error al cargar la imagen");
    }
  }
 public void conversationEndedExceptionHandler(
     @Handles(precedence = 100) CaughtException<ViewExpiredException> event,
     Logger log,
     HttpConversationContext conversationContext,
     FacesContext facesContext) {
   log.warn("View expired, redirecting to error page");
   conversationContext.activate(null);
   event.handled();
   facesContext
       .getApplication()
       .getNavigationHandler()
       .handleNavigation(facesContext, "*", "viewExpired");
 }
  @Override
  public void processEvent(final SystemEvent event) throws AbortProcessingException {
    if (event instanceof PreDestroyApplicationEvent && !isBeanManagerAvailable()) {
      log.info(
          "BeanManager no longer available; Cannot notify CDI-managed listeners of "
              + PreDestroyApplicationEvent.class.getSimpleName());
      return;
    }

    for (SystemEventListener l : getEventListeners()) {
      if (l.isListenerForSource(event.getSource())) {
        l.processEvent(event);
      }
    }
  }
  public void checkPermission(Integer id) {

    log.info("--------------- id " + id);
    check1 = true;
    check2 = false;
    check3 = false;
    //		try {
    //			String qr = " select ur.role_id " +
    //					" from user u " +
    //					" left join user_role ur on(ur.user_id = u.user_id) " +
    //					" left join role ro on(ro.role_id = ur.role_id) " +
    //					" where u.user_id = "+ id ;
    //
    //			check = em.createNativeQuery(qr).getSingleResult().toString();
    //			log.info("--------------- check "+check);
    //			if(check.equals("1")){
    //
    //				check1 = true;
    //				check2 = false; // test
    //				check3 = false;
    //
    //			}else if(check.equals("2")){
    //
    //				check1 = false;
    //				check2 = true; // test
    //				check3 = false;
    //
    //			}else if(check.equals("3")){
    //
    //				check1 = false;
    //				check2 = false; // test
    //				check3 = true;
    //			}
    //
    //
    //			log.info(check1);
    //			log.info(check2);
    //			log.info(check3);
    //
    //		} catch (Exception e) {
    //			e.printStackTrace();
    //		}

  }
Esempio n. 19
0
  public void start() {
    log.infof("Starting HeartbeatEmitter. Observe the HeartbeatEvent to subscribe.", Instant.now());

    final Runnable emitter =
        new Runnable() {
          @Override
          public void run() {
            try {
              log.debugf("heartbeat: %s", Instant.now());
              heartbeat.fire(new HeartbeatEvent());
            } catch (Exception e) {
              log.error(e);
            }
          }
        };

    emitterHandle =
        scheduler.scheduleAtFixedRate(emitter, initialDelay, periodInSeconds, TimeUnit.SECONDS);
  }
  @Override
  public List<BussinesEntityType> load(
      int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {

    log.info("load results for ..." + first + ", " + pageSize);

    int end = first + pageSize;

    QuerySortOrder order = QuerySortOrder.ASC;
    if (sortOrder == SortOrder.DESCENDING) {
      order = QuerySortOrder.DESC;
    }
    Map<String, Object> _filters = new HashMap<String, Object>();
    /*_filters.put(BussinesEntityType_.name, getSelectedBussinesEntityType()); //Filtro por defecto
    _filters.putAll(filters);*/

    QueryData<BussinesEntityType> qData =
        bussinesEntityTypeService.find(first, end, sortField, order, _filters);
    this.setRowCount(qData.getTotalResultCount().intValue());
    return qData.getResult();
  }
  public Message build() {
    String text;
    String detail = null;
    try {
      text = bundles.get(clientLocale, textKey.getBundle()).getString(textKey.getKey());
      if (detailKey != null) {
        detail = bundles.get(clientLocale, detailKey.getBundle()).getString(detailKey.getKey());
      }
    } catch (Exception e) {
      log.warn("Could not load bundle: " + textKey);
      text = textDefault;
    }

    if ((text == null) || "".equals(text)) {
      text = textKey.toString();
    }

    template.text(text);
    if (detail != null) {
      template.detail(detail);
    }
    return template.build();
  }
 public void setFirstResult(int firstResult) {
   log.info("set first result + firstResult");
   this.firstResult = firstResult;
   this.resultList = null;
 }
/** @author cesar */
@RequestScoped
@Named
public class BussinesEntityTypeListService extends LazyDataModel<BussinesEntityType> {

  private static final long serialVersionUID = 4819808125494695200L;
  private static final int MAX_RESULTS = 5;
  private static org.jboss.solder.logging.Logger log =
      org.jboss.solder.logging.Logger.getLogger(BussinesEntityTypeListService.class);
  @Inject @Web private EntityManager entityManager;
  @Inject private BussinesEntityTypeService bussinesEntityTypeService;
  private List<BussinesEntityType> resultList;
  private int firstResult = 0;
  private BussinesEntityType[] selectedBussinesEntitiesType;
  private BussinesEntityType selectedBussinesEntityType; // Filtro de cuenta schema

  public BussinesEntityTypeListService() {
    setPageSize(MAX_RESULTS);
    resultList = new ArrayList<BussinesEntityType>();
  }

  public List<BussinesEntityType> getResultList() {
    if (resultList.isEmpty() /*&& getSelectedBussinesEntityType() != null*/) {
      resultList = bussinesEntityTypeService.find(this.getPageSize(), firstResult);
    }

    return resultList;
  }

  public void setResultList(List<BussinesEntityType> resultList) {
    this.resultList = resultList;
  }

  public String find() {
    /*
    try {
    init();
    resultList = bussinesEntityTypeService.findAll();
    String summary = "Encontrados! ";
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null));
    System.out.println("lista "+resultList.get(0));
    } catch (Exception e) {

    }
    */
    this.getResultList();
    return "/pages/admin/bussinesentitytype/list";
  }

  public int getNextFirstResult() {
    return firstResult + this.getPageSize();
  }

  public int getPreviousFirstResult() {
    return this.getPageSize() >= firstResult ? 0 : firstResult - this.getPageSize();
  }

  public int getFirstResult() {
    return firstResult;
  }

  public void setFirstResult(int firstResult) {
    log.info("set first result + firstResult");
    this.firstResult = firstResult;
    this.resultList = null;
  }

  public boolean isPreviousExists() {
    return firstResult > 0;
  }

  @PostConstruct
  public void init() {
    log.info("Setup entityManager into bussinesEntityTypeService...");
    bussinesEntityTypeService.setEntityManager(entityManager);
  }

  @Override
  public BussinesEntityType getRowData(String rowKey) {

    return bussinesEntityTypeService.findByName(rowKey);
  }

  @Override
  public Object getRowKey(BussinesEntityType entity) {
    return entity.getName();
  }

  public BussinesEntityType[] getSelectedBussinesEntitiesType() {
    return selectedBussinesEntitiesType;
  }

  public void setSelectedBussinesEntitiesType(BussinesEntityType[] selectedBussinesEntitiesType) {
    this.selectedBussinesEntitiesType = selectedBussinesEntitiesType;
  }

  public BussinesEntityType getSelectedBussinesEntityType() {
    return selectedBussinesEntityType;
  }

  public void setSelectedBussinesEntityType(BussinesEntityType selectedBussinesEntityType) {
    this.selectedBussinesEntityType = selectedBussinesEntityType;
  }

  @Override
  public List<BussinesEntityType> load(
      int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {

    log.info("load results for ..." + first + ", " + pageSize);

    int end = first + pageSize;

    QuerySortOrder order = QuerySortOrder.ASC;
    if (sortOrder == SortOrder.DESCENDING) {
      order = QuerySortOrder.DESC;
    }
    Map<String, Object> _filters = new HashMap<String, Object>();
    /*_filters.put(BussinesEntityType_.name, getSelectedBussinesEntityType()); //Filtro por defecto
    _filters.putAll(filters);*/

    QueryData<BussinesEntityType> qData =
        bussinesEntityTypeService.find(first, end, sortField, order, _filters);
    this.setRowCount(qData.getTotalResultCount().intValue());
    return qData.getResult();
  }

  public void onRowSelect(SelectEvent event) {
    FacesMessage msg =
        new FacesMessage(
            UI.getMessages("module.BussinesEntityType") + " " + UI.getMessages("common.selected"),
            ((BussinesEntityType) event.getObject()).getName());

    FacesContext.getCurrentInstance().addMessage("", msg);
  }

  public void onRowUnselect(UnselectEvent event) {
    FacesMessage msg =
        new FacesMessage(
            UI.getMessages("module.BussinesEntityType") + " " + UI.getMessages("common.unselected"),
            ((BussinesEntityType) event.getObject()).getName());

    FacesContext.getCurrentInstance().addMessage("", msg);
    this.setSelectedBussinesEntityType(null);
  }
}
 @PostConstruct
 public void init() {
   log.info("Setup entityManager into bussinesEntityTypeService...");
   bussinesEntityTypeService.setEntityManager(entityManager);
 }
/**
 * @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
 * @author <a href="mailto:[email protected]">Sebastian Sachtleben</a>
 */
public class BundleTemplateMessageImpl implements BundleTemplateMessage {
  @Inject TemplateMessage template;

  private String textDefault;
  private BundleKey textKey;
  private BundleKey detailKey;

  @Inject ApplicationBundles bundles;

  @Inject @Client Locale clientLocale;

  private final Logger log = Logger.getLogger(BundleTemplateMessageImpl.class);

  public Message build() {
    String text;
    String detail = null;
    try {
      text = bundles.get(clientLocale, textKey.getBundle()).getString(textKey.getKey());
      if (detailKey != null) {
        detail = bundles.get(clientLocale, detailKey.getBundle()).getString(detailKey.getKey());
      }
    } catch (Exception e) {
      log.warn("Could not load bundle: " + textKey);
      text = textDefault;
    }

    if ((text == null) || "".equals(text)) {
      text = textKey.toString();
    }

    template.text(text);
    if (detail != null) {
      template.detail(detail);
    }
    return template.build();
  }

  /*
   * Setters
   */

  public BundleTemplateMessageImpl key(final BundleKey text) {
    this.textKey = text;
    return this;
  }

  public BundleTemplateMessageImpl detail(final BundleKey detailKey) {
    this.detailKey = detailKey;
    return this;
  }

  public BundleTemplateMessage defaults(final String text) {
    this.textDefault = text;
    return this;
  }

  public BundleTemplateMessageImpl params(final Object... textParams) {
    this.template.textParams(textParams);
    return this;
  }

  public BundleTemplateMessageImpl detailParams(final Object... detailParams) {
    this.template.detailParams(detailParams);
    return this;
  }

  public BundleTemplateMessage targets(final String targets) {
    this.template.targets(targets);
    return this;
  }

  public BundleTemplateMessage level(final Level level) {
    this.template.level(level);
    return this;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((template == null) ? 0 : template.hashCode());
    result = prime * result + ((textDefault == null) ? 0 : textDefault.hashCode());
    result = prime * result + ((textKey == null) ? 0 : textKey.hashCode());
    result = prime * result + ((detailKey == null) ? 0 : detailKey.hashCode());
    return result;
  }

  @Override
  public boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    BundleTemplateMessageImpl other = (BundleTemplateMessageImpl) obj;
    if (template == null) {
      if (other.template != null) {
        return false;
      }
    } else if (!template.equals(other.template)) {
      return false;
    }
    if (textDefault == null) {
      if (other.textDefault != null) {
        return false;
      }
    } else if (!textDefault.equals(other.textDefault)) {
      return false;
    }
    if (textKey == null) {
      if (other.textKey != null) {
        return false;
      }
    } else if (!textKey.equals(other.textKey)) {
      return false;
    }
    if (detailKey == null) {
      if (other.detailKey != null) {
        return false;
      }
    } else if (!detailKey.equals(other.detailKey)) {
      return false;
    }
    return true;
  }
}
public class LdapGroupListPanel extends LdapEntityListPanel<LdapGroup> {

  private static final Logger logger = Logger.getLogger(LdapGroupListPanel.class);

  @Inject TeamService teamService;

  public LdapGroupListPanel(String id, LdapManager manager) {
    super(id, new LdapGroupProvider(manager, Integer.MAX_VALUE));
  }

  private WebMarkupContainer newGroupMembersContainer(final String id, LdapGroup group) {
    WebMarkupContainer container = new WebMarkupContainer(id);
    DataView<LdapUser> membersList = newGroupMembersListView(group);
    container.add(membersList);
    return container;
  }

  private DataView<LdapUser> newGroupMembersListView(LdapGroup group) {
    List<LdapUser> users;
    try {
      users = group.getMembers();
    } catch (NamingException e) {
      logger.warn(e.getMessage(), e);
      users = new ArrayList<>(0);
    }
    DataView<LdapUser> members =
        new DataView<LdapUser>("membersList", new LdapGroupUsersProvider(users)) {

          @Override
          protected void populateItem(Item<LdapUser> item) {
            LdapUser user = item.getModelObject();
            WebMarkupContainer container = new WebMarkupContainer("member");
            ExternalLink mail =
                new ExternalLink(
                    "mail", Model.of("mailto:" + user.getMail()), new PropertyModel(user, "mail"));
            Label userName = new Label("username", new PropertyModel(user, "userName"));
            final String fullName = user.getFullName();
            Label fullNameLabel = new Label("fullname", Model.of(fullName));
            fullNameLabel.setVisible(fullName != null);
            container.add(mail);
            container.add(userName);
            container.add(fullNameLabel);
            item.add(container);
          }
        };
    members.setOutputMarkupId(true);
    return members;
  }

  @Override
  public void populateItem(Item<LdapGroup> item, Check<LdapGroup> check) {
    LdapGroup group = item.getModelObject();
    item.add(new Label("name", new PropertyModel(group, "name")));
    item.add(new Label("description", new PropertyModel(group, "description")));
    item.add(newGroupMembersContainer("members", group));

    if (isSelectionEnabled()) {
      if (teamService.ldapBasedGroupExists(group)) {
        check.setVisible(false);
        item.add(new AttributeAppender("class", Model.of("warning")));
        item.add(
            new AttributeAppender(
                "title", new StringResourceModel("table.team.warning.exists", this, null)));
      } else {
        item.add(new AttributeAppender("class", Model.of("success")));
      }
    }
  }

  @Override
  public void selectionChanged(AjaxRequestTarget target) {
    System.out.println("group selection changed");
  }

  private static class LdapGroupUsersProvider implements IDataProvider<LdapUser> {

    private final List<LdapUser> users;

    public LdapGroupUsersProvider(List<LdapUser> users) {
      this.users = users;
    }

    @Override
    public Iterator<? extends LdapUser> iterator(long first, long count) {
      return users.subList((int) first, (int) Math.min(first + count, size())).iterator();
    }

    @Override
    public long size() {
      return users.size();
    }

    @Override
    public IModel<LdapUser> model(LdapUser object) {
      return Model.of(object);
    }

    @Override
    public void detach() {}
  }
}
/** @author cesar */
@Named("consultaOdontHome")
@ViewScoped
public class ConsultaOdontologicaHome extends BussinesEntityHome<ConsultaOdontologica>
    implements Serializable {

  private static org.jboss.solder.logging.Logger log =
      org.jboss.solder.logging.Logger.getLogger(ConsultaOdontologicaHome.class);
  @Inject @Web private EntityManager em;
  @Inject private ConsultaOdontologicaServicio consultaOdontServicio;
  @Inject private FichaMedicaServicio fichaMedicaServicio;
  @Inject private FichaOdontologicaServicio fichaOdontServicio;
  @Inject private Identity identity;
  @Inject private ProfileService profileS;
  @Inject private TratamientoServicio tratamientoServicio;
  @Inject private RecetaMedicamentoService recetaMedicamentoServicio;
  @Inject private RecetaServicio recetasServicio;
  @Inject private ResultadoExamenLCService resultadosExamenesService;
  @Inject SettingService settingService;
  private Setting setting;

  private Diente diente;
  private FichaOdontologica fichaOdontolog;
  // private Servicio servicio;
  private SignosVitales signosVitales;
  private Tratamiento tratamiento;
  private Long fichaMedicaId;
  private PedidoExamenLaboratorio pedidoExamen;
  private Receta receta;

  private UploadedFile file;
  // private List<Servicio> listaServicios = new ArrayList<Servicio>();
  private List<Diente> listaDientes = new ArrayList<Diente>();
  //    private List<Diente> listaDientesC1 = new ArrayList<Diente>();
  //    private List<Diente> listaDientesC2 = new ArrayList<Diente>();
  //    private List<Diente> listaDientesC3 = new ArrayList<Diente>();
  //    private List<Diente> listaDientesC4 = new ArrayList<Diente>();
  private List<Tratamiento> tratamientos = new ArrayList<Tratamiento>();

  @Inject private ExamenLabService examenLabService;
  @Inject private PedidoExamenService pedidoServicio;
  private List<ExamenLabClinico> listaExamenLab = new ArrayList<ExamenLabClinico>();
  private PedidoExamenLaboratorio pedido;

  private Long turnoId;
  private Turno turno = new Turno();
  @Inject private TurnoService turnoS;

  public Long getConsultaOdontologicaId() {
    return (Long) getId();
  }

  public void setConsultaOdontologicaId(Long consultaOdontId) {
    setId(consultaOdontId);
    tratamientos =
        tratamientoServicio.buscarPorConsultaOdontologica(
            consultaOdontServicio.getPorId(getConsultaOdontologicaId()));
  }

  public FichaOdontologica getFichaOdontolog() {
    return fichaOdontolog;
  }

  public void setFichaOdontolog(FichaOdontologica fichaOdontolog) {
    this.fichaOdontolog = fichaOdontolog;
  }

  public Long getFichaMedicaId() {
    return fichaMedicaId;
  }

  public void setFichaMedicaId(Long fichaMedicaId) {
    this.fichaMedicaId = fichaMedicaId;
    if (fichaMedicaId != null) {
      this.setFichaOdontolog(
          fichaOdontServicio.getFichaOdontologicaPorFichaMedica(
              fichaMedicaServicio.getFichaMedicaPorId(fichaMedicaId)));
    }
  }

  public SignosVitales getSignosVitales() {
    return signosVitales;
  }

  public void setSignosVitales(SignosVitales signosVitales) {
    this.signosVitales = signosVitales;
  }

  public Diente getDiente() {
    return diente;
  }

  public void setDiente(Diente diente) {
    log.info("valor diente: " + diente.toString());
    this.diente = diente;
  }

  public Tratamiento getTratamiento() {
    return tratamiento;
  }

  public void setTratamiento(Tratamiento tratamiento) {
    this.tratamiento = tratamiento;
  }

  public UploadedFile getFile() {
    return file;
  }

  public void setFile(UploadedFile file) {
    this.file = file;
  }

  public List<Diente> getListaDientes() {
    return listaDientes;
  }

  public void setListaDientes(List<Diente> listaDientes) {
    this.listaDientes = listaDientes;
  }

  //    public List<Diente> getListaDientesC1() {
  //        //this.IniciarDientes();
  //        Collections.sort(listaDientesC1);
  //        return listaDientesC1;
  //    }
  //
  //    public void setListaDientesC1(List<Diente> listaDientesC1) {
  //        this.listaDientesC1 = listaDientesC1;
  //    }
  //
  //    public List<Diente> getListaDientesC2() {
  //        return listaDientesC2;
  //    }
  //
  //    public void setListaDientesC2(List<Diente> listaDientesC2) {
  //        this.listaDientesC2 = listaDientesC2;
  //    }
  //
  //    public List<Diente> getListaDientesC3() {
  //        return listaDientesC3;
  //    }
  //
  //    public void setListaDientesC3(List<Diente> listaDientesC3) {
  //        this.listaDientesC3 = listaDientesC3;
  //    }
  //    public List<Diente> getListaDientesC4() {
  //        Collections.sort(listaDientesC4);
  //        return listaDientesC4;
  //    }
  //
  //    public void setListaDientesC4(List<Diente> listaDientesC4) {
  //        this.listaDientesC4 = listaDientesC4;
  //    }
  public List<Tratamiento> getTratamientos() {
    return tratamientos;
  }

  public void setTratamientos(List<Tratamiento> tratamientos) {
    this.tratamientos = tratamientos;
  }

  public PedidoExamenLaboratorio getPedidoExamen() {
    return pedidoExamen;
  }

  public void setPedidoExamen(PedidoExamenLaboratorio pedidoExamen) {
    this.pedidoExamen = pedidoExamen;
  }

  public Receta getReceta() {
    return receta;
  }

  public void setReceta(Receta receta) {
    this.receta = receta;
  }

  public PedidoExamenLaboratorio getPedido() {
    return pedido;
  }

  public void setPedido(PedidoExamenLaboratorio pedido) {
    this.pedido = pedido;
  }

  public List<ExamenLabClinico> getListaExamenLab() {
    return listaExamenLab;
  }

  public void setListaExamenLab(List<ExamenLabClinico> listaExamenLab) {
    this.listaExamenLab = listaExamenLab;
  }

  public Long getTurnoId() {
    return turnoId;
  }

  public void setTurnoId(Long turnoId) {
    this.turnoId = turnoId;
    if (turnoId != null) {
      turno = turnoS.find(turnoId);
    }
  }

  public Turno getTurno() {
    return turno;
  }

  public void setTurno(Turno turno) {
    this.turno = turno;
  }

  @TransactionAttribute
  public ConsultaOdontologica load() {
    if (isIdDefined()) {
      wire();
    }
    // log.info("sgssalud --> cargar instance " + getInstance());
    if (getInstance().isPersistent()) {
      if (getInstance().getResponsable() == null) {
        getInstance().setResponsable(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
      }
    }
    return getInstance();
  }

  @TransactionAttribute
  public void wire() {
    getInstance();
  }

  @PostConstruct
  public void init() {
    setEntityManager(em);
    bussinesEntityService.setEntityManager(em);
    consultaOdontServicio.setEntityManager(em);
    fichaMedicaServicio.setEntityManager(em);
    fichaOdontServicio.setEntityManager(em);
    profileS.setEntityManager(em);
    tratamientoServicio.setEntityManager(em);
    recetaMedicamentoServicio.setEntityManager(em);
    recetasServicio.setEntityManager(em);
    receta = new Receta();
    resultadosExamenesService.setEntityManager(em);

    settingService.setEntityManager(em);
    setting = settingService.findByName("consultaActiva");
    //        if (getInstance().isPersistent()) {
    ////            this.IniciarDientes();
    //            Odontograma o = new Odontograma();
    //            //          o.setDientes(listaDientes);
    ////            log.info("Init Dientes  " + fichaOdontolog.toString());
    //            //fichaOdontolog.setOdontograma(o);
    //            //fichaOdontolog.setOdontogramaInicial(o);
    //        }
    // getInstance().setTiempoConsulta(FechasUtil.sumarRestaMinutosFecha(getInstance().getHoraConsulta(), 30));
    // log.info("Odont Inicial " + fichaOdontolog.getOdontogramaInicial());
    // log.info("Odont  " + fichaOdontolog.getOdontograma());

    /*if (!fichaOdontolog.getOdontograma().isPersistent()) {
    fichaOdontolog.setOdontograma(o);
    }
    if (!fichaOdontolog.getOdontogramaInicial().isPersistent()) {
    fichaOdontolog.setOdontogramaInicial(o);
    }*/
    examenLabService.setEntityManager(em);
    pedidoServicio.setEntityManager(em);
    listaExamenLab = examenLabService.getExamenesLab();
    pedido = new PedidoExamenLaboratorio();
    turnoS.setEntityManager(em);
  }

  @Override
  protected ConsultaOdontologica createInstance() {
    // prellenado estable para cualquier clase
    BussinesEntityType _type =
        bussinesEntityService.findBussinesEntityTypeByName(ConsultaOdontologica.class.getName());
    Date now = Calendar.getInstance().getTime();
    ConsultaOdontologica consultaOdont = new ConsultaOdontologica();
    consultaOdont.setCreatedOn(now);
    consultaOdont.setLastUpdate(now);
    consultaOdont.setActivationTime(now);
    consultaOdont.setSignosVitales(new SignosVitales());
    consultaOdont.setType(_type);
    consultaOdont.buildAttributes(bussinesEntityService);

    //        fOdontologica.setCreatedOn(now);
    //        fOdontologica.setActivationTime(now);
    //        fOdontologica.setLastUpdate(now);
    return consultaOdont;
  }

  @Override
  public Class<ConsultaOdontologica> getEntityClass() {
    return ConsultaOdontologica.class;
  }

  @TransactionAttribute
  public String guardar() {
    String salida = "";
    System.out.println("Guardar__________");
    Date now = Calendar.getInstance().getTime();
    getInstance().setLastUpdate(now);
    getInstance().setTiempoConsulta(FechasUtil.sumarRestaMinutosFecha(now, 5));
    try {
      if (getInstance().isPersistent()) {
        // System.out.println("Guardar__________1" + getInstance().getId());
        getInstance().setCode("REALIZADA");
        getInstance().setResponsable(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
        getInstance().getSignosVitales().setFechaActual(now);
        // System.out.println("Guardar__________ 2");
        save(getInstance());
        if (turno.isPersistent()) {
          turno.setEstado("Realizada");
          save(turno);
        }
        FacesMessage msg =
            new FacesMessage(
                "Se actualizo Consulta Odontológica: " + getInstance().getId() + " con éxito");
        FacesContext.getCurrentInstance().addMessage("", msg);
        System.out.println("Guardar__________3");
      } else {
        getInstance().setCode("REALIZADA");
        getInstance().setFichaOdontologica(fichaOdontolog);
        getInstance().setResponsable(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
        getInstance().getSignosVitales().setFechaActual(now);
        create(getInstance().getSignosVitales());
        create(getInstance());
        save(getInstance());
        if (turno.isPersistent()) {
          turno.setEstado("Realizada");
          save(turno);
        }
        FacesMessage msg =
            new FacesMessage(
                "Se creo nueva Consulta Odontológica: " + getInstance().getId() + " con éxito");
        FacesContext.getCurrentInstance().addMessage("", msg);

        salida =
            "/pages/depSalud/odontologia/consultaOdontologica.xhtml?faces-redirect=true"
                + "&fichaMedicaId="
                + getFichaMedicaId()
                + "&consultaOdontId="
                + getInstance().getId()
                + "&backView="
                + getBackView();
      }
    } catch (Exception e) {
      e.printStackTrace();
      FacesMessage msg = new FacesMessage("Error al guardar: " + getInstance().getId());
      FacesContext.getCurrentInstance().addMessage("", msg);
    }
    return salida;
  }
  /*
  @TransactionAttribute
  public void guardarTratamiento() {
  log.info("valor diente: " + diente);
  diente.setRutaIcon(servicio.getRutaImg());
  tratamiento.setFechaRelizacion(new Date());
  tratamientos.add(tratamiento);
  this.actualizarDiente(diente);
  }*/
  /*
  @TransactionAttribute
  public String agregarOdontograma(int odont) {
  String salida = null;
  Odontograma odontog = new Odontograma();
  //odontog.setDientes(this.agregarDientes());
  try {
  if (odont == 1) {  //inicial
  create(odontog);
  fichaOdontolog.setOdontogramaInicial(odontog);
  save(odontog);
  save(fichaOdontolog);
  salida = "/pages/depSalud/odontologia/odont.xhtml?faces-redirect=true"
  + "&fichaMedicaId=" + getFichaMedicaId()
  + "&consultaOdontId=" + getInstance().getId()
  + "&odontogramaId=" + odontog.getId()
  + "&backView=consultaOdontologica"
  + "&tipo=1";
  } else {  //Evolutivo
  create(odontog);
  fichaOdontolog.setOdontograma(odontog);
  save(odontog);
  save(fichaOdontolog);
  salida = "/pages/depSalud/odontologia/odont.xhtml?faces-redirect=true"
  + "&fichaMedicaId=" + getFichaMedicaId()
  + "&consultaOdontId=" + getInstance().getId()
  + "&odontogramaId=" + odontog.getId()
  + "&backView=consultaOdontologica"
  + "&tipo=0";
  }
  } catch (Exception e) {
  FacesMessage msg = new FacesMessage("Error", "al crear odontograma");
  FacesContext.getCurrentInstance().addMessage(null, msg);
  }
  return salida;
  }*/

  public void upload() {

    try {
      byte[] buffer = new byte[(int) file.getSize()];
      this.getInstance().setRadiografiaDental(buffer);
      FacesMessage msg =
          new FacesMessage("Ok", "Fichero " + file.getFileName() + " subido correctamente.");
      FacesContext.getCurrentInstance().addMessage(null, msg);
    } catch (Exception e) {
      log.info("Consulta Odont: Error al cargar la imagen");
    }
  }

  @TransactionAttribute
  public String borrarReceta() {
    System.out.println("Borrar receta_______: " + receta.toString());
    String salida = "";
    try {
      if (getInstance().isPersistent()) {
        Receta_Medicamento aux;
        List<Receta_Medicamento> listaRM = recetaMedicamentoServicio.obtenerPorReceta(receta);
        for (Receta_Medicamento recetaMed1 : listaRM) {
          Medicamento medicament = recetaMed1.getMedicamento();
          int cantidad = medicament.getUnidades() + recetaMed1.getCantidad();
          medicament.setUnidades(cantidad);
          aux = recetaMed1;
          em.merge(medicament);
          em.remove(aux);
        }
        delete(receta);
        // wire();
        // this.getInstance().setRecetas(recetasServicio.buscarRecetaPorConsultaMedica(getInstance()));
        System.out.println("ELIMINO RECETA");
        FacesContext.getCurrentInstance()
            .addMessage(
                null,
                new FacesMessage(
                    FacesMessage.SEVERITY_INFO, "Se elimino receta", "" + getInstance().getId()));
        salida =
            "/pages/depSalud/odontologia/consultaOdontologica.xhtml?faces-redirect=true"
                + "&fichaMedicaId="
                + getFichaMedicaId()
                + "&consultaOdontId="
                + getInstance().getId()
                + "&backView="
                + getBackView();
      }
    } catch (Exception e) {
      FacesContext.getCurrentInstance()
          .addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRORE", e.toString()));
      e.printStackTrace();
    }
    return salida;
  }

  @TransactionAttribute
  public String borrarPedidoExamen() {
    System.out.println("Borrar Pedido Examen_______: " + pedidoExamen.toString());
    String salida = "";
    try {
      if (getPedidoExamen().isPersistent()) {
        List<ResultadoExamenLabClinico> listaResultadosExamenLab =
            new ArrayList<ResultadoExamenLabClinico>();
        listaResultadosExamenLab =
            resultadosExamenesService.getResultadosExamenPorPedidoExamen(pedidoExamen);
        ResultadoExamenLabClinico aux;
        for (ResultadoExamenLabClinico result : listaResultadosExamenLab) {
          aux = result;
          em.remove(aux);
        }

        delete(pedidoExamen);
        // System.out.println("ELIMINO Pedido");
        FacesContext.getCurrentInstance()
            .addMessage(
                null,
                new FacesMessage(
                    FacesMessage.SEVERITY_INFO, "Se elimino Pedido", "" + pedidoExamen.getId()));
        salida =
            "/pages/depSalud/odontologia/consultaOdontologica.xhtml?faces-redirect=true"
                + "&fichaMedicaId="
                + getFichaMedicaId()
                + "&consultaOdontId="
                + getInstance().getId()
                + "&backView="
                + getBackView();
      }
    } catch (Exception e) {
      FacesContext.getCurrentInstance()
          .addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERRORE", e.toString()));
      e.printStackTrace();
    }
    return salida;
  }

  public boolean isEditable() {
    // return FechasUtil.editable(getInstance().getFechaConsulta(), getInstance().getHoraConsulta(),
    // 24);
    if ("REALIZADA".equals(getInstance().getCode()) && "false".equals(setting.getValue())) {
      //  System.out.println("DESHABILITADO");
      return true;
    }
    return false;
  }

  @TransactionAttribute
  public String agregarPedido() {
    Date now = Calendar.getInstance().getTime();
    System.out.println("INGRESo a Guardar _________");
    String salida = null;
    boolean ning = false;
    for (ExamenLabClinico ex : listaExamenLab) {
      if (ex.isSelect()) {
        ning = true;
        break;
      }
    }
    try {
      if (!ning) {
        // save(getInstance());
        FacesMessage msg =
            new FacesMessage(FacesMessage.SEVERITY_WARN, "Debe seleccionar minimo un examen", null);
        FacesContext.getCurrentInstance().addMessage("", msg);
        // return null;
      } else {
        // this.listaPedidoExamenLabC = pickListExamenesLab.getTarget();
        pedido.setFichaOdontologica(fichaOdontolog);
        pedido.setPaciente(fichaOdontolog.getFichaMedica().getPaciente());
        pedido.setEstado("Nuevo");
        pedido.setResponsableEmision(profileS.getProfileByIdentityKey(identity.getUser().getKey()));
        pedido.setFechaPedido(now);
        create(pedido);
        save(pedido);
        update();
        // System.out.println("Guardo Con exito 0_________");
        ResultadoExamenLabClinico resultadoExa;
        List<Parametros> pl = null; //
        for (ExamenLabClinico ex : this.listaExamenLab) {
          if (ex.isSelect()) {
            resultadoExa = new ResultadoExamenLabClinico();
            resultadoExa.setExamenLab(ex);
            resultadoExa.setPedidoExamenLab(pedido);
            pl = examenLabService.getParametrosPorExamen(ex);
            resultadoExa.agregarValoresResultados(pl);
            save(resultadoExa);
            // update();
          }
        }

        FacesMessage msg =
            new FacesMessage(
                "Se agrego nuevo Pedido de Examenes: " + getInstance().getId() + " con éxito");
        FacesContext.getCurrentInstance().addMessage("", msg);
        pedido = new PedidoExamenLaboratorio();
        // hc = hcs.buscarPorFichaMedica(fms.getFichaMedicaPorId(fichaMedicaId));

        RequestContext.getCurrentInstance().update(":form:tabOpc:tablaPedidos :form:growl");
        RequestContext.getCurrentInstance().execute("pedidoDlg.hide();");
        salida =
            "/pages/depSalud/odontologia/consultaOdontologica.xhtml?faces-redirect=true"
                + "&fichaMedicaId="
                + getFichaMedicaId()
                + "&consultaOdontId="
                + getInstance().getId()
                + "&backView="
                + getBackView();
      }
    } catch (Exception e) {
      e.printStackTrace();
      FacesMessage msg = new FacesMessage("Error al guardar: " + getInstance().getId());
      FacesContext.getCurrentInstance().addMessage("", msg);
    }

    return salida;
  }
}
 public void setDiente(Diente diente) {
   log.info("valor diente: " + diente.toString());
   this.diente = diente;
 }
/** Various utilities used on the platform */
@Setter
@Getter
@Singleton
public class UQasarUtil {

  static final String SEPARATOR = java.nio.file.FileSystems.getDefault().getSeparator();
  static final String ONTOLOGYFILE = "uq-ontology-model.rdf";

  protected static ResourceBundle res = null;
  private static Logger logger = Logger.getLogger(UQasarUtil.class);

  // List containing the notifications triggered by the rules' engine
  @Setter @Getter private static List<INotification> notifications = new ArrayList<>();

  @Setter @Getter private static Date latestTreeUpdateDate = new Date();

  @Setter @Getter
  private static Model uqModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);

  // Enumeration for the various suggestion types
  public enum SuggestionType {
    NO_SUGGESTION("no_suggestion"),
    QO_REMOVE("qo.remove"),
    QO_REPLACE("qo.replace"),
    METRIC_REMOVE("metric.remove"),
    ;

    private final String labelKey;

    SuggestionType(final String labelKey) {
      this.labelKey = labelKey;
    }

    @Override
    public String toString() {
      return getLabelModel().getObject();
    }

    public IModel<String> getLabelModel() {
      return ResourceBundleLocator.getLabelModel(UQasarUtil.class, "suggestion." + labelKey);
    }

    public static List<SuggestionType> getAllSuggestionTypes() {
      return Arrays.asList(values());
    }
  }

  /**
   * Get the temp directory to be used; in case JBoss is used, use its temp dir, otherwise the user
   * temp.
   *
   * @return
   */
  public static String getTempDirPath() {
    String tempDirectory = null;

    Properties systemProp = System.getProperties();
    // In case JBoss is used, use the JBoss temp dir
    if (systemProp.containsKey("jboss.server.temp.dir")) {
      tempDirectory = systemProp.getProperty("jboss.server.temp.dir");
      if (!tempDirectory.endsWith(SEPARATOR)) {
        tempDirectory += SEPARATOR;
      }
    }
    // Otherwise use a temp directory
    else {
      tempDirectory = System.getProperty("java.io.tmpdir");
      if (!tempDirectory.endsWith(SEPARATOR)) {
        tempDirectory += SEPARATOR;
      }
    }

    return tempDirectory;
  }

  /**
   * Get the data dir to be used; in case JBoss is used, use its data dir, otherwise the user temp.
   *
   * @return
   */
  public static String getDataDirPath() {
    String dataDirectory = null;
    Properties systemProp = System.getProperties();
    // In case JBoss is used
    if (systemProp.containsKey("jboss.server.data.dir")) {
      dataDirectory = systemProp.getProperty("jboss.server.data.dir");
      if (!dataDirectory.endsWith(SEPARATOR)) {
        dataDirectory += SEPARATOR;
      }
    }
    // Otherwise use a temp directory
    else {
      dataDirectory = System.getProperty("java.io.tmpdir");
      if (!dataDirectory.endsWith(SEPARATOR)) {
        dataDirectory += SEPARATOR;
      }
    }

    return dataDirectory;
  }

  /**
   * Construct a formula string to be evaluated.
   *
   * @param varsAndOpers
   * @return
   */
  public static String constructFormula(List<Object> varsAndOpers) {
    String formula = "";

    for (Object object : varsAndOpers) {
      formula += object;
    }

    logger.info("Constructed formula to be evaluated: " + formula);
    return formula;
  }

  /**
   * Get properties resource
   *
   * @return
   */
  public static ResourceBundle getProperties() {
    if (res == null) {
      loadProperties();
    }
    return res;
  }

  /** Load properties file */
  private static void loadProperties() {
    res = ResourceBundle.getBundle("uqasar");
  }

  /**
   * Round double to two decimals
   *
   * @param number
   * @return
   */
  public static Double round(double number) {
    DecimalFormat df = new DecimalFormat("#,##");
    df.setRoundingMode(RoundingMode.DOWN);
    String s = df.format(number);
    return Double.valueOf(s);
  }

  /**
   * Replace whitespace chars with the defined separator and escape the String
   *
   * @param name
   */
  public static String sanitizeName(String name) {
    final String SEPARATOR = "_";
    if (name.contains(" ")) {
      String processed = name.replaceAll(" ", SEPARATOR).concat(SEPARATOR);
      return StringEscapeUtils.escapeJavaScript(processed);
    }
    // Otherwise return the actual string
    return name;
  }

  /**
   * Replace the separator with whitespaces and unescape the String
   *
   * @param name
   * @return
   */
  public static String unSanitizeName(String name) {
    final String SEPARATOR = "_";
    if (name.contains(SEPARATOR)) {
      return StringEscapeUtils.unescapeJavaScript(name).replaceAll(SEPARATOR, " ").trim();
    }
    return StringEscapeUtils.unescapeJavaScript(name).trim();
  }

  /**
   * Get the pwd used for encrypting and decrypting adapter passwords TODO: Where could this be
   * saved securely
   *
   * @return
   */
  public static String getEncDecPwd() {
    return "jvnqeiPIqX_6cpdOYfDc7sHk7nEIv4zRn5984JwIHnq4AX7XQt";
  }

  /**
   * Get the Jira metric names TODO: Fetch the list of metrics from uQasarMetric
   *
   * @return
   */
  public static List<String> getJiraMetricNames() {
    String metrics[] = {
      "PROJECTS_PER_SYSTEM_INSTANCE",
      "ISSUES_PER_PROJECTS_PER_SYSTEM_INSTANCE",
      "FIXED_ISSUES_PER_PROJECT",
      "UNRESOLVED_ISSUES_PER_PROJECT",
      "UNRESOLVED_BUG_ISSUES_PER_PROJECT",
      "UNRESOLVED_TASK_ISSUES_PER_PROJECT"
    };

    return Arrays.asList(metrics);
  }

  public static List<String> getJiraMetricNamesAbbreviated() {
    String metrics[] = {"Projects", "Issues", "Fixed issues", "Unresolved issues"};

    return Arrays.asList(metrics);
  }

  /**
   * TODO: Fetch the list of metrics from uQasarMetric Get the Sonar metric names
   *
   * @return
   */
  public static List<String> getSonarMetricNames() {

    String metrics[] = {
      "NCLOC", // lines of code (NC=non comment)
      "LINES", // lines (i.e. all lines)
      "COMMENT_LINES", // number of comment lines
      "STATEMENTS", // number of statements
      "CLASSES", // number of classes
      "FILES", // number of files
      "DIRECTORIES", // number of directories
      "FUNCTIONS", // number of functions
      "COMMENT_LINES_DENSITY", // the density of comment lines (number in [0..100])
      "DUPLICATED_LINES", // number of duplicated lines
      "DUPLICATED_LINES_DENSITY", // the density of duplicated lines (number in [0..100])
      "COMPLEXITY", // cyclomatic complexity of the project
      "FUNCTION_COMPLEXITY", // the average cyclomatic complexity of a function
      "FILE_COMPLEXITY", // the average cyclomatic complexity of a source code file
      "CLASS_COMPLEXITY", // the average cyclomatic complexity of a class
      "UT_COVERAGE", // code coverage by unit tests
      "AT_COVERAGE", // code coverage by acceptance tests
      "OVERALL_COVERAGE", // code coverage by both, unit and acceptance tests
      "PACKAGE_TANGLES", // Number of file dependencies to cut in order to remove all cycles between
                         // directories.
      "PACKAGE_TANGLE_INDEX", // Level of directory interdependency. Best value (0%) means that
                              // there is no cycle and worst value (100%) means that directories are
                              // really tangled.
      "TEST_SUCCESS_DENSITY", // ratio of successfully executed tests to the overall number of te
      "TEST_FAILURES", // number of failed tests (failure = test could be run and is failed)
      "TEST_ERRORS", // number of errored tests (error = test could not be run)
      "TESTS", // number of tests

      // Sonar, available metrics that can be used if they are implemented on the adapter

      //			      /* core statistics */
      //				"LINES",
      //				"NCLOC",
      //				"CLASSES",
      //				"FILES",
      //				"DIRECTORIES",
      //				"PACKAGES",
      //				"FUNCTIONS",
      //				"ACCESSORS",
      //				"STATEMENTS",
      //				"PUBLIC_API",
      //
      //			      /* complexity */
      //				"COMPLEXITY",
      //				"CLASS_COMPLEXITY",
      //				"FUNCTION_COMPLEXITY",
      //				"FILE_COMPLEXITY",
      //				"CLASS_COMPLEXITY_DISTRIBUTION",
      //				"FUNCTION_COMPLEXITY_DISTRIBUTION",
      //
      //			      /* comments */
      //				"COMMENT_LINES",
      //				"COMMENT_LINES_DENSITY",
      //				"PUBLIC_DOCUMENTED_API_DENSITY",
      //				"PUBLIC_UNDOCUMENTED_API",
      //				"COMMENTED_OUT_CODE_LINES",
      //
      //			      /* unit tests */
      //				"TESTS",
      //				"TEST_EXECUTION_TIME",
      //				"TEST_ERRORS",
      //				"SKIPPED_TESTS",
      //				"TEST_FAILURES",
      //				"TEST_SUCCESS_DENSITY",
      //				"TEST_DATA",
      //
      //			      /* code coverage by unit tests */
      //				"COVERAGE",
      //				"LINES_TO_COVER",
      //				"UNCOVERED_LINES",
      //				"LINE_COVERAGE",
      //				"COVERAGE_LINE_HITS_DATA",
      //
      //				"CONDITIONS_TO_COVER",
      //				"UNCOVERED_CONDITIONS",
      //				"BRANCH_COVERAGE",
      //				"BRANCH_COVERAGE_HITS_DATA",
      //
      //				"UNCOVERED_COMPLEXITY_BY_TESTS",
      //
      //			      /* duplicated lines */
      //				"DUPLICATED_LINES",
      //				"DUPLICATED_BLOCKS",
      //				"DUPLICATED_FILES",
      //				"DUPLICATED_LINES_DENSITY",
      //				"DUPLICATIONS_DATA",
      //
      //			      /* coding rules */
      //				"USABILITY",
      //				"RELIABILITY",
      //				"EFFICIENCY",
      //				"PORTABILITY",
      //				"MAINTAINABILITY",
      //
      //				"WEIGHTED_VIOLATIONS",
      //				"VIOLATIONS_DENSITY",
      //				"VIOLATIONS",
      //				"BLOCKER_VIOLATIONS",
      //				"CRITICAL_VIOLATIONS",
      //				"MAJOR_VIOLATIONS",
      //				"MINOR_VIOLATIONS",
      //				"INFO_VIOLATIONS",
    };

    return Arrays.asList(metrics);
  }

  /**
   * TODO: Fetch the list of metrics from uQasarMetric Get the TestLink metric names
   *
   * @return
   */
  public static List<String> getTestLinkMetricNames() {
    String metrics[] = {"TEST_P", "TEST_F", "TEST_B", "TEST_N", "TEST_TOTAL"};

    return Arrays.asList(metrics);
  }

  /**
   * TODO: Fetch the list of metrics from uQasarMetric Get the Cubes direct Metric names
   *
   * @return Cubes metric Names
   */
  public static List<String> getCubesMetricNames() {
    String metrics[] = {
      "cube/jira/aggregate?cut=Status:Done",
      "cube/jira/aggregate?cut=Type:Bug",
      "cube/jira/aggregate?cut=Status:To%20Do",
      "cube/jira/aggregate?cut=Priority:Blocker",
      "cube/jira/aggregate?cut=Priority:Critical",
      "cube/jira/aggregate?cut=Priority:Major",
      "cube/jira/aggregate?cut=Priority:Minor",
      "cube/jira/aggregate?cut=Status:Open&cut=Priority:Major",
      //				"cube/jira/fact/UQ-1",
      //				"cube/jira/model",
      //				"cube/jira/cell",
      //				"cube/jira/members/Status",
      //				"cube/jira/facts",
      //				"cubes"
    };

    return Arrays.asList(metrics);
  }

  public static List<String> getGitlabMetricNames() {

    String metrics[] = {"GIT_COMMITS", "GIT_PROJECTS"};

    return Arrays.asList(metrics);
  }

  /**
   * Convert minutes to ms
   *
   * @param minutes
   * @return
   */
  public static int minsToMs(int minutes) {
    final int SEC = 60;
    final int MS = 1000;
    return minutes * SEC * MS;
  }

  /**
   * Compare two dates returning true if equal and false if not. This comparison omits milliseconds
   *
   * @param dateOne
   * @param dateTwo
   * @return
   */
  public static boolean isDateEqual(Date dateOne, Date dateTwo) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    String date1 = sdf.format(dateOne);
    String date2 = sdf.format(dateTwo);

    if (date1.equals(date2)) {
      return true;
    }

    return false;
  }

  /**
   * Takes care of computing the tree values (update metrics and compute QO/QI values based on that)
   * starting from the root node.
   *
   * @param projectRoot Node
   */
  public static void updateTree(TreeNode projectRoot) {
    // Create a timestamp at the start of the tree update so that
    // all the updated entities have the same value for the date.
    setLatestTreeUpdateDate(new Date());
    logger.info("Updating the QA Project tree...");
    postorder(projectRoot);
  }

  /**
   * Traverse the tree in postorder and update tree values
   *
   * @param node
   */
  private static void postorder(TreeNode node) {

    if (node == null) {
      return;
    }

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

    // Iterate the node children
    for (Object o : node.getChildren()) {
      TreeNode nodeChild = (TreeNode) o;
      UQasarUtil.postorder(nodeChild);
    }
    logger.debug("Traversing project tree in postorder..." + node.toString());
    // Update the value
    try {
      InitialContext ic = new InitialContext();
      AdapterDataService adapterDataService = new AdapterDataService();
      TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");

      if (node instanceof Metric) {
        Metric metric = (Metric) node;
        logger.debug("Recomputing the value of the Metric " + node);
        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 (node instanceof QualityIndicator) {
        logger.info("Recomputing the value of the Quality Indicator " + node);
        QualityIndicator qi = (QualityIndicator) node;
        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 (node instanceof QualityObjective) {
        logger.info("Recomputing the value of the Quality Objective " + node);
        QualityObjective qo = (QualityObjective) node;
        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 (node instanceof Project) {
        logger.info("Recomputing the value of the Project " + node);
        Project prj = (Project) node;
        double qoValueSum = 0;
        double denominator = 0;
        for (Object o : node.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(node);
      // 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];
        node.setSuggestionType(stype);
        if (suggestionsValues[0] != null && !suggestionsValues[0].equals("")) {
          node.setSuggestionValue((String) suggestionsValues[0]);
        }
      }

      treeNodeService.update(node);

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

    return;
  }

  /**
   * Takes care of computing the tree values (update metrics and compute QO/QI values based on that)
   * starting from the root node.
   *
   * @param projectRoot Node
   */
  public static void updateTreeWithParticularNode(TreeNode projectRoot, TreeNode projectTreeNode) {
    // Create a timestamp at the start of the tree update so that
    // all the updated entities have the same value for the date.
    setLatestTreeUpdateDate(new Date());
    logger.info("Updating the QA Project tree...");
    postorderWithParticularNode(projectRoot, projectTreeNode);
  }

  /**
   * 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;
  }

  /**
   * @param node Node whose value is studied
   * @return
   */
  private static Multimap<SuggestionType, Object> getSuggestionForNode(TreeNode node) {

    // For storing the suggestion type and the payload
    Multimap<SuggestionType, Object> suggestionsMultimap = ArrayListMultimap.create();

    final String EMPTY = "";

    try {
      InitialContext ic = new InitialContext();
      ProjectSimilarityService projectSimilarityService =
          (ProjectSimilarityService) ic.lookup("java:module/ProjectSimilarityService");
      QualityObjectiveSimilarityService qoSimilarityService =
          (QualityObjectiveSimilarityService)
              ic.lookup("java:module/QualityObjectiveSimilarityService");
      // TODO: Finding similar metrics

      if (node instanceof QualityObjective) {
        QualityObjective qo = (QualityObjective) node;
        Float value = qo.getValue();

        // If the value of a quality objective cannot be computed,
        // attempt to obtain a suggestion
        if (value == null || value.isNaN()) {
          // Attempt to find a suitable project
          Project proj = qo.getProject();
          Project similarProject = null;
          if (proj != null) {
            // Get a list of similar projects
            List<Project> similarProjects = projectSimilarityService.getSimilarProjects(proj);
            if (similarProjects != null && similarProjects.size() > 0) {
              // For now obtain the first suitable project
              similarProject = similarProjects.get(0);
            }
          }

          // If a suitable similar project was found, search for similar Quality Objective(s) to be
          // suggested
          if (similarProject != null) {
            // Get similar QOs from a similar project
            List<QualityObjective> qos = qoSimilarityService.getSimilarQOs(qo, similarProject);
            // If results were found, construct a suggestion (for now obtain the first one).
            if (qos != null && qos.size() > 0) {
              suggestionsMultimap.put(SuggestionType.QO_REPLACE, qos.get(0));
              return suggestionsMultimap;
            }
          }

          // Otherwise suggest the QO to be removed
          suggestionsMultimap.put(SuggestionType.QO_REMOVE, null);
          return suggestionsMultimap;
        }
      }
      // if a metric has no value / the value is 0, return a suggestion to
      // remove the metric
      if (node instanceof Metric) {

        Metric metric = (Metric) node;
        Float value = metric.getValue();

        if (value == null || value.isNaN() || value.isInfinite()) {
          suggestionsMultimap.put(SuggestionType.METRIC_REMOVE, null);
          return suggestionsMultimap;
        }
      }
    } catch (NamingException e) {
      e.printStackTrace();
    }

    // If no suggestion is to be provided, return an empty string
    // (overwrite the possible existing suggestion).
    suggestionsMultimap.put(SuggestionType.NO_SUGGESTION, "");
    return suggestionsMultimap;
  }

  /**
   * Get a list of Jenkins metrics
   *
   * @return
   */
  public static List<String> getJenkinsMetricNames() {
    String metrics[] = {
      "JENKINS_PROJECTS", // Jenkins projects
      "JENKINS_LATEST_BUILD_SUCCESS", // State of the latest build
      "JENKINS_BUILD_HISTORY",
    };

    return Arrays.asList(metrics);
  }

  /** 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();
    }
  }

  /** Writes the user entities to rdf */
  private static OntModel writeUserEntries() {
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    try {
      thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
      InitialContext ic = new InitialContext();
      UserService userService = (UserService) ic.lookup("java:module/UserService");
      List<User> users = userService.getAll();
      for (User u : users) {
        writer.save(u);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return model;
  }

  /** Writes the project entities to rdf */
  private static OntModel writeProjectEntries() {
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    try {
      thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
      InitialContext ic = new InitialContext();
      TreeNodeService treeNodeService = (TreeNodeService) ic.lookup("java:module/TreeNodeService");
      List<Project> projects = treeNodeService.getAllProjects();
      for (Project proj : projects) {
        writer.save(proj);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return model;
  }

  /** Write metadata entities from the beans to rdf model */
  private static OntModel writeMetaDataModelEntries() {
    OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
    thewebsemantic.Bean2RDF writer = new Bean2RDF(model);
    try {
      InitialContext ic = new InitialContext();
      for (final Class clazz : MetaData.getAllClasses()) {
        if (ContinuousIntegrationTool.class.isAssignableFrom(clazz)) {
          ContinuousIntegrationToolService cits =
              (ContinuousIntegrationToolService)
                  ic.lookup("java:module/ContinuousIntegrationToolService");
          List<ContinuousIntegrationTool> continuousIntegrationTools = cits.getAll();
          for (ContinuousIntegrationTool continuousIntegrationTool : continuousIntegrationTools) {
            writer.save(continuousIntegrationTool);
          }
        } else if (CustomerType.class.isAssignableFrom(clazz)) {
          CustomerTypeService cts =
              (CustomerTypeService) ic.lookup("java:module/CustomerTypeService");
          List<CustomerType> customerTypes = cts.getAll();
          for (CustomerType customerType : customerTypes) {
            writer.save(customerType);
          }
        } else if (IssueTrackingTool.class.isAssignableFrom(clazz)) {
          IssueTrackingToolService itts =
              (IssueTrackingToolService) ic.lookup("java:module/IssueTrackingToolService");
          List<IssueTrackingTool> issueTrackingTools = itts.getAll();
          for (IssueTrackingTool issueTrackingTool : issueTrackingTools) {
            writer.save(issueTrackingTool);
          }
        } else if (ProgrammingLanguage.class.isAssignableFrom(clazz)) {
          ProgrammingLanguageService pls =
              (ProgrammingLanguageService) ic.lookup("java:module/ProgrammingLanguageService");
          List<ProgrammingLanguage> programmingLanguages = pls.getAll();
          for (ProgrammingLanguage programmingLanguage : programmingLanguages) {
            writer.save(programmingLanguage);
          }
        } else if (ProjectType.class.isAssignableFrom(clazz)) {
          ProjectTypeService pts = (ProjectTypeService) ic.lookup("java:module/ProjectTypeService");
          List<ProjectType> projectTypes = pts.getAll();
          for (ProjectType projectType : projectTypes) {
            writer.save(projectType);
          }
        } else if (SoftwareLicense.class.isAssignableFrom(clazz)) {
          SoftwareLicenseService sls =
              (SoftwareLicenseService) ic.lookup("java:module/SoftwareLicenseService");
          List<SoftwareLicense> softwareLicenses = sls.getAll();
          for (SoftwareLicense softwareLicense : softwareLicenses) {
            writer.save(softwareLicense);
          }
        } else if (SoftwareType.class.isAssignableFrom(clazz)) {
          SoftwareTypeService sts =
              (SoftwareTypeService) ic.lookup("java:module/SoftwareTypeService");
          List<SoftwareType> softwareTypes = sts.getAll();
          for (SoftwareType softwareType : softwareTypes) {
            writer.save(softwareType);
          }
        } else if (SourceCodeManagementTool.class.isAssignableFrom(clazz)) {
          SourceCodeManagementToolService scmts =
              (SourceCodeManagementToolService)
                  ic.lookup("java:module/SourceCodeManagementToolService");
          List<SourceCodeManagementTool> sourceCodeManagementTools = scmts.getAll();
          for (SourceCodeManagementTool sourceCodeManagementTool : sourceCodeManagementTools) {
            writer.save(sourceCodeManagementTool);
          }
        } else if (StaticAnalysisTool.class.isAssignableFrom(clazz)) {
          StaticAnalysisToolService sats =
              (StaticAnalysisToolService) ic.lookup("java:module/StaticAnalysisToolService");
          List<StaticAnalysisTool> staticAnalysisTools = sats.getAll();
          for (StaticAnalysisTool staticAnalysisTool : staticAnalysisTools) {
            writer.save(staticAnalysisTool);
          }
        } else if (TestManagementTool.class.isAssignableFrom(clazz)) {
          TestManagementToolService tmts =
              (TestManagementToolService) ic.lookup("java:module/TestManagementToolService");
          List<TestManagementTool> testManagementTools = tmts.getAll();
          for (TestManagementTool testManagementTool : testManagementTools) {
            writer.save(testManagementTool);
          }
        } else if (Topic.class.isAssignableFrom(clazz)) {
          TopicService ts = (TopicService) ic.lookup("java:module/TopicService");
          List<Topic> topics = ts.getAll();
          for (Topic topic : topics) {
            writer.save(topic);
          }
        } else if (SoftwareDevelopmentMethodology.class.isAssignableFrom(clazz)) {
          SoftwareDevelopmentMethodologyService sdms =
              (SoftwareDevelopmentMethodologyService)
                  ic.lookup("java:module/SoftwareDevelopmentMethodologyService");
          List<SoftwareDevelopmentMethodology> softwareDevelopmentMethodologies = sdms.getAll();
          for (SoftwareDevelopmentMethodology softwareDevelopmentMethodology :
              softwareDevelopmentMethodologies) {
            writer.save(softwareDevelopmentMethodology);
          }
        } else if (QModelTagData.class.isAssignableFrom(clazz)) {
          QModelTagDataService qmtds =
              (QModelTagDataService) ic.lookup("java:module/QModelTagDataService");
          List<QModelTagData> qmodelTagData = qmtds.getAll();
          for (QModelTagData qmtd : qmodelTagData) {
            writer.save(qmtd);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return model;
  }

  /** 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.");
  }

  public static String execSparQLQuery(String query) {
    System.out.println("execSPINQuery");
    Model model = getUqModel();

    // Register system functions (such as sp:gt (>))
    SPINModuleRegistry.get().init();

    Query arqQuery = ARQFactory.get().createQuery(model, query);
    ARQ2SPIN arq2SPIN = new ARQ2SPIN(model);
    Select spinQuery = (Select) arq2SPIN.createQuery(arqQuery, null);

    System.out.println("SPIN query in Turtle:");
    model.write(System.out, FileUtils.langTurtle);

    System.out.println("-----");
    String str = spinQuery.toString();
    System.out.println("SPIN query:\n" + str);

    // Now turn it back into a Jena Query
    Query parsedBack = ARQFactory.get().createQuery(spinQuery);
    System.out.println("Jena query:\n" + parsedBack);

    com.hp.hpl.jena.query.Query arq = ARQFactory.get().createQuery(spinQuery);
    QueryExecution qexec = ARQFactory.get().createQueryExecution(arq, model);
    QuerySolutionMap arqBindings = new QuerySolutionMap();
    arqBindings.add("predicate", RDFS.label);
    qexec.setInitialBinding(arqBindings); // Pre-assign the arguments
    ResultSet rs = qexec.execSelect();

    //		System.out.println("#####################################################################");
    //
    //		if (rs.hasNext()) {
    //			QuerySolution row = rs.next();
    //			System.out.println("Row: " +row.toString());
    //			RDFNode user = row.get("User");
    //			Literal label = row.getLiteral("label");
    //			System.out.println(user.toString());
    //		}
    //		RDFNode object = rs.next().get("object");
    //		System.out.println("Label is " + object);

    Collection<User> users = Sparql.exec(getUqModel(), User.class, query);

    String usersString = "";
    for (User user : users) {
      System.out.println("User: "******"<br/>";
    }

    System.out.println("execSPINQuery() done.");
    return usersString;
  }
}
  /**
   * 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;
  }