net.sourceforge.pmd.lang.Language Java Examples

The following examples show how to use net.sourceforge.pmd.lang.Language. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PmdProcessor.java    From sputnik with Apache License 2.0 6 votes vote down vote up
/**
 * Paste from PMD
 */
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) {
    Set<Language> languages = new HashSet<>();
    LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer();

    for (Rule rule : ruleSets.getAllRules()) {
        Language language = rule.getLanguage();
        if (languages.contains(language))
            continue;
        LanguageVersion version = discoverer.getDefaultLanguageVersion(language);
        if (RuleSet.applies(rule, version)) {
            languages.add(language);
            log.debug("Using {} version: {}", language.getShortName(), version.getShortName());
        }
    }
    return languages;
}
 
Example #2
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Set<Language> getApplicableLanguages(PMDConfiguration configuration, RuleSets ruleSets) {
    Set<Language> languages = new HashSet<>();
    LanguageVersionDiscoverer discoverer = configuration.getLanguageVersionDiscoverer();

    for (Rule rule : ruleSets.getAllRules()) {
        Language language = rule.getLanguage();
        if (languages.contains(language)) {
            continue;
        }
        LanguageVersion version = discoverer.getDefaultLanguageVersion(language);
        if (RuleSet.applies(rule, version)) {
            languages.add(language);
            if (LOG.isLoggable(Level.FINE)) {
                LOG.fine("Using " + language.getShortName() + " version: " + version.getShortName());
            }
        }
    }
    return languages;
}
 
Example #3
Source File: MainDesignerController.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void initLanguageChoicebox() {
    languageChoicebox.getItems().addAll(getSupportedLanguages().sorted().collect(Collectors.toList()));
    languageChoicebox.setConverter(DesignerUtil.stringConverter(Language::getName, AuxLanguageRegistry::findLanguageByNameOrDefault));

    SingleSelectionModel<Language> langSelector = languageChoicebox.getSelectionModel();
    @NonNull Language restored = globalLanguage.getOrElse(defaultLanguage());

    globalLanguage.bind(langSelector.selectedItemProperty());

    langSelector.select(restored);

    Platform.runLater(() -> {
        langSelector.clearSelection();
        langSelector.select(restored); // trigger listener
    });
}
 
Example #4
Source File: SimplePopups.java    From pmd-designer with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void showAboutPopup(DesignerRoot root) {
    Alert licenseAlert = new Alert(AlertType.INFORMATION);
    licenseAlert.setWidth(500);
    licenseAlert.setHeaderText("About");

    ScrollPane scroll = new ScrollPane();
    TextArea textArea = new TextArea();

    String sb =
        "PMD core version:\t\t\t" + PMDVersion.VERSION + "\n"
            + "Designer version:\t\t\t" + Designer.getCurrentVersion()
            + " (supports PMD core " + Designer.getPmdCoreMinVersion() + ")\n"
            + "Designer settings dir:\t\t"
            + root.getService(DesignerRoot.DISK_MANAGER).getSettingsDirectory() + "\n"
            + "Available languages:\t\t"
            + AuxLanguageRegistry.getSupportedLanguages().map(Language::getTerseName).collect(Collectors.toList())
            + "\n";

    textArea.setText(sb);
    scroll.setContent(textArea);

    licenseAlert.getDialogPane().setContent(scroll);
    licenseAlert.showAndWait();
}
 
Example #5
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static LanguageVersion findLanguageVersionByTerseName(String string) {
    String[] split = string.split(" ");
    Language lang = findLanguageByTerseName(split[0]);
    if (lang == null) {
        return null;
    }
    return split.length == 1 ? lang.getDefaultVersion()
                             : lang.getVersion(split[1]);
}
 
Example #6
Source File: PmdProcessor.java    From sputnik with Apache License 2.0 5 votes vote down vote up
/**
 * PMD has terrible design of process configuration. You must use report file with it. I paste this method here and
 * improve it.
 *
 * @throws IllegalArgumentException
 *             if the configuration is not correct
 */
