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

  }
  @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 setFirstResult(int firstResult) {
   log.info("set first result + firstResult");
   this.firstResult = firstResult;
   this.resultList = null;
 }
 @PostConstruct
 public void init() {
   log.info("Setup entityManager into bussinesEntityTypeService...");
   bussinesEntityTypeService.setEntityManager(entityManager);
 }
 /** 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);
 }
 public void setDiente(Diente diente) {
   log.info("valor diente: " + diente.toString());
   this.diente = diente;
 }
  /**
   * 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;
  }
  /**
   * Import seed data when Seam Servlet fires an event notifying observers that the web application
   * is being initialized.
   */
  public void importData(@Observes @Initialized WebApplication webapp) {
    log.info("Importing seed data for application " + webapp.getName());
    // use manual transaction control since this is a managed bean
    try {
      utx.begin();
      if (entityManager.createQuery("select g from Genre g").getResultList().size() == 0) {
        // AS7-2045
        //            entityManager.createQuery("delete from User").executeUpdate();
        //
        //            entityManager.createQuery("delete from Content").executeUpdate();
        //            entityManager.createQuery("delete from Genre").executeUpdate();

        persist(users);
        for (TwoTuple<String, String> genre : genres) {
          if ("ИСТОРИИ".equals(genre.getFirst())) {
            createGenre(
                new Genre(genre.getFirst(), genre.getSecond()),
                Arrays.asList(
                    new TwoTuple<Genre, List<Content>>(
                        new Genre(
                            "ЛИЧНЫЙ ОПЫТ",
                            "Рассказ читателям о результатах собственных экспериментов."),
                        new ArrayList<Content>())));
          } else if ("ОБЗОРЫ".equals(genre.getFirst())) {
            createGenre(
                new Genre(genre.getFirst(), genre.getSecond()),
                Arrays.asList(
                    new TwoTuple<Genre, List<Content>>(
                        new Genre("ГАДЖЕТЫ", "Обзор гаджетов."), new ArrayList<Content>())));
          } else if ("РАЗВЛЕЧЕНИЯ".equals(genre.getFirst())) {
            createGenre(
                new Genre(genre.getFirst(), genre.getSecond()),
                Arrays.asList(
                    new TwoTuple<Genre, List<Content>>(
                        new Genre("Юмор", "Анекдоты, шутки..."), new ArrayList<Content>())));
          } else if ("ПРОЧЕЕ".equals(genre.getFirst())) {
            createGenre(
                new Genre(genre.getFirst(), genre.getSecond()),
                Arrays.asList(
                    new TwoTuple<Genre, List<Content>>(
                        new Genre("ВИДЕО", "Любительское видео"), new ArrayList<Content>()),
                    new TwoTuple<Genre, List<Content>>(
                        new Genre("ВИДЕО-КЛИПЫ", "Музыкальные видео клипы"),
                        new ArrayList<Content>())));
          } else {
            createGenre(
                new Genre(genre.getFirst(), genre.getSecond()),
                new ArrayList<TwoTuple<Genre, List<Content>>>());
          }
        }
      }
      indextData();
      utx.commit();
      log.info("Seed data successfully imported");
    } catch (Exception e) {
      log.error("Import failed. Seed data will not be available.", e);
      try {
        if (utx.getStatus() == Status.STATUS_ACTIVE) {
          try {
            utx.rollback();
          } catch (Exception rbe) {
            log.error("Error rolling back transaction", rbe);
          }
        }
      } catch (Exception se) {
      }
    }
  }
Example #17
0
 /**
  * Called every minute to request garbage collection.
  *
  * @param second The observed event.
  */
 public void collectGarbage(@Observes @Every(Interval.MINUTE) Trigger minute) {
   log.info("Requesting garbage collection");
   System.gc();
 }
Example #18
0
 /**
  * Clear the graph every 2 minutes, at 20 seconds past the minute.
  *
  * @param e The event observed.
  */
 public void clearGraphData(@Observes @Scheduled("20 */2 * ? * *") Trigger e) {
   log.info("Clearing data on schedule");
   getCatDataSet().clear();
 }
Example #19
0
 public void stop() {
   if (emitterHandle != null) {
     log.info("Stopping HeartbeatEmitter.");
     emitterHandle.cancel(true);
   }
 }