Search in sources :

Example 31 with LanguageVersion

use of net.sourceforge.pmd.lang.LanguageVersion in project pmd by pmd.

the class LanguageVersionDiscovererTest method testPython.

/**
 * Test on Python file with default version
 */
@Test
public void testPython() {
    LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer();
    File pythonFile = new File("/path/to/MY_PACKAGE.py");
    LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(pythonFile);
    assertEquals("LanguageVersion must be Python!", LanguageRegistry.getLanguage(PythonLanguageModule.NAME).getDefaultVersion(), languageVersion);
}
Also used : LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) LanguageVersionDiscoverer(net.sourceforge.pmd.lang.LanguageVersionDiscoverer) File(java.io.File) Test(org.junit.Test)

Example 32 with LanguageVersion

use of net.sourceforge.pmd.lang.LanguageVersion in project pmd by pmd.

the class LanguageVersionDiscovererTest method testJspFile.

/**
 * Test on JSP file.
 */
@Test
public void testJspFile() {
    LanguageVersionDiscoverer discoverer = new LanguageVersionDiscoverer();
    File jspFile = new File("/path/to/MyPage.jsp");
    LanguageVersion languageVersion = discoverer.getDefaultLanguageVersionForFile(jspFile);
    assertEquals("LanguageVersion must be JSP!", LanguageRegistry.getLanguage(JspLanguageModule.NAME).getDefaultVersion(), languageVersion);
}
Also used : LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) LanguageVersionDiscoverer(net.sourceforge.pmd.lang.LanguageVersionDiscoverer) File(java.io.File) Test(org.junit.Test)

Example 33 with LanguageVersion

use of net.sourceforge.pmd.lang.LanguageVersion in project maven-plugins by apache.

the class PmdReport method getPMDConfiguration.

/**
 * Constructs the PMD configuration class, passing it an argument that configures the target JDK.
 *
 * @return the resulting PMD
 * @throws org.apache.maven.reporting.MavenReportException if targetJdk is not supported
 */
public PMDConfiguration getPMDConfiguration() throws MavenReportException {
    PMDConfiguration configuration = new PMDConfiguration();
    LanguageVersion languageVersion = null;
    if (("java".equals(language) || null == language) && null != targetJdk) {
        languageVersion = LanguageRegistry.findLanguageVersionByTerseName("java " + targetJdk);
        if (languageVersion == null) {
            throw new MavenReportException("Unsupported targetJdk value '" + targetJdk + "'.");
        }
    } else if ("javascript".equals(language) || "ecmascript".equals(language)) {
        languageVersion = LanguageRegistry.findLanguageVersionByTerseName("ecmascript");
    } else if ("jsp".equals(language)) {
        languageVersion = LanguageRegistry.findLanguageVersionByTerseName("jsp");
    }
    if (languageVersion != null) {
        getLog().debug("Using language " + languageVersion);
        configuration.setDefaultLanguageVersion(languageVersion);
    }
    if (typeResolution) {
        try {
            @SuppressWarnings("unchecked") List<String> classpath = includeTests ? project.getTestClasspathElements() : project.getCompileClasspathElements();
            getLog().debug("Using aux classpath: " + classpath);
            configuration.prependClasspath(StringUtils.join(classpath.iterator(), File.pathSeparator));
        } catch (Exception e) {
            throw new MavenReportException(e.getMessage(), e);
        }
    }
    if (null != suppressMarker) {
        configuration.setSuppressMarker(suppressMarker);
    }
    configuration.setBenchmark(benchmark);
    if (analysisCache) {
        configuration.setAnalysisCacheLocation(analysisCacheLocation);
        getLog().debug("Using analysis cache location: " + analysisCacheLocation);
    }
    return configuration;
}
Also used : LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) ResourceNotFoundException(org.codehaus.plexus.resource.loader.ResourceNotFoundException) MavenReportException(org.apache.maven.reporting.MavenReportException) IOException(java.io.IOException) FileResourceCreationException(org.codehaus.plexus.resource.loader.FileResourceCreationException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) FileNotFoundException(java.io.FileNotFoundException) PMDConfiguration(net.sourceforge.pmd.PMDConfiguration) MavenReportException(org.apache.maven.reporting.MavenReportException)

Example 34 with LanguageVersion

use of net.sourceforge.pmd.lang.LanguageVersion in project pmd-eclipse-plugin by pmd.

the class BaseVisitor method reviewResource.

/**
 * Run PMD against a resource
 *
 * @param resource
 *            the resource to process
 */