private void doPMD(@NotNull PMDConfiguration configuration) throws IllegalArgumentException {
    // Load the RuleSets
    RuleSetFactory ruleSetFactory = RulesetsFactoryUtils.getRulesetFactory(configuration, new ResourceLoader());

    RuleSets ruleSets = RulesetsFactoryUtils.getRuleSets(configuration.getRuleSets(), ruleSetFactory);
    // this is just double check - we don't get null here
    // instead IllegalArgumentException/RuntimeException is thrown if configuration is wrong
    if (ruleSets == null) {
        return;
    }

    Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
    // this throws RuntimeException when modified file does not exist in workspace
    List<DataSource> files = PMD.getApplicableFiles(configuration, languages);

    long reportStart = System.nanoTime();
    try {
        renderer = configuration.createRenderer();
        List<Renderer> renderers = new LinkedList<>();
        renderers.add(renderer);
        renderer.start();

        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);

        RuleContext ctx = new RuleContext();

        PMD.processFiles(configuration, ruleSetFactory, files, ctx, renderers);

        reportStart = System.nanoTime();
        renderer.end();
    } catch (IOException e) {
        log.error("PMD analysis error", e);
    } finally {
        Benchmarker.mark(Benchmark.Reporting, System.nanoTime() - reportStart, 0);
    }
}
 
Example #7
Source File: AstPackageExplorer.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
AstPackageExplorer(Language language) {
    availableNodeNames =
        ResourceUtil.getClassesInPackage("net.sourceforge.pmd.lang." + language.getTerseName() + ".ast")
                    .filter(clazz -> clazz.getSimpleName().startsWith("AST"))
                    .filter(clazz -> !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()))
                    .map(m -> m.getSimpleName().substring("AST".length()))
                    .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

}
 
Example #8
Source File: LanguageVersionRangeSlider.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void initLanguage(Language language) {

        if (language == null) {
            curVersions = Collections.emptyList();
            setDisable(true);
            return;
        }

        // for some reason Collections.sort doesn't work
        curVersions = language.getVersions().stream().sorted(LanguageVersion::compareTo).collect(Collectors.toList());

        setDisable(curVersions.size() < 2);

        setMax(curVersions.size());
    }
 
Example #9
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Map<String, LanguageVersion> getExtensionsToLanguageMap() {
    Map<String, LanguageVersion> result = new HashMap<>();
    getSupportedLanguageVersions().stream()
                                  .map(LanguageVersion::getLanguage)
                                  .distinct()
                                  .collect(Collectors.toMap(Language::getExtensions,
                                                            Language::getDefaultVersion))
                                  .forEach((key, value) -> key.forEach(ext -> result.put(ext, value)));
    return result;
}
 
Example #10
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static boolean isXmlDialect(Language language) {
    switch (language.getTerseName()) {
    case "xml":
    case "pom":
    case "wsql":
    case "fxml":
    case "xsl":
        return true;
    default:
        return false;
    }
}
 
Example #11
Source File: ExportXPathWizardController.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/** Gets the template used to initialise the code area. */
private static LiveTemplateBuilder<ObservableXPathRuleBuilder> liveTemplateBuilder() {
    return LiveTemplate.<ObservableXPathRuleBuilder>newBuilder()
        .withDefaultIndent("      ")
        .withDefaultEscape(StringEscapeUtils::escapeXml10)
        .append("<rule name=\"").bind(ObservableRuleBuilder::nameProperty).appendLine("\"")
        .appendIndent(1).append("language=\"").bind(ObservableRuleBuilder::languageProperty, Language::getTerseName).appendLine("\"")
        .bind(ObservableRuleBuilder::minimumVersionProperty, indented(2, surrounded("minimumLanguageVersion=\"", "\"\n", asString(LanguageVersion::getVersion))))
        .bind(ObservableRuleBuilder::maximumVersionProperty, indented(2, surrounded("maximumLanguageVersion=\"", "\"\n", asString(LanguageVersion::getVersion))))
        .withDefaultEscape(s -> s) // special escape for message
        .appendIndent(1).append("message=\"").bind(b -> b.messageProperty().map(ExportXPathWizardController::escapeMessageFormatter)).appendLine("\"")
        .withDefaultEscape(StringEscapeUtils::escapeXml10) // restore escaper
        .appendIndent(1).append("class=\"").bind(ObservableRuleBuilder::clazzProperty, Class::getCanonicalName).appendLine("\">")
        .withDefaultIndent("   ")
        .appendIndent(1).appendLine("<description>")
        .bind(ObservableRuleBuilder::descriptionProperty, wrapped(55, 2, true, asString())).endLine()
        .appendIndent(1).appendLine("</description>")
        .appendIndent(1).append("<priority>").bind(ObservableRuleBuilder::priorityProperty, p -> "" + p.getPriority()).appendLine("</priority>")
        .appendIndent(1).appendLine("<properties>")
        .bindTemplatedSeq(
            ObservableRuleBuilder::getRuleProperties,
            prop -> prop.appendIndent(2)
                        .append("<property name=\"").bind(PropertyDescriptorSpec::nameProperty)
                        .append("\" type=\"").bind(PropertyDescriptorSpec::typeIdProperty, PropertyTypeId::getStringId)
                        .append("\" value=\"").bind(PropertyDescriptorSpec::valueProperty)
                        .append("\" description=\"").bind(PropertyDescriptorSpec::descriptionProperty)
                        .appendLine("\"/>")
        )
        .appendIndent(2).append("<property name=\"version\" value=\"").bind(ObservableXPathRuleBuilder::xpathVersionProperty).appendLine("\"/>")
        .appendIndent(2).appendLine("<property name=\"xpath\">")
        .appendIndent(3).appendLine("<value>")
        .appendLine("<![CDATA[")
        .withDefaultEscape(s -> s) // stop escaping
        .bind(ObservableXPathRuleBuilder::xpathExpressionProperty).endLine()
        .appendLine("]]>")
        .appendIndent(3).appendLine("</value>")
        .appendIndent(2).appendLine("</property>")
        .appendIndent(1).appendLine("</properties>")
        .appendLine("</rule>");
}
 
