net.sourceforge.pmd.lang.LanguageVersion Java Examples
The following examples show how to use
net.sourceforge.pmd.lang.LanguageVersion.
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: Main.java From diff-check with GNU Lesser General Public License v2.1 | 6 votes |
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 #2
Source File: PmdProcessor.java From sputnik with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: SourceEditorController.java From pmd-designer with BSD 2-Clause "Simplified" License | 6 votes |
private void initializeLanguageSelector() { languageVersionChoicebox.setConverter(DesignerUtil.stringConverter(LanguageVersion::getName, AuxLanguageRegistry::getLanguageVersionByName)); getService(DesignerRoot.APP_GLOBAL_LANGUAGE) .values() .filter(Objects::nonNull) .subscribe(lang -> { languageVersionChoicebox.setItems(lang.getVersions().stream().sorted().collect(Collectors.toCollection(LiveArrayList::new))); languageVersionChoicebox.getSelectionModel().select(lang.getDefaultVersion()); boolean disable = lang.getVersions().size() == 1; languageVersionChoicebox.setVisible(!disable); languageVersionChoicebox.setManaged(!disable); }); languageVersionUIProperty = Var.suspendable(languageVersionChoicebox.valueProperty()); // this will be overwritten by property restore if needed languageVersionUIProperty.setValue(defaultLanguageVersion()); }
Example #4
Source File: PMDParameters.java From diff-check with GNU Lesser General Public License v2.1 | 5 votes |
public static PMDConfiguration transformParametersIntoConfiguration(PMDParameters params) { if (null == params.getSourceDir() && null == params.getUri() && null == params.getFileListPath() && null == params.getGitDir()) { throw new IllegalArgumentException( "Please provide a parameter for source root directory (-dir or -d), database URI (-uri or -u), file list path (-filelist) or git dir (-git-dir)."); } PMDConfiguration configuration = new PMDConfiguration(); configuration.setInputPaths(params.getSourceDir()); configuration.setInputFilePath(params.getFileListPath()); configuration.setInputUri(params.getUri()); configuration.setReportFormat(params.getFormat()); configuration.setBenchmark(params.isBenchmark()); configuration.setDebug(params.isDebug()); configuration.setMinimumPriority(params.getMinimumPriority()); configuration.setReportFile(params.getReportfile()); configuration.setReportProperties(params.getProperties()); configuration.setReportShortNames(params.isShortnames()); configuration.setRuleSets(params.getRulesets()); configuration.setRuleSetFactoryCompatibilityEnabled(!params.noRuleSetCompatibility); configuration.setShowSuppressedViolations(params.isShowsuppressed()); configuration.setSourceEncoding(params.getEncoding()); configuration.setStressTest(params.isStress()); configuration.setSuppressMarker(params.getSuppressmarker()); configuration.setThreads(params.getThreads()); configuration.setFailOnViolation(params.isFailOnViolation()); configuration.setGitDir(params.getGitDir()); configuration.setBaseRev(params.getBaseRev()); configuration.setIncludeStagedCodes(params.isIncludeStagedCodes()); configuration.setExcludeRegexp(params.getExcludeRegexp()); LanguageVersion languageVersion = LanguageRegistry.findLanguageVersionByTerseName(params.getLanguage() + " " + params.getVersion()); if(languageVersion != null) { configuration.getLanguageVersionDiscoverer().setDefaultLanguageVersion(languageVersion); } try { configuration.prependClasspath(params.getAuxclasspath()); } catch (IOException e) { throw new IllegalArgumentException("Invalid auxiliary classpath: " + e.getMessage(), e); } return configuration; }
Example #5
Source File: Main.java From diff-check with GNU Lesser General Public License v2.1 | 5 votes |
/** * Helper method to get a configured parser for the requested language. The parser is * configured based on the given {@link PMDConfiguration}. * @param languageVersion the requested language * @param configuration the given configuration * @return the pre-configured parser */ public static Parser parserFor(LanguageVersion languageVersion, PMDConfiguration configuration) { // TODO Handle Rules having different parser options. LanguageVersionHandler languageVersionHandler = languageVersion.getLanguageVersionHandler(); ParserOptions options = languageVersionHandler.getDefaultParserOptions(); if (configuration != null) { options.setSuppressMarker(configuration.getSuppressMarker()); } return languageVersionHandler.getParser(options); }
Example #6
Source File: LanguageVersionRangeSlider.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
public Var<LanguageVersion> maxVersionProperty() { return Var.mapBidirectional( highValueProperty(), num -> fromIndex(num.intValue()), ver -> ver == null ? curVersions.size() : curVersions.indexOf(ver) ); }
Example #7
Source File: LanguageVersionRangeSlider.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
public Var<LanguageVersion> minVersionProperty() { return Var.mapBidirectional( lowValueProperty(), num -> fromIndex(num.intValue()), ver -> ver == null ? -1 : curVersions.indexOf(ver) ); }
Example #8
Source File: LanguageVersionRangeSlider.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
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: LanguageVersionRangeSlider.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
public LanguageVersionRangeSlider() { setMin(NO_MIN); setBlockIncrement(1); setMajorTickUnit(1); setMinorTickCount(0); setSnapToTicks(true); currentLanguage.values().distinct().subscribe(this::initLanguage); StringConverter<Number> converter = DesignerUtil.stringConverter( num -> { int n = num.intValue(); if (n < 0) { return NO_MIN_STR; } else if (n >= curVersions.size()) { return NO_MAX_STR; } else { return curVersions.get(n).getShortName(); } }, ver -> { switch (ver) { case NO_MIN_STR: return -1; case NO_MAX_STR: return curVersions.size(); default: LanguageVersion withName = curVersions.stream().filter(lv -> lv.getShortName().equals(ver)).findFirst().get(); return curVersions.indexOf(withName); } } ); setLabelFormatter(converter); }
Example #10
Source File: AuxLanguageRegistry.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
@NonNull public static LanguageVersion getLanguageVersionByName(String name) { return getSupportedLanguageVersions().stream() .filter(it -> it.getName().equals(name)) .findFirst() .orElse(defaultLanguageVersion()); }
Example #11
Source File: AuxLanguageRegistry.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
public static synchronized List<LanguageVersion> getSupportedLanguageVersions() { if (supportedLanguageVersions == null) { supportedLanguageVersions = getSupportedLanguages().flatMap(it -> it.getVersions().stream()) .filter(AuxLanguageRegistry::filterLanguageVersion) .collect(Collectors.toList()); } return supportedLanguageVersions; }
Example #12
Source File: AuxLanguageRegistry.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
private static boolean filterLanguageVersion(LanguageVersion lv) { return !StringUtils.containsIgnoreCase(lv.getLanguage().getName(), "dummy") && Optional.ofNullable(lv.getLanguageVersionHandler()) .map(handler -> handler.getParser(handler.getDefaultParserOptions())) .filter(Parser::canParse) .isPresent(); }
Example #13
Source File: AuxLanguageRegistry.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
@Nullable public static synchronized LanguageVersion getLanguageVersionFromExtension(String filename) { if (extensionsToLanguage == null) { extensionsToLanguage = getExtensionsToLanguageMap(); } if (filename.indexOf('.') > 0) { String[] tokens = filename.split("\\."); return extensionsToLanguage.get(tokens[tokens.length - 1]); } return null; }
Example #14
Source File: AuxLanguageRegistry.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
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 #15
Source File: AuxLanguageRegistry.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
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 #16
Source File: ExportXPathWizardController.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
/** 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 #17
Source File: ASTManagerImpl.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
public ASTManagerImpl(ASTManagerImpl base, Function<LanguageVersion, LanguageVersion> languageVersionMap) { this(base.getDesignerRoot()); languageVersionProperty().bind(base.languageVersionProperty().map(languageVersionMap)); sourceCode.bind(base.sourceCodeProperty()); classLoaderProperty().bind(base.classLoaderProperty()); }
Example #18
Source File: TestXmlParser.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
private static LiveTestCase fromDescriptor( String code, String description, int expectedProblems, @Nullable LanguageVersion version, boolean ignored, List<String> messages, List<Integer> lineNumbers, Properties properties, ObservableRuleBuilder owner ) { LiveTestCase live = new LiveTestCase(); live.setRule(owner); live.setSource(code); live.setDescription(description); live.setLanguageVersion(version); live.setIgnored(ignored); List<String> lines = Arrays.asList(code.split("\\r?\\n")); for (int i = 0; i < expectedProblems; i++) { String m = messages.size() > i ? messages.get(i) : null; int line = lineNumbers.size() > i ? lineNumbers.get(i) : -1; TextRange tr = line >= 0 ? TextRange.fullLine(line, lines.get(line - 1).length()) : null; live.getExpectedViolations().add(new LiveViolationRecord(tr, m, false)); } properties.forEach((k, v) -> live.setProperty(k.toString(), v.toString())); return live; }
Example #19
Source File: MainDesignerController.java From pmd-designer with BSD 2-Clause "Simplified" License | 5 votes |
private void loadSourceFromFile(File file) { if (file != null) { try { String source = IOUtils.toString(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8); sourceEditorController.setText(source); LanguageVersion guess = getLanguageVersionFromExtension(file.getName()); if (guess == null) { if (!isXmlDialect(getGlobalLanguage())) { // if we're a xml language, assume the file is some xml dialect too, // otherwise go back to plain text sourceEditorController.setLanguageVersion(plainTextLanguage().getDefaultVersion()); } if (getSupportedLanguages().count() > 1) { SimplePopups.showActionFeedback( languageChoicebox, AlertType.INFORMATION, "Pick a language?" ); } } else if (guess != sourceEditorController.getLanguageVersion()) { // guess the language from the extension sourceEditorController.setLanguageVersion(guess); SimplePopups.showActionFeedback( languageChoicebox, AlertType.CONFIRMATION, "Set language to " + guess.getLanguage().getName() ); } recentFiles.push(file); } catch (IOException e) { e.printStackTrace(); } } }
Example #20
Source File: ObservableRuleBuilder.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public LanguageVersion getMaximumVersion() { return maximumVersion.getValue(); }
Example #21
Source File: SourceEditorController.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
@Override protected void beforeParentInit() { astManager.languageVersionProperty() .map(LanguageVersion::getLanguage) .values() .filter(Objects::nonNull) .distinct() .subscribe(nodeEditionCodeArea::updateSyntaxHighlighter); ((ASTManagerImpl) astManager).classLoaderProperty().bind(auxclasspathClassLoader); // default text, will be overwritten by settings restore setText(getDefaultText()); searchButton.setOnAction(e -> astTreeView.focusSearchField()); exportTreeButton.setOnAction( e -> getService(DesignerRoot.TREE_EXPORT_WIZARD).apply(x -> x.showYourself(x.bindToTree(getService(DesignerRoot.AST_MANAGER)))) ); TestCreatorService creatorService = getService(DesignerRoot.TEST_CREATOR); creatorService.getSourceFetchRequests() .messageStream(true, this) .subscribe(tick -> creatorService.getAdditionRequests().pushEvent(this, currentlyOpenTestCase.getOrElse(defaultTestCase).deepCopy())); propertiesMapButton.setOnAction(e -> propertiesPopover.showOrFocus(p -> p.show(propertiesMapButton))); violationsButton.setOnAction(e -> violationsPopover.showOrFocus(p -> p.show(violationsButton))); violationsButton.textProperty().bind( currentlyOpenTestCase.flatMap(it -> it.getExpectedViolations().sizeProperty()) .map(it -> "Expected violations (" + it + ")") .orElseConst("Expected violations") ); propertiesMapButton.disableProperty().bind( currentlyOpenTestCase.flatMap(LiveTestCase::ruleProperty) .map(ObservableRuleBuilder::getRuleProperties) .flatMap(LiveList::sizeProperty) .map(it -> it == 0) .orElseConst(false) ); DragAndDropUtil.registerAsNodeDragTarget( violationsButton, range -> { LiveViolationRecord record = new LiveViolationRecord(); record.setRange(range); record.setExactRange(true); SimplePopups.showActionFeedback(violationsButton, AlertType.CONFIRMATION, "Violation added"); currentlyOpenTestCase.ifPresent(v -> v.getExpectedViolations().add(record)); }, getDesignerRoot()); currentlyOpenTestCase.orElseConst(defaultTestCase) .changes() .subscribe(it -> handleTestOpenRequest(it.getOldValue(), it.getNewValue())); currentlyOpenTestCase.values().subscribe(test -> { violationsPopover.rebind(test); propertiesPopover.rebind(test); }); }
Example #22
Source File: TestCollectionController.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public Val<LanguageVersion> getDefaultLanguageVersion() { return builder.languageProperty().map(Language::getDefaultVersion); }
Example #23
Source File: SourceEditorController.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public LanguageVersion getLanguageVersion() { return languageVersionUIProperty.getValue(); }
Example #24
Source File: SourceEditorController.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public void setLanguageVersion(LanguageVersion version) { languageVersionUIProperty.setValue(version); }
Example #25
Source File: LanguageVersionRangeSlider.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
private LanguageVersion fromIndex(int idx) { return idx < 0 || idx >= curVersions.size() ? null : curVersions.get(idx); }
Example #26
Source File: SourceEditorController.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public Var<LanguageVersion> languageVersionProperty() { return languageVersionUIProperty; }
Example #27
Source File: XPathEvaluator.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
/** * Evaluates an XPath query on the compilation unit. Performs * no side effects. * * @param compilationUnit AST root * @param languageVersion language version * @param xpathVersion XPath version * @param xpathQuery XPath query * @param properties Properties of the rule * * @throws XPathEvaluationException if there was an error during the evaluation. The cause is preserved */ public static List<Node> evaluateQuery(Node compilationUnit, LanguageVersion languageVersion, String xpathVersion, String xpathQuery, Map<String, String> propertyValues, List<PropertyDescriptorSpec> properties) throws XPathEvaluationException { if (StringUtils.isBlank(xpathQuery)) { return emptyList(); } try { List<Node> results = new ArrayList<>(); XPathRule xpathRule = new XPathRule() { @Override public void addViolation(Object data, Node node, String arg) { results.add(node); } }; xpathRule.setMessage(""); xpathRule.setLanguage(languageVersion.getLanguage()); xpathRule.setXPath(xpathQuery); xpathRule.setVersion(xpathVersion); properties.stream() .map(PropertyDescriptorSpec::build) .forEach(xpathRule::definePropertyDescriptor); propertyValues.forEach((k, v) -> { PropertyDescriptor<?> d = xpathRule.getPropertyDescriptor(k); if (d != null) { setRulePropertyCapture(xpathRule, d, v); } else { throw new RuntimeException("Property '" + k + "' is not defined, available properties: " + properties.stream().map(PropertyDescriptorSpec::getName).collect(Collectors.toList())); } }); final RuleSet ruleSet = new RuleSetFactory().createSingleRuleRuleSet(xpathRule); RuleSets ruleSets = new RuleSets(ruleSet); RuleContext ruleContext = new RuleContext(); ruleContext.setLanguageVersion(languageVersion); ruleContext.setIgnoreExceptions(false); ruleSets.apply(singletonList(compilationUnit), ruleContext, xpathRule.getLanguage()); return results; } catch (RuntimeException e) { throw new XPathEvaluationException(e); } }
Example #28
Source File: ObservableRuleBuilder.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public LanguageVersion getMinimumVersion() { return minimumVersion.getValue(); }
Example #29
Source File: ObservableRuleBuilder.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public void setMinimumVersion(LanguageVersion minimumVersion) { this.minimumVersion.setValue(minimumVersion); }
Example #30
Source File: ObservableRuleBuilder.java From pmd-designer with BSD 2-Clause "Simplified" License | 4 votes |
public Var<LanguageVersion> minimumVersionProperty() { return minimumVersion; }