Search in sources :

Example 6 with ResourceLoader

use of net.sourceforge.pmd.util.ResourceLoader in project pmd by pmd.

the class PMD method doPMD.

/**
 * This method is the main entry point for command line usage.
 *
 * @param configuration
 *            the configure to use
 * @return number of violations found.
 */
public static int doPMD(PMDConfiguration configuration) {
    // Load the RuleSets
    RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration, new ResourceLoader());
    RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(configuration.getRuleSets(), ruleSetFactory);
    if (ruleSets == null) {
        return 0;
    }
    Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
    List<DataSource> files = getApplicableFiles(configuration, languages);
    long reportStart = System.nanoTime();
    try {
        Renderer renderer = configuration.createRenderer();
        List<Renderer> renderers = Collections.singletonList(renderer);
        renderer.setWriter(IOUtil.createWriter(configuration.getReportFile()));
        renderer.start();
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
        RuleContext ctx = new RuleContext();
        final AtomicInteger violations = new AtomicInteger(0);
        ctx.getReport().addListener(new ThreadSafeReportListener() {

            @Override
            public void ruleViolationAdded(RuleViolation ruleViolation) {
                violations.incrementAndGet();
            }

            @Override
            public void metricAdded(Metric metric) {
            // ignored - not needed for counting violations
            }
        });
        processFiles(configuration, ruleSetFactory, files, ctx, renderers);
        reportStart = System.nanoTime();
        renderer.end();
        renderer.flush();
        return violations.get();
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null) {
            LOG.severe(message);
        } else {
            LOG.log(Level.SEVERE, "Exception during processing", e);
        }
        LOG.log(Level.FINE, "Exception during processing", e);
        LOG.info(PMDCommandLineInterface.buildUsageText());
        return 0;
    } finally {
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
        /*
             * Make sure it's our own classloader before attempting to close it....
             * Maven + Jacoco provide us with a cloaseable classloader that if closed
             * will throw a ClassNotFoundException.
            */
        if (configuration.getClassLoader() instanceof ClasspathClassLoader) {
            IOUtil.tryCloseClassLoader(configuration.getClassLoader());
        }
    }
}
Also used : ResourceLoader(net.sourceforge.pmd.util.ResourceLoader) URISyntaxException(java.net.URISyntaxException) SQLException(java.sql.SQLException) IOException(java.io.IOException) DataSource(net.sourceforge.pmd.util.datasource.DataSource) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) ClasspathClassLoader(net.sourceforge.pmd.util.ClasspathClassLoader) Language(net.sourceforge.pmd.lang.Language) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Renderer(net.sourceforge.pmd.renderers.Renderer) Metric(net.sourceforge.pmd.stat.Metric)

Example 7 with ResourceLoader

use of net.sourceforge.pmd.util.ResourceLoader in project pmd by pmd.

the class RuleSetFactoryTest method testExtendedReferences.

