Esempio n. 1
0
  @Test
  public void update_description_only() throws Exception {
    MetricDto metric = insertNewMetric(ValueType.STRING);
    ComponentDto component = insertNewProject("project-uuid");
    CustomMeasureDto customMeasure =
        newCustomMeasure(component, metric)
            .setMetricId(metric.getId())
            .setComponentUuid(component.uuid())
            .setCreatedAt(system.now())
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();
    when(system.now()).thenReturn(123_456_789L);

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
        .setParam(PARAM_VALUE, "new-text-measure-value")
        .execute();

    CustomMeasureDto updatedCustomMeasure =
        dbClient.customMeasureDao().selectOrFail(dbSession, customMeasure.getId());
    assertThat(updatedCustomMeasure.getTextValue()).isEqualTo("new-text-measure-value");
    assertThat(updatedCustomMeasure.getDescription()).isEqualTo("custom-measure-description");
    assertThat(updatedCustomMeasure.getUpdatedAt()).isEqualTo(123_456_789L);
    assertThat(customMeasure.getCreatedAt()).isEqualTo(updatedCustomMeasure.getCreatedAt());
  }
Esempio n. 2
0
  @Test
  public void fail_if_not_logged_in() throws Exception {
    userSessionRule.anonymous();
    expectedException.expect(UnauthorizedException.class);
    MetricDto metric =
        MetricTesting.newMetricDto().setEnabled(true).setValueType(ValueType.STRING.name());
    dbClient.metricDao().insert(dbSession, metric);
    ComponentDto component = ComponentTesting.newProjectDto("project-uuid");
    dbClient.componentDao().insert(dbSession, component);
    CustomMeasureDto customMeasure =
        newCustomMeasureDto()
            .setMetricId(metric.getId())
            .setComponentUuid(component.uuid())
            .setCreatedAt(system.now())
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();

    ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
        .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
        .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
        .setParam(PARAM_VALUE, "1984")
        .execute();
  }
Esempio n. 3
0
  @Test
  public void returns_full_object_in_response() throws Exception {
    MetricDto metric =
        MetricTesting.newMetricDto()
            .setEnabled(true)
            .setValueType(ValueType.STRING.name())
            .setKey("metric-key");
    dbClient.metricDao().insert(dbSession, metric);
    ComponentDto component = ComponentTesting.newProjectDto("project-uuid").setKey("project-key");
    dbClient.componentDao().insert(dbSession, component);
    CustomMeasureDto customMeasure =
        newCustomMeasure(component, metric)
            .setCreatedAt(100_000_000L)
            .setDescription("custom-measure-description")
            .setTextValue("text-measure-value");
    dbClient.customMeasureDao().insert(dbSession, customMeasure);
    dbSession.commit();
    when(system.now()).thenReturn(123_456_789L);

    WsTester.Result response =
        ws.newPostRequest(CustomMeasuresWs.ENDPOINT, UpdateAction.ACTION)
            .setParam(PARAM_ID, String.valueOf(customMeasure.getId()))
            .setParam(PARAM_DESCRIPTION, "new-custom-measure-description")
            .setParam(PARAM_VALUE, "new-text-measure-value")
            .execute();

    response.assertJson(getClass(), "custom-measure.json");
    String responseAsString = response.outputAsString();
    assertThat(responseAsString)
        .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", customMeasure.getId()));
    assertThat(responseAsString)
        .matches(String.format(".*\"id\"\\s*:\\s*\"%s\".*", metric.getId()));
    assertThat(responseAsString).matches(".*createdAt.*updatedAt.*");
  }
