private void fireAnalysis(ScopesAgendaFilter scopesAgendaFilter) throws RuntimeException {

    verifier.fireAnalysis(scopesAgendaFilter);

    if (verifier.hasErrors()) {
      StringBuilder message = new StringBuilder("Verifier Errors:\n");
      for (VerifierError verifierError : verifier.getErrors()) {
        message.append("\t");
        message.append(verifierError.getMessage());
        message.append("\n");
      }
      throw new RuntimeException(message.toString());
    }
  }
  private void addHeaderToVerifier() {
    StringBuffer header = new StringBuffer();
    header.append("package " + packageItem.getName() + "\n");
    header.append(ServiceImplementation.getDroolsHeader(packageItem) + "\n");

    verifier.addResourcesToVerify(
        ResourceFactory.newReaderResource(new StringReader(header.toString())), ResourceType.DRL);
  }
Beispiel #3
0
  public void analyse(Project project, SensorContext context) {
    DroolsPlugin.configureSourceDir(project);
    Language drools = new Drools(project);
    ProjectFileSystem fileSystem = project.getFileSystem();
    Map<String, DroolsPackage> packageMap = new HashMap<String, DroolsPackage>();
    VerifierBuilder verifierBuilder = VerifierBuilderFactory.newVerifierBuilder();
    for (File file : fileSystem.getSourceFiles(drools)) {
      Verifier verifier = verifierBuilder.newVerifier();
      try {
        DroolsFile resource = DroolsFile.fromIOFile(file, false);
        Source source = analyseSourceCode(file);
        if (source != null) {
          context.saveMeasure(
              resource, CoreMetrics.LINES, (double) source.getMeasure(Metric.LINES));
          context.saveMeasure(
              resource, CoreMetrics.NCLOC, (double) source.getMeasure(Metric.LINES_OF_CODE));
          context.saveMeasure(
              resource,
              CoreMetrics.COMMENT_LINES,
              (double) source.getMeasure(Metric.COMMENT_LINES));
        }
        context.saveMeasure(resource, CoreMetrics.FILES, 1.0);
        context.saveMeasure(
            resource,
            CoreMetrics.CLASSES,
            (double)
                (resource.getPackageDescr().getRules().size()
                    + resource.getPackageDescr().getFunctions().size()));
        packageMap.put(resource.getParent().getKey(), resource.getParent());

        verifier.addResourcesToVerify(new FileSystemResource(file), ResourceType.DRL);
        verifier.fireAnalysis();
        saveViolations(resource, context, verifier.getResult());
      } catch (Throwable e) {
        DroolsPlugin.LOG.error(
            "error while verifier analyzing '" + file.getAbsolutePath() + "'", e);
      } finally {
        verifier.dispose();
      }
    }

    for (DroolsPackage droolsPackage : packageMap.values()) {
      context.saveMeasure(droolsPackage, CoreMetrics.PACKAGES, 1.0);
    }
  }
  @Test
  public void testSubruleSubsumption1() throws Exception {

    VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();

    Verifier verifier = vBuilder.newVerifier();

    verifier.addResourcesToVerify(
        ResourceFactory.newClassPathResource("SubsumptantSubRules1.drl", getClass()),
        ResourceType.DRL);

    //        for ( VerifierError error : verifier.getMissingClasses() ) {
    //            System.out.println( error.getMessage() );
    //        }

    assertFalse(verifier.hasErrors());

    boolean noProblems = verifier.fireAnalysis();
    assertTrue(noProblems);

    Collection<Object> subsumptionList =
        ((VerifierImpl) verifier)
            .getKnowledgeSession()
            .getObjects(new ClassObjectFilter(Subsumption.class));

    int count = 0;
    for (Object object : subsumptionList) {
      //                        System.out.println( " * " + ((Subsumption) object) );
      if (((VerifierComponent) ((Subsumption) object).getLeft())
          .getVerifierComponentType()
          .equals(VerifierComponentType.SUB_RULE)) {
        //                System.out.println( " ** " + ((SubRule) ((Subsumption)
        // object).getLeft()).getItems() + " - " + ((SubRule) ((Subsumption)
        // object).getRight()).getItems() );
        count++;
      }
    }
    assertEquals(2, count);

    verifier.dispose();
  }
  private void addToVerifier(AssetItemIterator assets, ResourceType resourceType) {
    while (assets.hasNext()) {
      AssetItem asset = assets.next();
      if (!asset.isArchived() && !asset.getDisabled()) {
        if (resourceType == ResourceType.DTABLE) {
          DecisionTableConfiguration dtableconfiguration =
              KnowledgeBuilderFactory.newDecisionTableConfiguration();
          dtableconfiguration.setInputType(DecisionTableInputType.XLS);

          verifier.addResourcesToVerify(
              ResourceFactory.newByteArrayResource(asset.getBinaryContentAsBytes()),
              resourceType,
              (ResourceConfiguration) dtableconfiguration);
        } else {
          verifier.addResourcesToVerify(
              ResourceFactory.newReaderResource(new StringReader(asset.getContent())),
              resourceType);
        }
      }
    }
  }
  @Override
  public AnalysisReport verify() {
    addHeaderToVerifier();

    addRuleAssetToVerifier();

    fireAnalysis();

    VerifierReport report = verifier.getResult();

    return VerifierReportCreator.doReport(report);
  }
  private AnalysisReport performAssetVerification(
      RuleAsset asset, boolean useVerifierDefaultConfig, Set<String> activeWorkingSets)
      throws SerializationException {
    long startTime = System.currentTimeMillis();

    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(
              new PackageNameType(asset.getMetaData().getPackageName()),
              RoleType.PACKAGE_DEVELOPER.getName());
    }

    PackageItem packageItem =
        getAssetService().getRulesRepository().loadPackage(asset.getMetaData().getPackageName());

    List<String> constraintRules = applyWorkingSets(activeWorkingSets);

    Verifier verifierToBeUsed = null;
    if (useVerifierDefaultConfig) {
      verifierToBeUsed = defaultVerifier;
    } else {
      verifierToBeUsed = getWorkingSetVerifier(constraintRules);
    }

    log.debug("constraints rules: " + constraintRules);

    try {
      VerifierRunner runner = new VerifierRunner(verifierToBeUsed);
      AnalysisReport report = runner.verify(packageItem, chooseScopesAgendaFilterFor(asset));

      verifierToBeUsed.flushKnowledgeSession();

      log.debug("Asset verification took: " + (System.currentTimeMillis() - startTime));

      return report;

    } catch (Throwable t) {
      throw new SerializationException(t.getMessage());
    }
  }
  private void addRuleAssetToVerifier() {

    ContentHandler handler = ContentManager.getHandler(ruleAsset.getFormat());

    if (!(handler instanceof IRuleAsset)) {
      throw new IllegalStateException("IRuleAsset Expected");
    }

    RuleModel model = (RuleModel) ruleAsset.getContent();

    String brl = BRXMLPersistence.getInstance().marshal(model);

    verifier.addResourcesToVerify(
        ResourceFactory.newByteArrayResource(brl.getBytes()), ResourceType.BRL);
  }
  private void addDRLRulesToVerifier() {

    AssetItemIterator rules = packageItem.listAssetsByFormat(AssetFormats.DRL);

    while (rules.hasNext()) {
      AssetItem rule = rules.next();

      ContentHandler contentHandler = ContentManager.getHandler(rule.getFormat());
      if (contentHandler.isRuleAsset()) {
        IRuleAsset ruleAsset = (IRuleAsset) contentHandler;
        String drl = ruleAsset.getRawDRL(rule);
        verifier.addResourcesToVerify(
            ResourceFactory.newReaderResource(new StringReader(drl)), ResourceType.DRL);
      }
    }
  }
  @WebRemote
  @Restrict("#{identity.loggedIn}")
  public AnalysisReport analysePackage(String packageUUID) throws SerializationException {
    if (Contexts.isSessionContextActive()) {
      Identity.instance()
          .checkPermission(new PackageUUIDType(packageUUID), RoleType.PACKAGE_DEVELOPER.getName());
    }

    PackageItem packageItem = getAssetService().getRulesRepository().loadPackageByUUID(packageUUID);

    VerifierRunner runner = new VerifierRunner(defaultVerifier);

    AnalysisReport report =
        runner.verify(
            packageItem,
            new ScopesAgendaFilter(true, ScopesAgendaFilter.VERIFYING_SCOPE_KNOWLEDGE_PACKAGE));

    defaultVerifier.flushKnowledgeSession();

    return report;
  }
  public AnalysisReport verify(PackageItem packageItem, ScopesAgendaFilter scopesAgendaFilter) {
    this.packageItem = packageItem;

    addHeaderToVerifier();

    addToVerifier(
        packageItem.listAssetsByFormat(new String[] {AssetFormats.DSL}), ResourceType.DSL);

    // TODO: Model JARS

    addToVerifier(
        packageItem.listAssetsByFormat(new String[] {AssetFormats.DRL_MODEL}), ResourceType.DRL);

    addToVerifier(
        packageItem.listAssetsByFormat(new String[] {AssetFormats.FUNCTION}), ResourceType.DRL);

    addToVerifier(
        packageItem.listAssetsByFormat(new String[] {AssetFormats.DSL_TEMPLATE_RULE}),
        ResourceType.DSLR);

    addToVerifier(
        packageItem.listAssetsByFormat(new String[] {AssetFormats.DECISION_SPREADSHEET_XLS}),
        ResourceType.DTABLE);

    addGuidedDecisionTablesToVerifier();

    addDRLRulesToVerifier();

    addToVerifier(
        packageItem.listAssetsByFormat(new String[] {AssetFormats.BUSINESS_RULE}),
        ResourceType.BRL);

    fireAnalysis(scopesAgendaFilter);

    VerifierReport report = verifier.getResult();

    return VerifierReportCreator.doReport(report);
  }