protected final void reviewResource(IResource resource) {
    IFile file = (IFile) resource.getAdapter(IFile.class);
    if (file == null || file.getFileExtension() == null) {
        return;
    }
    Reader input = null;
    try {
        boolean included = isIncluded(file);
        LOG.debug("Derived files included: " + projectProperties.isIncludeDerivedFiles());
        LOG.debug("file " + file.getName() + " is derived: " + file.isDerived());
        LOG.debug("file checked: " + included);
        prepareMarkerAccumulator(file);
        LanguageVersionDiscoverer languageDiscoverer = new LanguageVersionDiscoverer();
        LanguageVersion languageVersion = languageDiscoverer.getDefaultLanguageVersionForFile(file.getName());
        // in case it is java, select the correct java version
        if (languageVersion != null && languageVersion.getLanguage() == LanguageRegistry.getLanguage(JavaLanguageModule.NAME)) {
            languageVersion = PMDPlugin.javaVersionFor(file.getProject());
        }
        if (languageVersion != null) {
            configuration().setDefaultLanguageVersion(languageVersion);
        }
        LOG.debug("discovered language: " + languageVersion);
        PMDPlugin.setJavaClassLoader(configuration(), resource.getProject());
        final File sourceCodeFile = file.getRawLocation().toFile();
        if (included && getRuleSet().applies(sourceCodeFile) && isFileInWorkingSet(file) && languageVersion != null) {
            subTask("PMD checking: " + file.getName());
            Timer timer = new Timer();
            RuleContext context = PMD.newRuleContext(file.getName(), sourceCodeFile);
            context.setLanguageVersion(languageVersion);
            input = new InputStreamReader(file.getContents(), file.getCharset());
            // getPmdEngine().processFile(input, getRuleSet(), context);
            // getPmdEngine().processFile(sourceCodeFile, getRuleSet(),
            // context);
            DataSource dataSource = new ReaderDataSource(input, file.getName());
            RuleSetFactory ruleSetFactory = new RuleSetFactory() {

                @Override
                public synchronized RuleSets createRuleSets(String referenceString) throws RuleSetNotFoundException {
                    return new RuleSets(getRuleSet());
                }
            };
            // need to disable multi threading, as the ruleset is
            // not recreated and shared between threads...
            // but as we anyway have only one file to process, it won't hurt
            // here.
            configuration().setThreads(0);
            LOG.debug("PMD running on file " + file.getName());
            final Report collectingReport = new Report();
            Renderer collectingRenderer = new AbstractRenderer("collectingRenderer", "Renderer that collect violations") {

                @Override
                public void startFileAnalysis(DataSource dataSource) {
                // TODO Auto-generated method stub
                }

                @Override
                public void start() throws IOException {
                // TODO Auto-generated method stub
                }

                @Override
                public void renderFileReport(Report report) throws IOException {
                    for (RuleViolation v : report) {
                        collectingReport.addRuleViolation(v);
                    }
                    for (Iterator<ProcessingError> it = report.errors(); it.hasNext(); ) {
                        collectingReport.addError(it.next());
                    }
                    for (Iterator<ConfigurationError> it = report.configErrors(); it.hasNext(); ) {
                        collectingReport.addConfigError(it.next());
                    }
                }

                @Override
                public void end() throws IOException {
                // TODO Auto-generated method stub
                }

                @Override
                public String defaultFileExtension() {
                    // TODO Auto-generated method stub
                    return null;
                }
            };
            // PMD.processFiles(configuration(), ruleSetFactory,
            // Arrays.asList(dataSource), context,
            // Arrays.asList(collectingRenderer));
            new MonoThreadProcessor(configuration()).processFiles(ruleSetFactory, Arrays.asList(dataSource), context, Arrays.asList(collectingRenderer));
            LOG.debug("PMD run finished.");
            timer.stop();
            pmdDuration += timer.getDuration();
            LOG.debug("PMD found " + collectingReport.size() + " violations for file " + file.getName());
            if (collectingReport.hasConfigErrors()) {
                StringBuilder message = new StringBuilder("There were configuration errors!\n");
                Iterator<ConfigurationError> errors = collectingReport.configErrors();
                while (errors.hasNext()) {
                    ConfigurationError error = errors.next();
                    message.append(error.rule().getName()).append(": ").append(error.issue()).append('\n');
                }
                PMDPlugin.getDefault().logWarn(message.toString());
                LOG.warn(message);
            }
            if (collectingReport.hasErrors()) {
                StringBuilder message = new StringBuilder("There were processing errors!\n");
                Iterator<ProcessingError> errors = collectingReport.errors();
                while (errors.hasNext()) {
                    ProcessingError error = errors.next();
                    message.append(error.getFile()).append(": ").append(error.getMsg()).append(' ').append(error.getDetail()).append("\n");
                }
                PMDPlugin.getDefault().logWarn(message.toString());
                throw new PMDException(message.toString());
            }
            updateMarkers(file, collectingReport.iterator(), isUseTaskMarker());
            worked(1);
            fileCount++;
        } else {
            LOG.debug("The file " + file.getName() + " is not in the working set");
        }
    } catch (CoreException e) {
        // TODO: complete message
        LOG.error("Core exception visiting " + file.getName(), e);
    } catch (PMDException e) {
        // TODO: complete message
        LOG.error("PMD exception visiting " + file.getName(), e);
    } catch (IOException e) {
        // TODO: complete message
        LOG.error("IO exception visiting " + file.getName(), e);
    } catch (PropertiesException e) {
        // TODO: complete message
        LOG.error("Properties exception visiting " + file.getName(), e);
    } catch (IllegalArgumentException e) {
        LOG.error("Illegal argument", e);
    } finally {
        IOUtil.closeQuietly(input);
    }
}
Also used : IFile(org.eclipse.core.resources.IFile) RuleContext(net.sourceforge.pmd.RuleContext) PropertiesException(net.sourceforge.pmd.eclipse.runtime.properties.PropertiesException) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) RuleViolation(net.sourceforge.pmd.RuleViolation) LanguageVersionDiscoverer(net.sourceforge.pmd.lang.LanguageVersionDiscoverer) ProcessingError(net.sourceforge.pmd.Report.ProcessingError) RuleSetFactory(net.sourceforge.pmd.RuleSetFactory) RuleSets(net.sourceforge.pmd.RuleSets) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) InputStreamReader(java.io.InputStreamReader) Report(net.sourceforge.pmd.Report) MonoThreadProcessor(net.sourceforge.pmd.processor.MonoThreadProcessor) IOException(java.io.IOException) DataSource(net.sourceforge.pmd.util.datasource.DataSource) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) ConfigurationError(net.sourceforge.pmd.Report.ConfigurationError) ReaderDataSource(net.sourceforge.pmd.util.datasource.ReaderDataSource) Timer(name.herlin.command.Timer) CoreException(org.eclipse.core.runtime.CoreException) AbstractRenderer(net.sourceforge.pmd.renderers.AbstractRenderer) Renderer(net.sourceforge.pmd.renderers.Renderer) AbstractRenderer(net.sourceforge.pmd.renderers.AbstractRenderer) PMDException(net.sourceforge.pmd.PMDException) IFile(org.eclipse.core.resources.IFile) File(java.io.File)