Example #12
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determines all the diff files, that should be analyzed by PMD.
 * @param configuration contains either the file path or the DB URI, from where to load the files
 * @param languages used to filter by file extension
 * @return List<DataSource> of files
 */
public static List<DataSource> getApplicableGitDiffFiles(PMDConfiguration configuration, Set<Language> languages) {
    long startFiles = System.nanoTime();
    List<File> diffFiles = calculateGitDiffFiles(configuration, languages);
    if (diffFiles == null || diffFiles.isEmpty()) {
        System.exit(0);
    }
    String paths = diffFiles.stream().map(File::getAbsolutePath).collect(Collectors.joining(","));
    configuration.setInputPaths(paths);
    List<DataSource> files = internalGetApplicableFiles(configuration, languages);
    long endFiles = System.nanoTime();
    Benchmarker.mark(Benchmark.CollectFiles, endFiles - startFiles, 0);
    return files;
}
 
Example #13
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static List<File> calculateGitDiffFiles(PMDConfiguration configuration, Set<Language> languages) {
    LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(languages);
    File repoDir = new File(configuration.getGitDir());
    if (!repoDir.isDirectory()) {
        System.out.println("git directory " + configuration.getGitDir() + " is not a directory!");
        System.exit(1);
    }
    String oldRev = configuration.getBaseRev();
    boolean includeStagedCodes = configuration.isIncludeStagedCodes();
    if (StringUtils.isBlank(oldRev)) {
        oldRev = includeStagedCodes ? "HEAD" : "HEAD~";
    }
    String newRev = "HEAD";
    DiffCalculator calculator = DiffCalculator.builder().diffAlgorithm(new HistogramDiff()).build();
    try {
        List<DiffEntryWrapper> diffEntryList = calculator.calculateDiff(repoDir, oldRev, newRev, includeStagedCodes)
                .stream()
                .filter(diffEntry -> !diffEntry.isDeleted())
                .filter(diffEntry -> fileSelector.accept(diffEntry.getNewFile().getParentFile(), diffEntry.getNewFile().getName()))
                .collect(Collectors.toList());

        if (StringUtils.isNotBlank(configuration.getExcludeRegexp())) {
            Pattern excludePattern = Pattern.compile(configuration.getExcludeRegexp());
            diffEntryList.removeIf(diffEntry -> excludePattern.matcher(diffEntry.getAbsoluteNewPath()).matches());
        }

         DIFF_ENTRY_LIST.addAll(diffEntryList);

         return diffEntryList.stream()
                .map(DiffEntryWrapper::getNewFile)
                .collect(Collectors.toList());

     } catch (Exception e) {
        e.printStackTrace();
        System.out.println("error happened when calculate git diff");
        return Collections.emptyList();
    }
}
 
Example #14
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Determines all the files, that should be analyzed by PMD.
 * @param configuration contains either the file path or the DB URI, from where to load the files
 * @param languages used to filter by file extension
 * @return List<DataSource> of files
 */
public static List<DataSource> getApplicableFiles(PMDConfiguration configuration, Set<Language> languages) {
    long startFiles = System.nanoTime();
    List<DataSource> files = internalGetApplicableFiles(configuration, languages);
    if (StringUtils.isNotBlank(configuration.getExcludeRegexp())) {
        Pattern excludePattern = Pattern.compile(configuration.getExcludeRegexp());
        files.removeIf(file -> excludePattern.matcher(file.getNiceFileName(false, "")).matches());
    }
    long endFiles = System.nanoTime();
    Benchmarker.mark(Benchmark.CollectFiles, endFiles - startFiles, 0);
    return files;
}
 