Beispiel #12
0
  @Test
  @Ignore("08-APR-2011 temporally ignoring -Rikkola-")
  public void testCauseTrace() throws Exception {

    VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();

    // Check that the builder works.
    assertFalse(vBuilder.hasErrors());
    assertEquals(0, vBuilder.getErrors().size());

    Verifier verifier = vBuilder.newVerifier();

    verifier.addResourcesToVerify(
        new ClassPathResource("Causes.drl", getClass()), ResourceType.DRL);

    assertFalse(verifier.hasErrors());
    assertEquals(0, verifier.getErrors().size());

    boolean works = verifier.fireAnalysis();

    assertTrue(works);

    VerifierReport result = verifier.getResult();
    assertNotNull(result);
    assertEquals(0, result.getBySeverity(Severity.ERROR).size());
    Collection<VerifierMessageBase> warnings = result.getBySeverity(Severity.WARNING);
    Collection<VerifierMessageBase> redundancyWarnings = new ArrayList<VerifierMessageBase>();

    for (VerifierMessageBase verifierMessageBase : warnings) {
      if (verifierMessageBase.getMessageType().equals(MessageType.REDUNDANCY)) {
        redundancyWarnings.add(verifierMessageBase);
      }
    }

    assertEquals(1, redundancyWarnings.size());

    VerifierMessage message = (VerifierMessage) redundancyWarnings.toArray()[0];

    //        System.out.println( message );

    assertEquals(2, message.getImpactedRules().size());

    assertTrue(message.getImpactedRules().values().contains("Your First Rule"));
    assertTrue(message.getImpactedRules().values().contains("Your Second Rule"));

    Cause[] causes = message.getCauses().toArray(new Cause[message.getCauses().size()]);

    assertEquals(1, causes.length);
    causes = causes[0].getCauses().toArray(new Cause[causes[0].getCauses().size()]);

    assertEquals(2, causes.length);

    causes = causes[0].getCauses().toArray(new Cause[causes[0].getCauses().size()]);

    assertEquals(1, causes.length);

    causes = causes[0].getCauses().toArray(new Cause[causes[0].getCauses().size()]);

    assertEquals(1, causes.length);

    causes = causes[0].getCauses().toArray(new Cause[causes[0].getCauses().size()]);

    assertEquals(2, causes.length);

    assertEquals(0, result.getBySeverity(Severity.NOTE).size());
  }