Esempio n. 4
0
 private void updateMetricInDb(
     DbSession dbSession, MetricDto metricInDb, MetricDto metricTemplate) {
   String key = metricTemplate.getKey();
   String name = metricTemplate.getShortName();
   String type = metricTemplate.getValueType();
   String domain = metricTemplate.getDomain();
   String description = metricTemplate.getDescription();
   if (key != null) {
     metricInDb.setKey(key);
   }
   if (name != null) {
     metricInDb.setShortName(name);
   }
   if (type != null) {
     metricInDb.setValueType(type);
   }
   if (domain != null) {
     metricInDb.setDomain(domain);
   }
   if (description != null) {
     metricInDb.setDescription(description);
   }
   dbClient.metricDao().update(dbSession, metricInDb);
   dbSession.commit();
 }
  public QualityGateConditionDto createCondition(
      DbSession dbSession,
      long qGateId,
      String metricKey,
      String operator,
      @Nullable String warningThreshold,
      @Nullable String errorThreshold,
      @Nullable Integer period) {
    getNonNullQgate(dbSession, qGateId);
    MetricDto metric = getNonNullMetric(dbSession, metricKey);
    validateCondition(metric, operator, warningThreshold, errorThreshold, period);
    checkConditionDoesNotAlreadyExistOnSameMetricAndPeriod(
        getConditions(dbSession, qGateId, null), metric, period);

    QualityGateConditionDto newCondition =
        new QualityGateConditionDto()
            .setQualityGateId(qGateId)
            .setMetricId(metric.getId())
            .setMetricKey(metric.getKey())
            .setOperator(operator)
            .setWarningThreshold(warningThreshold)
            .setErrorThreshold(errorThreshold)
            .setPeriod(period);
    dbClient.gateConditionDao().insert(newCondition, dbSession);
    return newCondition;
  }
 private static void checkRatingMetric(
     MetricDto metric,
     @Nullable String warningThreshold,
     @Nullable String errorThreshold,
     @Nullable Integer period,
     Errors errors) {
   if (!metric.getValueType().equals(RATING.name())) {
     return;
   }
   if (period != null && !metric.getKey().startsWith("new_")) {
     errors.add(
         Message.of(
             format("The metric '%s' cannot be used on the leak period", metric.getShortName())));
   }
   if (!isValidRating(warningThreshold)) {
     addInvalidRatingError(warningThreshold, errors);
     return;
   }
   if (!isValidRating(errorThreshold)) {
     addInvalidRatingError(errorThreshold, errors);
     return;
   }
   checkRatingGreaterThanOperator(warningThreshold, errors);
   checkRatingGreaterThanOperator(errorThreshold, errors);
 }
Esempio n. 7
0
 private void checkNoOtherMetricWithTargetKey(
     DbSession dbSession, MetricDto metricInDb, MetricDto template) {
   String targetKey = template.getKey();
   MetricDto metricWithTargetKey = dbClient.metricDao().selectByKey(dbSession, targetKey);
   if (isMetricFoundInDb(metricWithTargetKey)
       && !metricInDb.getId().equals(metricWithTargetKey.getId())) {
     throw new BadRequestException(
         String.format("The key '%s' is already used by an existing metric.", targetKey));
   }
 }
 @Override
 public Metric findByKey(String key) {
   DbSession session = dbClient.openSession(false);
   try {
     MetricDto dto = dbClient.metricDao().selectByKey(session, key);
     if (dto != null && dto.isEnabled()) {
       return ToMetric.INSTANCE.apply(dto);
     }
     return null;
   } finally {
     MyBatis.closeQuietly(session);
   }
 }
 private static void checkPeriod(MetricDto metric, @Nullable Integer period, Errors errors) {
   if (period == null) {
     errors.check(
         !metric.getKey().startsWith("new_"),
         "A period must be selected for differential metrics.");
   } else {
     errors.check(period == 1, "The only valid quality gate period is 1, the leak period.");
   }
 }
Esempio n. 10
0
 private void checkMetricInDbAndTemplate(
     DbSession dbSession, @Nullable MetricDto metricInDb, MetricDto template) {
   if (!isMetricFoundInDb(metricInDb)
       || isMetricDisabled(metricInDb)
       || !isMetricCustom(metricInDb)) {
     throw new BadRequestException(
         String.format("No active custom metric has been found for id '%d'.", template.getId()));
   }
   checkNoOtherMetricWithTargetKey(dbSession, metricInDb, template);
   if (haveMetricTypeChanged(metricInDb, template)) {
     List<CustomMeasureDto> customMeasures =
         dbClient.customMeasureDao().selectByMetricId(dbSession, metricInDb.getId());
     if (haveAssociatedCustomMeasures(customMeasures)) {
       throw new BadRequestException(
           String.format(
               "You're trying to change the type '%s' while there are associated custom measures.",
               metricInDb.getValueType()));
     }
   }
 }
