Monday, November 23, 2020

Create Sonar Plugin - Create Qulaity Profile

  1.  Create a built in Quality profile for the Foo language.
  2. implements BuiltInQualityProfilesDefinition
  3. can set default profile -  profile.setDefault(true)
  4. Load the profile giving profile name and active rule set. Here active rules were given in "foo_quality_profile.json" inside ""ruleKeys""



------------------------------------------------------------------

package com.plugin.sonar.language.foo;

import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition;
import org.sonarsource.analyzer.commons.BuiltInQualityProfileJsonLoader;

import static com.plugin.sonar.util.FooConstants.*;

public class FooQualityProfile implements BuiltInQualityProfilesDefinition {

@Override
public void define(Context context) {
NewBuiltInQualityProfile profile = context.createBuiltInQualityProfile(FooSQL_QUALITY_PROFILE_NAME, LANGUAGE_KEY);
profile.setDefault(true);
BuiltInQualityProfileJsonLoader.load(profile, REPO_KEY, JSON_PROFILE_PATH);
profile.done();
}
}

-------------------------------

below is the sample "foo_quality_profile.json" with 5 active keys.

-----------------------------------------------------------------------

{
"name": "Foo Quality Profile",
"ruleKeys": [
"1",
"2",
"3",
"4",
"5"

]
}

Create Sonar Plugin - Language properties

 Language property class contains the properties related to the language.


----------------------------------------------------------------------------------------------

package com.plugin.sonar.language.foo;

import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.resources.Qualifiers;

import java.util.Collections;
import java.util.List;

import static com.plugin.sonar.util.FooConstants.*;

public class FooLanguageProperties {

private FooLanguageProperties() {
// only statics
}

public static List<PropertyDefinition> getProperties() {
return Collections.singletonList(PropertyDefinition.builder(FILE_SUFFIXES_KEY)//".foo,.f"
.defaultValue(FILE_SUFFIXES_DEFAULT_VALUE)
.category(LANGUAGE_NAME)
.name("File Suffixes")
.description("Comma-separated list of suffixes for files to analyze.")
.onQualifiers(Qualifiers.PROJECT)
.build());
}
}


Create Sonar Plugin - Language class

 Language class contains the

  1. Class extends AbstractLanguage  
  2. defines KEY and Name for Language
  3. File extensions for the specific language. ( here Foo.) Note we have used comma as seprator when you define multiple extensions.
  4. We have injected "Configuration" - org.sonar.api.config.Configuration;
    1. Basically at the  construction of the object, Key and Name for the language and configurations are set ( Constructor injection )


----------------------------------------------------------------------------------------------

package com.plugin.sonar.language.foo;

import org.apache.commons.lang.StringUtils;
import org.sonar.api.config.Configuration;
import org.sonar.api.resources.AbstractLanguage;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.plugin.sonar.util.FooConstants.*;

public class FooLanguage extends AbstractLanguage {

private Configuration config;

public FooLanguage(Configuration configuration) {
super(LANGUAGE_KEY, LANGUAGE_NAME);
this.config = configuration;
}

@Override
public String[] getFileSuffixes() {
String[] suffixes = filterEmptyStrings(config.getStringArray(FILE_SUFFIXES_KEY));
if (suffixes.length == 0) {
suffixes = StringUtils.split(FILE_SUFFIXES_DEFAULT_VALUE, ",");
}
return suffixes;
}

private String[] filterEmptyStrings(String[] stringArray) {
List<String> nonEmptyStrings = new ArrayList<>();
for (String string : stringArray) {
if (StringUtils.isNotBlank(string.trim())) {
nonEmptyStrings.add(string.trim());
}
}
return nonEmptyStrings.toArray(new String[0]);
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
FooLanguage that = (FooLanguage) o;
return Objects.equals(config, that.config);
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), config);
}
}

Create Sonar Plugin - Plugin exception class

 you can create your own exception class. Here is a sample of a exception class with message only.


package com.plugin.sonar.exception;

public class FooPluginException extends Exception {
public FooPluginException(String errorMsg) {
super(errorMsg);
}
}

