Monday, November 23, 2020

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);
}
}

No comments:

Post a Comment