plugin for adding issues referring to manual rules into sonar - plugins

import org.sonar.api.component.ResourcePerspectives;
public class MySensor extends Sensor {
private final ResourcePerspectives perspectives;
public MySensor(ResourcePerspectives p) {
this.perspectives = p;
}
public void analyse(Project project, SensorContext context) {
Resource myResource; // to be set
Issuable issuable = perspectives.as(Issuable.class, myResource);
if (issuable != null) {
// can be used
Issue issue = issuable.newIssueBuilder()
//repository : pmd, key : AvoidArrayLoops
.setRuleKey(RuleKey.of("pmd", "AvoidArrayLoops"))
.setLine(10)
.build();
//works
issuable.addIssue(issue);
Issue issue2 = issuable.newIssueBuilder()
//repository : manual, key : performance
.setRuleKey(RuleKey.of("manual", "performance"))
.setLine(10)
.build();
// doesn't work
issuable.addIssue(issue2);
}
}
}
When I try to add the issue "issue" referring to the pmd rule AvoidArrayLoops it works. More generally, when I try to add issues referring to pmd or checkstyle rules it works.
However, when I try to add issues referring to manual rules such as the issue "issue2", it doesn't work. I have created manually the rule "performance" so the rule performance exists in the list of manual rules in sonar.
I would like to know if it is impossible to add issues referring to manual rules or if I am not using the right parameters for the method RuleKey.of.
Thanks

One reason why your custom issue is not shown in Sonar may be that you haven't enabled it the rule.
Select settings - Quality Profiles, click on your quality profile, select the tab "Coding rules", set Activation to "any", click search and check whether your rule is being displayed here.
If so, check the checkbox next to it and select the severity. Now, the rule violations will be displayed in Sonar.

Related

Custom moodle completion rule does not work

I am developing a mod_plugin for Moodle and want to support the automatic activity completion with a custom rule. I followed the official documentation and implemented all necessary functions. In the lib.php [pluginname]_supports method I have registered, FEATURE_GRADE_HAS_GRADE, FEATURE_COMPLETION_TRACKS_VIEWS, FEATURE_COMPLETION_HAS_RULES.
The \mod_[pluginname]\completion\custom_completion class defines a custom rule named "completiontest" in get_defined_custom_rules(). During my tests I found out that the methods get_state(), get_sort_order() and get_custom_rule_descriptions() are never executed. Also I don't see any output via activity_information().
I have cleared all caches, created new instances of my activity module, with no result. My development environment uses Moodle 3.11.7 (Build: 20220509).
My custom_completion.php script:
<?php
declare(strict_types=1);
namespace mod_cwr\completion;
use core_completion\activity_custom_completion;
class custom_completion extends activity_custom_completion {
public function get_state(string $rule): int {
return COMPLETION_INCOMPLETE;
}
public static function get_defined_custom_rules(): array {
return [
'completiontest'
];
}
public function get_custom_rule_descriptions(): array {
return [
'completiontest' => 'testout'
];
}
public function get_sort_order(): array {
return [
'completionview',
'completiontest',
'completionusegrade'
];
}
}
Test at the view.php:
$completion = new completion_info($course);
$completion->set_module_viewed($coursemodule);
if($completion->is_enabled($coursemodule) == COMPLETION_TRACKING_AUTOMATIC){
$completion->update_state($coursemodule, COMPLETION_INCOMPLETE, $USER->id);
}
$completiondetails = \core_completion\cm_completion_details::get_instance($coursemodule, $USER->id);
$activitydates = \core\activity_dates::get_dates_for_module($coursemodule, $USER->id);
echo $OUTPUT->activity_information($coursemodule, $completiondetails, $activitydates);
At the mod_form.php I check with completion_rule_enabled() if a custom rule is activated by the settings.
Does anyone have any idea what the problem could be?
Looking at the mod_forum plugin code showed me, that the get_state($rule) method does not observe all custom rules, only those selected in the settings. How do I tell Moodle to use a specific custom rule?
You appear to be calling update_state() and passing in the possible state change as COMPLETION_INCOMPLETE.
This is a way of telling Moodle "if the state is already incomplete, don't bother doing any expensive completion calculations to check if it should change state".
If you want Moodle to check and then (potentially) change the state to "complete", then pass COMPLETION_COMPLETE. If you really don't know which way it could be switching, then leave the param at the default COMPLETION_UNKNOWN (a good example would be forum completion - if you have just created a forum post, then you might cause the forum to be marked as "complete", but you certainly can't cause the forum to be marked as "incomplete", so you can pass the COMPLETION_COMPLETE parameter, so Moodle knows it only needs to check for changes if the forum is not already "complete").
Also, don't bother passing $USER->id as the third parameter - that's the default which is used of you don't pass anything.
As for telling Moodle which rules to use - it is up to you, when your function is called, to check your plugins settings to determine which rules are in use (and any other relevant configuration - e.g. with mod_forum, it needs to check how many posts are required for completion).
Thank you for the support. Got it running.
I now use $completion->update_state($coursemodule, COMPLETION_COMPLETE); and also had to fix [pluginname]_get_coursemodule_info() with $result->customdata['customcompletionrules']['completiontest'] = $cwr->completiontest; and totally forgot the return $result;.