Create Sonar Plugin - Plugin class

We create a plugin class implementing org.sonar.api.Plugin.

Implement "define" contract and register all classes as extensions. Plugin class is the entry point.

Below is the sample code for FooPlugin class.

You can see that, you need to implement all other specialized classes before registering as extensions.

---------------------------------------------------------------------------------------------------


package com.plugin.sonar;

import com.plugin.sonar.language.foo.FooLanguage;
import com.plugin.sonar.language.foo.FooLanguageProperties;
import com.plugin.sonar.language.foo.FooQualityProfile;
import com.plugin.sonar.scanner.FooScanner;
import com.plugin.sonar.util.Extractor;
import com.plugin.sonar.language.foo.FooRulesDefinition;
import org.sonar.api.Plugin;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;

public class FooPlugin implements Plugin {

private static final Logger LOG = Loggers.get(FooPlugin.class);

public void define(Context context) {
LOG.info("defining all extensions for Foo Language plugin");
context.addExtensions(FooLanguage.class, FooRulesDefinition.class)
.addExtensions(FooQualityProfile.class, FooLanguageProperties.getProperties());
context.addExtension(FooScanner.class);
context.addExtension(Extractor.class);
}
}

Create Sonar Plugin - Basic Class Structure for Sonar Plugin using Java

You can write a sonar Plugin for a langauge using Java.

When you write a plugin there few key components you need to write. Below is the basic structure of classes.

Let's assume you are writting plugin for "Foo" language. 

Here we are calling a third party component which bundled in a executable Jar file. we generate violations in a xml file and show them in SonarQube.

1. class FooPlugin implements Plugin

Plugin class which connects all the component

2. class FooLanguage extends AbstractLanguage

Implement Key and Name for language and some other features

3. class FooRulesDefinition implements RulesDefinition

create repository and define rules for language

4. class FooQualityProfile implements BuiltInQualityProfilesDefinition

Create a quality profile for language. you can set this profile as your default quality profile and also define rules for the profile.

5. class FooLanguageProperties

define properties for the language.

6. class FooScanner implements Sensor

Logic for analysis of the files written language "foo" will be handled/written here. once analysis is done, result/issues will be saved as report in SonarQube.

7. class Extractor

As i explained files will  be analysed using a thirid party jar, we need to extarct that jar from our plugin Jar and also related files need to do the excution. Logic for extraction is written here. 

Tuesday, November 10, 2020

Property file loader

 properties file is used to store project configuration data or settings. You can write your own property file loader or use Java java.util.Properties directly.

Here is an sample of custom property file loader.


import com.test.properties.exception.PropertyException;

import org.apache.log4j.Logger;


import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

import java.util.Properties;


public class PropertyLoader {

    private final Map<String, Properties> propertyRepo;

    private static final Logger LOGGER = Logger.getLogger(PropertyLoader.class);

    private PropertyLoader() {

        propertyRepo = new HashMap<String, Properties>();

    }

    public String getProperty(final String propertyFileLocation, final String property, final String defaultValue) throws PropertyException {

        Properties properties = propertyRepo.get(propertyFileLocation);

        if (properties == null) {

            properties = loadPropertes(propertyFileLocation);

            propertyRepo.put(propertyFileLocation, properties);

        }

        return properties.getProperty(property) != null ? properties.getProperty(property) : defaultValue;

    }

    public String getProperty(final String propertyFileLocation, final String property) throws PropertyException {

        return getProperty(propertyFileLocation, property, null);

    }

    private static Properties loadPropertes(final String fileLocation) throws PropertyException {

        Properties properties = new Properties();

        try {

            try (InputStream inputStream = new FileInputStream(fileLocation)) {

                properties.load(inputStream);

            }

        } catch (IOException e) {

            LOGGER.error("Error in loading property file : " + fileLocation, e);

            throw new PropertyException("Error in loading property file : " + fileLocation);

        }

        return properties;

    }

    public static PropertyLoader getInstance() {

        return HOLDER.INSTANCE;

    }

    private static final class HOLDER {

        private static final PropertyLoader INSTANCE = new PropertyLoader();

    }

}