@Test
public void testExtendedReferences() throws Exception {
    InputStream in = new ResourceLoader().loadClassPathResourceAsStream("net/sourceforge/pmd/rulesets/reference-ruleset.xml");
    assertNotNull("Test ruleset not found - can't continue with test!", in);
    in.close();
    RuleSetFactory rsf = new RuleSetFactory();
    RuleSets rs = rsf.createRuleSets("net/sourceforge/pmd/rulesets/reference-ruleset.xml");
    // added by referencing a complete ruleset (TestRuleset1.xml)
    assertNotNull(rs.getRuleByName("MockRule1"));
    assertNotNull(rs.getRuleByName("MockRule2"));
    assertNotNull(rs.getRuleByName("MockRule3"));
    assertNotNull(rs.getRuleByName("TestRuleRef"));
    // added by specific reference
    assertNotNull(rs.getRuleByName("TestRule"));
    // this is from TestRuleset2.xml, but not referenced
    assertNull(rs.getRuleByName("TestRule2Ruleset2"));
    Rule mockRule3 = rs.getRuleByName("MockRule3");
    assertEquals("Overridden message", mockRule3.getMessage());
    assertEquals(2, mockRule3.getPriority().getPriority());
    Rule mockRule2 = rs.getRuleByName("MockRule2");
    assertEquals("Just combine them!", mockRule2.getMessage());
    // assert that MockRule2 is only once added to the ruleset, so that it
    // really
    // overwrites the configuration inherited from TestRuleset1.xml
    assertEquals(1, countRule(rs, "MockRule2"));
    Rule mockRule1 = rs.getRuleByName("MockRule1");
    assertNotNull(mockRule1);
    PropertyDescriptor<?> prop = mockRule1.getPropertyDescriptor("testIntProperty");
    Object property = mockRule1.getProperty(prop);
    assertEquals("5", String.valueOf(property));
    // included from TestRuleset3.xml
    assertNotNull(rs.getRuleByName("Ruleset3Rule2"));
    // excluded from TestRuleset3.xml
    assertNull(rs.getRuleByName("Ruleset3Rule1"));
    // overridden to 5
    Rule ruleset4Rule1 = rs.getRuleByName("Ruleset4Rule1");
    assertNotNull(ruleset4Rule1);
    assertEquals(5, ruleset4Rule1.getPriority().getPriority());
    assertEquals(1, countRule(rs, "Ruleset4Rule1"));
    // priority overridden for whole TestRuleset4 group
    Rule ruleset4Rule2 = rs.getRuleByName("Ruleset4Rule2");
    assertNotNull(ruleset4Rule2);
    assertEquals(2, ruleset4Rule2.getPriority().getPriority());
}
Also used : ResourceLoader(net.sourceforge.pmd.util.ResourceLoader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JavaUtilLoggingRule(net.sourceforge.pmd.junit.JavaUtilLoggingRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) Test(org.junit.Test)

Example 8 with ResourceLoader

use of net.sourceforge.pmd.util.ResourceLoader in project pmd by pmd.

the class RuleSetFactoryTest method testReferencePriority.

@Test
public void testReferencePriority() throws RuleSetNotFoundException {
    ResourceLoader rl = new ResourceLoader();
    RuleSetFactory rsf = new RuleSetFactory(rl, RulePriority.LOW, false, true);
    RuleSet ruleSet = rsf.createRuleSet(createRuleSetReferenceId(REF_INTERNAL_TO_INTERNAL_CHAIN));
    assertEquals("Number of Rules", 3, ruleSet.getRules().size());
    assertNotNull(ruleSet.getRuleByName("MockRuleName"));
    assertNotNull(ruleSet.getRuleByName("MockRuleNameRef"));
    assertNotNull(ruleSet.getRuleByName("MockRuleNameRefRef"));
    rsf = new RuleSetFactory(rl, RulePriority.MEDIUM_HIGH, false, true);
    ruleSet = rsf.createRuleSet(createRuleSetReferenceId(REF_INTERNAL_TO_INTERNAL_CHAIN));
    assertEquals("Number of Rules", 2, ruleSet.getRules().size());
    assertNotNull(ruleSet.getRuleByName("MockRuleNameRef"));
    assertNotNull(ruleSet.getRuleByName("MockRuleNameRefRef"));
    rsf = new RuleSetFactory(rl, RulePriority.HIGH, false, true);
    ruleSet = rsf.createRuleSet(createRuleSetReferenceId(REF_INTERNAL_TO_INTERNAL_CHAIN));
    assertEquals("Number of Rules", 1, ruleSet.getRules().size());
    assertNotNull(ruleSet.getRuleByName("MockRuleNameRefRef"));
    rsf = new RuleSetFactory(rl, RulePriority.LOW, false, true);
    ruleSet = rsf.createRuleSet(createRuleSetReferenceId(REF_INTERNAL_TO_EXTERNAL_CHAIN));
    assertEquals("Number of Rules", 3, ruleSet.getRules().size());
    assertNotNull(ruleSet.getRuleByName("ExternalRefRuleName"));
    assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRef"));
    assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRefRef"));
    rsf = new RuleSetFactory(rl, RulePriority.MEDIUM_HIGH, false, true);
    ruleSet = rsf.createRuleSet(createRuleSetReferenceId(REF_INTERNAL_TO_EXTERNAL_CHAIN));
    assertEquals("Number of Rules", 2, ruleSet.getRules().size());
    assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRef"));
    assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRefRef"));
    rsf = new RuleSetFactory(rl, RulePriority.HIGH, false, true);
    ruleSet = rsf.createRuleSet(createRuleSetReferenceId(REF_INTERNAL_TO_EXTERNAL_CHAIN));
    assertEquals("Number of Rules", 1, ruleSet.getRules().size());
    assertNotNull(ruleSet.getRuleByName("ExternalRefRuleNameRefRef"));
}
Also used : ResourceLoader(net.sourceforge.pmd.util.ResourceLoader) Test(org.junit.Test)

Example 9 with ResourceLoader

use of net.sourceforge.pmd.util.ResourceLoader in project pmd by pmd.

the class RuleSetFactoryTest method testOverridePriorityLoadWithMinimum.

@Test
public void testOverridePriorityLoadWithMinimum() throws RuleSetNotFoundException {
    RuleSetFactory rsf = new RuleSetFactory(new ResourceLoader(), RulePriority.MEDIUM_LOW, true, true);
    RuleSet ruleset = rsf.createRuleSet("net/sourceforge/pmd/rulesets/ruleset-minimum-priority.xml");
    // only one rule should remain, since we filter out the other rules by minimum priority
    assertEquals("Number of Rules", 1, ruleset.getRules().size());
    // Priority is overridden and applied, rule is missing
    assertNull(ruleset.getRuleByName("DummyBasicMockRule"));
    // that's the remaining rule
    assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
    // now, load with default minimum priority
    rsf = new RuleSetFactory();
    ruleset = rsf.createRuleSet("net/sourceforge/pmd/rulesets/ruleset-minimum-priority.xml");
    assertEquals("Number of Rules", 2, ruleset.getRules().size());
    Rule dummyBasicMockRule = ruleset.getRuleByName("DummyBasicMockRule");
    assertEquals("Wrong Priority", RulePriority.LOW, dummyBasicMockRule.getPriority());
}
Also used : ResourceLoader(net.sourceforge.pmd.util.ResourceLoader) JavaUtilLoggingRule(net.sourceforge.pmd.junit.JavaUtilLoggingRule) MockRule(net.sourceforge.pmd.lang.rule.MockRule) Test(org.junit.Test)

Example 10 with ResourceLoader

use of net.sourceforge.pmd.util.ResourceLoader in project pmd by pmd.

the class RuleSetReferenceIdTest method testConstructorGivenHttpUrlInputStream.

@Test
public void testConstructorGivenHttpUrlInputStream() throws Exception {
    String path = "/profiles/export?format=pmd&language=java&name=Sonar%2520way";
    String rulesetUrl = "http://localhost:" + wireMockRule.port() + path;
    stubFor(head(urlEqualTo(path)).willReturn(aResponse().withStatus(200)));
    stubFor(get(urlEqualTo(path)).willReturn(aResponse().withStatus(200).withHeader("Content-type", "text/xml").withBody("xyz")));
    RuleSetReferenceId ruleSetReferenceId = new RuleSetReferenceId("  " + rulesetUrl + "  ");
    assertRuleSetReferenceId(true, rulesetUrl, true, null, rulesetUrl, ruleSetReferenceId);
    try (InputStream inputStream = ruleSetReferenceId.getInputStream(new ResourceLoader())) {
        String loaded = IOUtils.toString(inputStream, "UTF-8");
        assertEquals("xyz", loaded);
    }
    verify(1, headRequestedFor(urlEqualTo(path)));
    verify(0, headRequestedFor(urlEqualTo("/profiles")));
    verify(1, getRequestedFor(urlEqualTo(path)));
    assertEquals(1, findAll(headRequestedFor(urlMatching(".*"))).size());
    assertEquals(1, findAll(getRequestedFor(urlMatching(".*"))).size());
}
Also used : ResourceLoader(net.sourceforge.pmd.util.ResourceLoader) InputStream(java.io.InputStream) Test(org.junit.Test)

Aggregations

ResourceLoader (net.sourceforge.pmd.util.ResourceLoader)13 Test (org.junit.Test)9 InputStream (java.io.InputStream)5 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ArrayList (java.util.ArrayList)2 Properties (java.util.Properties)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 JavaUtilLoggingRule (net.sourceforge.pmd.junit.JavaUtilLoggingRule)2 MockRule (net.sourceforge.pmd.lang.rule.MockRule)2 Renderer (net.sourceforge.pmd.renderers.Renderer)2 DataSource (net.sourceforge.pmd.util.datasource.DataSource)2 File (java.io.File)1 IOException (java.io.IOException)1 URISyntaxException (java.net.URISyntaxException)1 SQLException (java.sql.SQLException)1 LinkedList (java.util.LinkedList)1 StringTokenizer (java.util.StringTokenizer)1 Logger (java.util.logging.Logger)1 Report (net.sourceforge.pmd.Report)1 RuleContext (net.sourceforge.pmd.RuleContext)1