Codeeffect rule editor allows to select only one action even though there are multiple actions to select from

I have requirements to use codeeffect rule editor for our feature. We have dynamic actions to render in the rule editor which user can select from.
So for that i have created the rule editor using FlexSource type. I tried to configure actions in rule editor by adding FlexMethodInfo for each actions and configured ActionAttributes for each of them.
e.g. the actions are "SetAmount", "SetPercentage" and "SetQuantity" .
It successfully renders the editor and provides the above three options to select from. But which ever option i select it only selects "SetAmount" and shows that in rule editor.
The idea behind FlexSource is to subclass System.Type so that Editor can continue using reflection to enumerate methods, properties, fields, etc.
To do that, there is a minimum number of classes and methods that have to be implemented. The Flex demo shows which those are.
However current version is missing an override for FlexMethodInfo.ToString().
Please add following to your FlexMethodInfo class. Adjust return values to reflect your actual methods and their signatures. The Editor uses ToString() to build hashes and match methods. It follows the same logic as MethodInfo.ToString().
public override string ToString()
{
switch (methodName)
{
case "Concatenate":
return "System.String Concatenate(System.String, System.String)";
case "Register":
return "Register()";
case "Confirm":
return "Confirm(System.String)";
default:
return base.ToString();
}
}
Make sure to get latest NuGet packages for the Editor and Engine. I believe they have released an update that addresses some use cases.

SonarQube adds all issues as Code Smell

After upgrading to 5.5 version and now the latest (5.6) SonarQube always shows the issues I create through my plugin as "Code Smell". I would like to know more about the categorization and how can I add them as other types ("Vulnerability" and "Bug"). The code where I create the issues is as follows:
Issuable issuable = this.resourcePerspectives.as(Issuable.class, inputFile);
if (issuable != null) {
Issue issue = issuable.newIssueBuilder()
.ruleKey(activeRule.ruleKey())
.line(vulnerability.getLine())
.message(someMessage)
.severity(severity)
.build();
issuable.addIssue(issue))
} //...
Current support for bugs and vulnerabilities is a "creative implementation" (read "hack") based on tags. So, add the "bug" tag to your rule and its issues will be raised as bugs. Add the "security" tag to a rule and its issues will be raised as vulnerabilities.
Rules with both "bug" and "security" tags will be treated as bug rules.
For future reference, this mechanism is expected to change in the "near" future, but there's currently no schedule for it.
Edit
The current (6.1) version of the API provides the ability to simply declare rule type.

How can I make N2CMS show edit page in admin interface by default?

When I am in the N2 management / admin interface, if I click on a node in the tree, by default it shows the output of that page. I can show the edit screen for that node by right clicking the node and clicking 'Edit'. Can I get it to show the edit screen for that node by just clicking the node? Is there some setting I can change in web.config?
So the comment that I left on the question above doesn't really answer the question (it works only for the root node). However, pretty much everything in N2 is pluggable, so you can use the dependency injection framework to replace the code that generates URLs in the edit interface with your own code as follows:
using N2.Configuration;
using N2.Edit;
using N2.Engine;
using N2.Web;
namespace MyWebsite
{
[Service(typeof(IEditUrlManager), Replaces = typeof(EditUrlManager))]
public class MyEditUrlManager : EditUrlManager
{
public MyEditUrlManager(IUrlParser parser, EditSection config)
: base(parser, config)
{
}
public override string GetPreviewUrl(N2.ContentItem selectedItem)
{
return GetEditExistingItemUrl(selectedItem);
}
}
}

