Exemplo n.º 1
0
  private void disableDeprecatedUserRules(DatabaseSession session) {
    List<Integer> deprecatedUserRuleIds = Lists.newLinkedList();
    deprecatedUserRuleIds.addAll(
        session
            .createQuery(
                "SELECT r.id FROM "
                    + Rule.class.getSimpleName()
                    + " r WHERE r.parent IS NOT NULL AND NOT EXISTS(FROM "
                    + Rule.class.getSimpleName()
                    + " p WHERE r.parent=p)")
            .getResultList());

    deprecatedUserRuleIds.addAll(
        session
            .createQuery(
                "SELECT r.id FROM "
                    + Rule.class.getSimpleName()
                    + " r WHERE r.parent IS NOT NULL AND EXISTS(FROM "
                    + Rule.class.getSimpleName()
                    + " p WHERE r.parent=p and p.enabled=false)")
            .getResultList());

    for (Integer deprecatedUserRuleId : deprecatedUserRuleIds) {
      Rule rule = session.getSingleResult(Rule.class, "id", deprecatedUserRuleId);
      rule.setEnabled(false);
      session.saveWithoutFlush(rule);
    }
  }
 void persistConfiguration() {
   List<PastSnapshot> pastSnapshots = configuration.getProjectPastSnapshots();
   for (PastSnapshot pastSnapshot : pastSnapshots) {
     projectSnapshot = session.reattach(Snapshot.class, projectSnapshot.getId());
     projectSnapshot.setPeriodMode(pastSnapshot.getIndex(), pastSnapshot.getMode());
     projectSnapshot.setPeriodModeParameter(
         pastSnapshot.getIndex(), pastSnapshot.getModeParameter());
     projectSnapshot.setPeriodDate(pastSnapshot.getIndex(), pastSnapshot.getTargetDate());
     session.save(projectSnapshot);
   }
   session.commit();
 }
Exemplo n.º 3
0
 public ValidationMessages restoreProfile(String xmlBackup) {
   ValidationMessages messages = ValidationMessages.create();
   RulesProfile profile = xmlProfileParser.parse(new StringReader(xmlBackup), messages);
   if (profile != null) {
     DatabaseSession session = sessionFactory.getSession();
     RulesProfile existingProfile =
         session.getSingleResult(
             RulesProfile.class, "name", profile.getName(), "language", profile.getLanguage());
     if (existingProfile != null) {
       messages.addErrorText(
           "The profile " + profile + " already exists. Please delete it before restoring.");
     } else if (!messages.hasErrors()) {
       session.saveWithoutFlush(profile);
       session.commit();
     }
   }
   return messages;
 }
Exemplo n.º 4
0
 public void importProfile(RulesDao rulesDao, RulesProfile toImport) {
   if (toImport.getEnabled() == null) {
     // backward-compatibility with versions < 2.6. The field "enabled" did not exist. Default
     // value is true.
     toImport.setEnabled(true);
   }
   importActiveRules(rulesDao, toImport);
   importAlerts(toImport);
   session.save(toImport);
 }
Exemplo n.º 5
0
  public void exportXml(SonarConfig sonarConfig) {
    this.profiles =
        (this.profiles == null ? session.getResults(RulesProfile.class) : this.profiles);
    // the profiles objects must be cloned to avoid issues CGLib
    List<RulesProfile> cloned = new ArrayList<RulesProfile>();
    for (RulesProfile profile : this.profiles) {
      cloned.add((RulesProfile) profile.clone());
    }

    sonarConfig.setProfiles(cloned);
  }
Exemplo n.º 6
0
 /** Important : the ruby controller has already create the profile */
 public ValidationMessages importProfile(
     String profileName, String language, String importerKey, String profileDefinition) {
   ValidationMessages messages = ValidationMessages.create();
   ProfileImporter importer = getProfileImporter(importerKey);
   RulesProfile profile = importer.importProfile(new StringReader(profileDefinition), messages);
   if (!messages.hasErrors()) {
     DatabaseSession session = sessionFactory.getSession();
     RulesProfile persistedProfile =
         session.getSingleResult(RulesProfile.class, "name", profileName, "language", language);
     for (ActiveRule activeRule : profile.getActiveRules()) {
       ActiveRule persistedActiveRule =
           persistedProfile.activateRule(activeRule.getRule(), activeRule.getSeverity());
       for (ActiveRuleParam activeRuleParam : activeRule.getActiveRuleParams()) {
         persistedActiveRule.setParameter(activeRuleParam.getKey(), activeRuleParam.getValue());
       }
     }
     session.saveWithoutFlush(persistedProfile);
     session.commit();
   }
   return messages;
 }
Exemplo n.º 7
0
  public void start() {
    TimeProfiler profiler = new TimeProfiler();

    DatabaseSession session = sessionFactory.getSession();
    disableAllRules(session);
    for (RuleRepository repository : repositories) {
      profiler.start(
          "Register rules ["
              + repository.getKey()
              + "/"
              + StringUtils.defaultString(repository.getLanguage(), "-")
              + "]");
      registerRepository(repository, session);
      profiler.stop();
    }

    profiler.start("Disable deprecated user rules");
    disableDeprecatedUserRules(session);
    profiler.stop();

    session.commit();
  }