Esempio n. 11
0
  private static MetricDto newMetricTemplate(Request request) {
    int id = request.mandatoryParamAsInt(PARAM_ID);
    String key = request.param(PARAM_KEY);
    if (key != null) {
      MetricKeyValidator.checkMetricKeyFormat(key);
    }
    String type = request.param(PARAM_TYPE);
    String name = request.param(PARAM_NAME);
    String domain = request.param(PARAM_DOMAIN);
    String description = request.param(PARAM_DESCRIPTION);

    MetricDto metricTemplate = new MetricDto().setId(id);
    if (key != null) {
      metricTemplate.setKey(key);
    }
    if (type != null) {
      metricTemplate.setValueType(type);
    }
    if (name != null) {
      metricTemplate.setShortName(name);
    }
    if (domain != null) {
      metricTemplate.setDomain(domain);
    }
    if (description != null) {
      metricTemplate.setDescription(description);
    }
    return metricTemplate;
  }
  public QualityGateConditionDto updateCondition(
      DbSession dbSession,
      long condId,
      String metricKey,
      String operator,
      @Nullable String warningThreshold,
      @Nullable String errorThreshold,
      @Nullable Integer period) {
    QualityGateConditionDto condition = getNonNullCondition(dbSession, condId);
    MetricDto metric = getNonNullMetric(dbSession, metricKey);
    validateCondition(metric, operator, warningThreshold, errorThreshold, period);
    checkConditionDoesNotAlreadyExistOnSameMetricAndPeriod(
        getConditions(dbSession, condition.getQualityGateId(), condition.getId()), metric, period);

    condition
        .setMetricId(metric.getId())
        .setMetricKey(metric.getKey())
        .setOperator(operator)
        .setWarningThreshold(warningThreshold)
        .setErrorThreshold(errorThreshold)
        .setPeriod(period);
    dbClient.gateConditionDao().update(condition, dbSession);
    return condition;
  }
  private static void checkConditionDoesNotAlreadyExistOnSameMetricAndPeriod(
      Collection<QualityGateConditionDto> conditions,
      MetricDto metric,
      @Nullable final Integer period) {
    if (conditions.isEmpty()) {
      return;
    }

    boolean conditionExists =
        conditions
            .stream()
            .anyMatch(
                c ->
                    c.getMetricId() == metric.getId() && ObjectUtils.equals(c.getPeriod(), period));
    if (conditionExists) {
      String errorMessage =
          period == null
              ? format("Condition on metric '%s' already exists.", metric.getShortName())
              : format(
                  "Condition on metric '%s' over leak period already exists.",
                  metric.getShortName());
      throw new BadRequestException(errorMessage);
    }
  }
Esempio n. 14
0
 private static void writeMetric(JsonWriter json, MetricDto metric) {
   json.beginObject();
   json.prop(FIELD_ID, String.valueOf(metric.getId()));
   json.prop(FIELD_KEY, metric.getKey());
   json.prop(FIELD_TYPE, metric.getValueType());
   json.prop(FIELD_NAME, metric.getShortName());
   json.prop(FIELD_DOMAIN, metric.getDomain());
   json.prop(FIELD_DESCRIPTION, metric.getDescription());
   json.endObject();
 }
 @Override
 public boolean apply(@Nonnull MetricDto dto) {
   return dto.isEnabled();
 }
 @Override
 public Metric apply(@Nonnull MetricDto dto) {
   Metric<Serializable> metric = new Metric<>();
   metric.setId(dto.getId());
   metric.setKey(dto.getKey());
   metric.setDescription(dto.getDescription());
   metric.setName(dto.getShortName());
   metric.setBestValue(dto.getBestValue());
   metric.setDomain(dto.getDomain());
   metric.setEnabled(dto.isEnabled());
   metric.setDirection(dto.getDirection());
   metric.setHidden(dto.isHidden());
   metric.setQualitative(dto.isQualitative());
   metric.setType(Metric.ValueType.valueOf(dto.getValueType()));
   metric.setOptimizedBestValue(dto.isOptimizedBestValue());
   metric.setUserManaged(dto.isUserManaged());
   metric.setWorstValue(dto.getWorstValue());
   return metric;
 }
Esempio n. 17
0
 private CustomMeasureDto newCustomMeasure(ComponentDto project, MetricDto metric) {
   return newCustomMeasureDto()
       .setMetricId(metric.getId())
       .setComponentUuid(project.uuid())
       .setCreatedAt(system.now());
 }
 private static void checkOperator(MetricDto metric, String operator, Errors errors) {
   ValueType valueType = valueOf(metric.getValueType());
   errors.check(
       isOperatorAllowed(operator, valueType),
       format("Operator %s is not allowed for metric type %s.", operator, metric.getValueType()));
 }
 @Override
 public boolean apply(@Nonnull MetricDto input) {
   return input.getKey().equals(metricKeyToSort);
 }
Esempio n. 20
0
 private static boolean isMetricDisabled(MetricDto metricInDb) {
   return !metricInDb.isEnabled();
 }
 private static boolean isAlertable(MetricDto metric) {
   return isAvailableForInit(metric) && BooleanUtils.isFalse(metric.isHidden());
 }
Esempio n. 22
0
 private static boolean isMetricCustom(MetricDto metricInDb) {
   return metricInDb.isUserManaged();
 }
 private static boolean isAvailableForInit(MetricDto metric) {
   return !metric.isDataType() && !CoreMetrics.ALERT_STATUS_KEY.equals(metric.getKey());
 }
Esempio n. 24
0
 private static boolean haveMetricTypeChanged(MetricDto metricInDb, MetricDto template) {
   return !metricInDb.getValueType().equals(template.getValueType())
       && template.getValueType() != null;
 }
 private static void validateMetric(MetricDto metric, Errors errors) {
   errors.check(
       isAlertable(metric),
       format("Metric '%s' cannot be used to define a condition.", metric.getKey()));
 }