Suppress Errors in JavaScript validation

I'm currently developing an eclipse plugin. This plugin contains a project nature which depends on the javaScript nature of jsdt.
Now at a few details the JavaScripts that the projects of my nature can contain are somewhat special.
They can contain "compiler hints" which are basicly statements beginning with #
They can contain return statements outside of functions
But at this two points the standard validation of jsdt come in and marks them as errors (which is normally right). I already managed to get this errors filtered out in the properties of the JavaScript validator (manually).
My question is, how can i exclude these errors from the validation of jsdt automatically for the projects with my nature?
JSDT uses concrete syntax parser which generates syntax errors.
You can't disable this. Only semantics error or warnings can be configured.
However you can disable entire validation of JSDT.
Below solution will suppress errors ands warnings which are generated while we save some changes on java script files. (Auto Build, Build)
Open Properties Dialog of Your Project.
Choose Builders item.
Uncheck "JavaScript Validator". And Press OK button.
Remove current errors and warnings from Problems View
This solution can't eliminate error or warning annotations in editor while you edit. They will show up on editor temporarily only when you edit it.
After a lot of research, hours of deleting markers and debugging i finally managed to delete the errors i wanted. In a bad bad way of course but i've come to a point where i just wanted this to work no matter how it's done.
If you ever want to delete existing problems that had been created during the validation process of jsdt you need to do the following (and you must not ommit anything):
Create a class extending org.eclipse.wst.jsdt.core.compiler.ValidationParticipant
Override isActive(), buildStarting() and reconcile() methods.
So there are two things you basicly have to care about.
The actual problem markers that will be created or had already been created at the end of the validation process.
The Problems created by the validation process. They are of the type CategorizedProblem and can be obtained by the ReconcileContext object that is passed to the reconcile() method.
It seems to me that the CategorizedProblems will be translated to problem markers after the validation process.
So what you need to do is:
Delete all unwanted problem markers of all files in buildStarting (this removes problem markers from all files in your project that are about to be validated)
Iterate the CategorizedProblem objects of the ReconcileContext (getProblems())
Create a new Array containing only the CategorizedProblems you want to keep
Set this new Array to the ReconcileContext with putProblems()
Delete the unwanted markers again for that file (i don't know why this is needed, please don't ask, i don't care anymore :-/)
An example implementation of such a validationParticipant could look like this: (this one will filter out problems complaining about return statements outside of methods:
[...ommited imports ...]
public class MyValidationParticipant extends org.eclipse.wst.jsdt.core.compiler.ValidationParticipant{
#Override
public boolean isActive(IJavaScriptProject project) {
return true;
}
#Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
super.buildStarting(files, isBatch);
for(BuildContext context : files){
IFile file = context.getFile();
deleteUnwantedMarkers(file);
}
}
#Override
public void reconcile(ReconcileContext context) {
IResource resource = context.getWorkingCopy().getResource();
CategorizedProblem[] newProblems = new CategorizedProblem[0];
ArrayList<CategorizedProblem> newProblemList = new ArrayList<CategorizedProblem>();
CategorizedProblem[] probs = context.getProblems("org.eclipse.wst.jsdt.core.problem");
if(probs != null){
for(CategorizedProblem p : probs){
if(!(p.getMessage().equals("Cannot return from outside a function or method."))){
newProblemList.add(p);
}
}
}
}
context.putProblems("org.eclipse.wst.jsdt.core.problem", newProblemList.toArray(newProblems));
deleteUnwantedMarkers(resource);
}
public static void deleteUnwantedMarkers(IResource resource){
if(resource.isSynchronized(IResource.DEPTH_INFINITE)){
try {
IMarker[] markers = resource.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
if(markers != null && markers.length > 0){
for(IMarker m : markers){
Object message = m.getAttribute(IMarker.MESSAGE);
if(message.equals("Cannot return from outside a function or method.")){
m.delete();
}
}
}
}catch (CoreException e) {
e.printStackTrace();
}
}
}
}
As i said, this is kind of a bad solution since the code relies on the String of the error message. There should be better ways to identify the problems you don't want to have.
Don't forget to add a proper extension in your plugin.xml for the ValidationParticipant.