Exemplo n.º 8
0
  public void execute(SensorContext context) {
    Collection<Sensor> sensors = selector.select(Sensor.class, module, true, sensorMatcher);
    eventBus.fireEvent(new SensorsPhaseEvent(Lists.newArrayList(sensors), true));

    for (Sensor sensor : sensors) {
      // SONAR-2965 In case the sensor takes too much time we close the session to not face a
      // timeout
      session.commitAndClose();

      executeSensor(context, sensor);
    }

    eventBus.fireEvent(new SensorsPhaseEvent(Lists.newArrayList(sensors), false));
  }
 /**
  * Only used to get the real date of the snapshot on the current period. The date is used to
  * calculate new_violations measures
  */
 @CheckForNull
 private Snapshot findSnapshot(Snapshot projectSnapshot) {
   String hql =
       "from "
           + Snapshot.class.getSimpleName()
           + " where resourceId=:resourceId and (rootId=:rootSnapshotId or id=:rootSnapshotId)";
   List<Snapshot> snapshots =
       session
           .createQuery(hql)
           .setParameter("resourceId", projectSnapshot.getResourceId())
           .setParameter("rootSnapshotId", projectSnapshot.getId())
           .setMaxResults(1)
           .getResultList();
   return snapshots.isEmpty() ? null : snapshots.get(0);
 }
Exemplo n.º 10
0
  private void updateRule(Rule persistedRule, Rule rule, DatabaseSession session) {
    persistedRule.setName(rule.getName());
    persistedRule.setConfigKey(rule.getConfigKey());
    persistedRule.setDescription(rule.getDescription());
    persistedRule.setSeverity(rule.getSeverity());
    persistedRule.setEnabled(true);
    persistedRule.setCardinality(rule.getCardinality());

    // delete deprecated params
    deleteDeprecatedParameters(persistedRule, rule, session);

    // add new params and update existing params
    updateParameters(persistedRule, rule);

    session.saveWithoutFlush(persistedRule);
  }
Exemplo n.º 11
0
 private void deleteDeprecatedParameters(Rule persistedRule, Rule rule, DatabaseSession session) {
   if (persistedRule.getParams() != null && persistedRule.getParams().size() > 0) {
     for (Iterator<RuleParam> it = persistedRule.getParams().iterator(); it.hasNext(); ) {
       RuleParam persistedParam = it.next();
       if (rule.getParam(persistedParam.getKey()) == null) {
         it.remove();
         session
             .createQuery(
                 "delete from "
                     + ActiveRuleParam.class.getSimpleName()
                     + " where ruleParam=:param")
             .setParameter("param", persistedParam)
             .executeUpdate();
       }
     }
   }
 }
Exemplo n.º 12
0
 private void importAlerts(RulesProfile profile) {
   if (profile.getAlerts() != null) {
     for (Iterator<Alert> ia = profile.getAlerts().iterator(); ia.hasNext(); ) {
       Alert alert = ia.next();
       Metric unMarshalledMetric = alert.getMetric();
       String validKey = unMarshalledMetric.getKey();
       Metric matchingMetricInDb = session.getSingleResult(Metric.class, "key", validKey);
       if (matchingMetricInDb == null) {
         LoggerFactory.getLogger(getClass()).error("Unable to find metric " + validKey);
         ia.remove();
         continue;
       }
       alert.setMetric(matchingMetricInDb);
       alert.setRulesProfile(profile);
     }
   }
 }
Exemplo n.º 13
0
  public Measure reloadMeasure(Measure measure) {
    if (measure.getId() != null
        && dataIdByMeasureId.containsKey(measure.getId())
        && !measure.hasData()) {
      Integer dataId = dataIdByMeasureId.get(measure.getId());
      MeasureData data = session.getSingleResult(MeasureData.class, "id", dataId);
      if (data == null) {
        LOG.error("The MEASURE_DATA row with id {} is lost", dataId);

      } else {
        if (LOG.isDebugEnabled()) {
          LOG.debug("Reload the data measure: {}, id={}", measure.getMetricKey(), measure.getId());
        }
        measure.setData(data.getText());
        loadedMeasures.add(measure);
      }
    }
    return measure;
  }
Exemplo n.º 14
0
  private void registerRepository(RuleRepository repository, DatabaseSession session) {
    Map<String, Rule> rulesByKey = Maps.newHashMap();
    for (Rule rule : repository.createRules()) {
      rule.setRepositoryKey(repository.getKey());
      rulesByKey.put(rule.getKey(), rule);
    }
    Logs.INFO.info(rulesByKey.size() + " rules");

    List<Rule> persistedRules = session.getResults(Rule.class, "pluginName", repository.getKey());
    for (Rule persistedRule : persistedRules) {
      Rule rule = rulesByKey.get(persistedRule.getKey());
      if (rule != null) {
        updateRule(persistedRule, rule, session);
        rulesByKey.remove(rule.getKey());
      }
    }

    saveNewRules(rulesByKey.values(), session);
  }
Exemplo n.º 15
0
 public void onSensorExecution(SensorExecutionEvent event) {
   if (event.isEnd()) {
     flushMemory();
     session.commit();
   }
 }
Exemplo n.º 16
0
 public void onDecoratorsPhase(DecoratorsPhaseEvent event) {
   if (event.isEnd()) {
     session.commit();
   }
 }
Exemplo n.º 17
0
 private RulesProfile loadProfile(DatabaseSession session, int profileId) {
   return session.getSingleResult(RulesProfile.class, "id", profileId);
 }
Exemplo n.º 18
0
 private void disableAllRules(DatabaseSession session) {
   session
       .createQuery(
           "UPDATE " + Rule.class.getSimpleName() + " SET enabled=false WHERE parent IS NULL")
       .executeUpdate();
 }
Exemplo n.º 19
0
 private void saveNewRules(Collection<Rule> rules, DatabaseSession session) {
   for (Rule rule : rules) {
     rule.setEnabled(true);
     session.saveWithoutFlush(rule);
   }
 }