Example 35 with LanguageVersion

use of net.sourceforge.pmd.lang.LanguageVersion in project pmd-eclipse-plugin by pmd.

the class RulePanelManager method buildLanguageVersionCombo.

private Combo buildLanguageVersionCombo(Composite parent, final boolean isMinVersion) {
    int style = creatingNewRule() ? SWT.SINGLE | SWT.BORDER : SWT.READ_ONLY | SWT.BORDER;
    final Combo combo = new Combo(parent, style);
    combo.addSelectionListener(new SelectionAdapter() {

        public void widgetSelected(SelectionEvent event) {
            if (rules == null) {
                return;
            }
            final int selIdx = combo.getSelectionIndex();
            final LanguageVersion version = selIdx == 0 ? null : selectedLanguage().getVersions().get(selIdx - 1);
            RuleVisitor visitor = new RuleVisitor() {

                public boolean accept(Rule rule) {
                    if (isMinVersion) {
                        rule.setMinimumLanguageVersion(version);
                    } else {
                        rule.setMaximumLanguageVersion(version);
                    }
                    return true;
                }
            };
            rules.rulesDo(visitor);
            valueChanged(null, version == null ? "" : version.getName());
        }
    });
    return combo;
}
Also used : RuleVisitor(net.sourceforge.pmd.eclipse.ui.preferences.br.RuleVisitor) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) SelectionEvent(org.eclipse.swt.events.SelectionEvent) LanguageVersion(net.sourceforge.pmd.lang.LanguageVersion) Combo(org.eclipse.swt.widgets.Combo) XPathRule(net.sourceforge.pmd.lang.rule.XPathRule) Rule(net.sourceforge.pmd.Rule)

Aggregations

LanguageVersion (net.sourceforge.pmd.lang.LanguageVersion)35 Test (org.junit.Test)14 LanguageVersionDiscoverer (net.sourceforge.pmd.lang.LanguageVersionDiscoverer)10 File (java.io.File)9 IOException (java.io.IOException)8 RuleContext (net.sourceforge.pmd.RuleContext)7 Language (net.sourceforge.pmd.lang.Language)7 Parser (net.sourceforge.pmd.lang.Parser)7 StringReader (java.io.StringReader)5 Node (net.sourceforge.pmd.lang.ast.Node)5 PMDConfiguration (net.sourceforge.pmd.PMDConfiguration)4 ParserOptions (net.sourceforge.pmd.lang.ParserOptions)4 ArrayList (java.util.ArrayList)3 Rule (net.sourceforge.pmd.Rule)3 PropertyDescriptor (net.sourceforge.pmd.properties.PropertyDescriptor)3 GargoylePMDConfiguration (com.kyj.fx.voeditor.visual.framework.pmd.GargoylePMDConfiguration)2 FileNotFoundException (java.io.FileNotFoundException)2 Reader (java.io.Reader)2 HashSet (java.util.HashSet)2 JMenuBar (javax.swing.JMenuBar)2