Example #15
Source File: XPathRuleEditorController.java    From pmd-designer with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Val<String> titleProperty() {

    Val<Function<String, String>> languagePrefix =
        getRuleBuilder().languageProperty()
                        .map(Language::getTerseName)
                        .map(lname -> rname -> lname + "/" + rname);

    return getRuleBuilder().nameProperty()
                           .orElseConst("NewRule")
                           .mapDynamic(languagePrefix);
}
 
Example #16
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@NonNull
public static Language findLanguageByShortName(String shortName) {
    return getSupportedLanguages().filter(it -> it.getShortName().equals(shortName))
                                  .findFirst()
                                  .orElse(defaultLanguage());
}
 
Example #17
Source File: TestCollectionController.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Val<LanguageVersion> getDefaultLanguageVersion() {
    return builder.languageProperty().map(Language::getDefaultVersion);
}
 
Example #18
Source File: XPathCompletionSource.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Gets a suggestion tool suited to the given language.
 */
public static XPathCompletionSource forLanguage(Language language) {
    return BY_LANGUAGE.computeIfAbsent(language, l -> new XPathCompletionSource(NodeNameFinder.forLanguage(l)));
}
 
Example #19
Source File: LanguageVersionRangeSlider.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Var<Language> currentLanguageProperty() {
    return currentLanguage;
}
 
Example #20
Source File: NodeEditionCodeArea.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void updateSyntaxHighlighter(Language language) {
    setSyntaxHighlighter(AvailableSyntaxHighlighters.getHighlighterForLanguage(language).orElse(null));
}
 
Example #21
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Nullable
public static Language findLanguageByTerseName(String name) {
    return getSupportedLanguages().filter(it -> it.getTerseName().equals(name))
                                  .findFirst()
                                  .orElse(null);
}
 
Example #22
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@NonNull
public static Language findLanguageByNameOrDefault(String n) {
    Language lang = findLanguageByName(n);
    return lang == null ? defaultLanguage() : lang;
}
 
Example #23
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Nullable
public static Language findLanguageByName(String n) {
    return getSupportedLanguages().filter(it -> it.getName().equals(n))
                                  .findFirst()
                                  .orElse(null);
}
 
Example #24
Source File: ObservableRuleBuilder.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setLanguage(Language language) {
    this.language.setValue(language);
}
 
Example #25
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@NonNull
public static Stream<Language> getSupportedLanguages() {
    return Stream.concat(Stream.of(PlainTextLanguage.INSTANCE), LanguageRegistry.getLanguages().stream());
}
 
Example #26
Source File: AuxLanguageRegistry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static Language plainTextLanguage() {
    return PlainTextLanguage.INSTANCE;
}
 
Example #27
Source File: MainDesignerController.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@PersistentProperty
public Language getGlobalLanguage() {
    return globalLanguage.getValue();
}
 
Example #28
Source File: Main.java    From diff-check with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * 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);
    RuleSets ruleSets = RulesetsFactoryUtils.getRuleSetsWithBenchmark(configuration.getRuleSets(), ruleSetFactory);
    if (ruleSets == null) {
        return 0;
    }

    Set<Language> languages = getApplicableLanguages(configuration, ruleSets);
    List<DataSource> files = Collections.emptyList();
    if (StringUtils.isNotBlank(configuration.getGitDir())) {
        files = getApplicableGitDiffFiles(configuration, languages);
    } else {
        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);
        DiffLineFilter filter = new DiffLineFilter(Main.DIFF_ENTRY_LIST);
        ctx.getReport().addListener(new ReportListener() {
            @Override
            public void ruleViolationAdded(RuleViolation ruleViolation) {
                if (!filter.accept(ruleViolation)) {
                    return;
                }
                violations.incrementAndGet();
            }
            @Override
            public void metricAdded(Metric metric) {
            }
        });

        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);
    }
}
 
Example #29
Source File: MainDesignerController.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void setGlobalLanguage(Language lang) {
    globalLanguage.setValue(lang);
}
 
Example #30
Source File: ExportXPathWizardController.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Var<Language> languageProperty() {
    return Var.fromVal(languageChoiceBox.getSelectionModel().selectedItemProperty(), languageChoiceBox.getSelectionModel()::select);
}