import org.sonar.api.resources.ProjectFileSystem;
import org.sonar.api.utils.SonarException;
-import java.io.*;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Locale;
private static final Logger LOG = LoggerFactory.getLogger(CheckstyleConfiguration.class);
public static final String PROPERTY_GENERATE_XML = "sonar.checkstyle.generateXml";
- private CheckstyleProfileExporter confExporter;
- private RulesProfile profile;
- private Settings conf;
- private ProjectFileSystem fileSystem;
+ private final CheckstyleProfileExporter confExporter;
+ private final RulesProfile profile;
+ private final Settings conf;
+ private final ProjectFileSystem fileSystem;
public CheckstyleConfiguration(Settings conf, CheckstyleProfileExporter confExporter, RulesProfile profile, ProjectFileSystem fileSystem) {
this.conf = conf;
return null;
}
- public com.puppycrawl.tools.checkstyle.api.Configuration getCheckstyleConfiguration() throws IOException, CheckstyleException {
+ public com.puppycrawl.tools.checkstyle.api.Configuration getCheckstyleConfiguration() throws CheckstyleException {
File xmlConfig = getXMLDefinitionFile();
LOG.info("Checkstyle configuration: " + xmlConfig.getAbsolutePath());
*/
package org.sonar.plugins.checkstyle;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.Extension;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
import org.sonar.api.SonarPlugin;
-import java.util.Arrays;
import java.util.List;
@Properties({
type = PropertyType.TEXT)})
public final class CheckstylePlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(
- CheckstyleSensor.class,
- CheckstyleConfiguration.class,
- CheckstyleExecutor.class,
- CheckstyleAuditListener.class,
- CheckstyleProfileExporter.class,
- CheckstyleProfileImporter.class,
- CheckstyleRuleRepository.class,
- SonarWayProfile.class,
- SunConventionsProfile.class,
- SonarWayWithFindbugsProfile.class);
+ public List<Class<? extends Extension>> getExtensions() {
+ return ImmutableList.of(
+ CheckstyleSensor.class,
+ CheckstyleConfiguration.class,
+ CheckstyleExecutor.class,
+ CheckstyleAuditListener.class,
+ CheckstyleProfileExporter.class,
+ CheckstyleProfileImporter.class,
+ CheckstyleRuleRepository.class,
+ SonarWayProfile.class,
+ SunConventionsProfile.class,
+ SonarWayWithFindbugsProfile.class);
}
}
import org.apache.commons.io.FileUtils;
import org.junit.Test;
-import org.sonar.api.config.Settings;
import org.sonar.api.profiles.RulesProfile;
import org.sonar.api.resources.Project;
import org.sonar.api.test.MavenTestUtils;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
-import java.util.Locale;
-
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
*/
package org.sonar.plugins.cobertura;
-import org.sonar.api.*;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.Properties;
+import org.sonar.api.Property;
+import org.sonar.api.SonarPlugin;
-import java.util.ArrayList;
import java.util.List;
@Properties({
- @Property(
- key = CoreProperties.COBERTURA_REPORT_PATH_PROPERTY,
- name = "Report path",
- description = "Path (absolute or relative) to Cobertura xml report file.",
- project = true,
- global = false),
- @Property(
- key = CoreProperties.COBERTURA_MAXMEM_PROPERTY,
- defaultValue = CoreProperties.COBERTURA_MAXMEM_DEFAULT_VALUE,
- name = "Maxmem",
- description = "Maximum memory to pass to JVM of Cobertura processes",
- project = true,
- global = true) })
+ @Property(
+ key = CoreProperties.COBERTURA_REPORT_PATH_PROPERTY,
+ name = "Report path",
+ description = "Path (absolute or relative) to Cobertura xml report file.",
+ project = true,
+ global = false),
+ @Property(
+ key = CoreProperties.COBERTURA_MAXMEM_PROPERTY,
+ defaultValue = CoreProperties.COBERTURA_MAXMEM_DEFAULT_VALUE,
+ name = "Maxmem",
+ description = "Maximum memory to pass to JVM of Cobertura processes",
+ project = true,
+ global = true)})
public class CoberturaPlugin extends SonarPlugin {
- public List<Class<? extends Extension>> getExtensions() {
- List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>();
- list.add(CoberturaSensor.class);
- list.add(CoberturaMavenPluginHandler.class);
- list.add(CoberturaMavenInitializer.class);
- return list;
+ public List<Class<? extends BatchExtension>> getExtensions() {
+ return ImmutableList.of(
+ CoberturaSensor.class,
+ CoberturaMavenPluginHandler.class,
+ CoberturaMavenInitializer.class);
}
}
*/
package org.sonar.plugins.cobertura;
-import static org.hamcrest.CoreMatchers.is;
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
-import org.sonar.api.resources.*;
+import org.sonar.api.resources.JavaFile;
+import org.sonar.api.resources.JavaPackage;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.ProjectFileSystem;
+import org.sonar.api.resources.Qualifiers;
+import org.sonar.api.resources.Resource;
+import org.sonar.api.resources.Scopes;
import org.sonar.api.test.IsMeasure;
import org.sonar.api.test.IsResource;
import java.io.File;
import java.net.URISyntaxException;
+import static org.hamcrest.CoreMatchers.is;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyDouble;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
public class CoberturaSensorTest {
private SensorContext context;
}
@Test
- public void shouldNotFailIfReportNotSpecifiedOrNotFound() throws URISyntaxException {
+ public void shouldNotFailIfReportNotSpecifiedOrNotFound() {
ProjectFileSystem pfs = mock(ProjectFileSystem.class);
when(pfs.resolvePath(anyString()))
.thenReturn(new File("notFound.xml"));
public final class CorePlugin extends SonarPlugin {
@SuppressWarnings({"rawtypes", "unchecked"})
- public List getExtensions() {
+ public List<Class<? extends Extension>> getExtensions() {
List extensions = Lists.newLinkedList();
extensions.add(DefaultResourceTypes.class);
*/
package org.sonar.plugins.core.sensors;
-import org.dbunit.dataset.DataSetException;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.*;
import org.sonar.api.batch.DecoratorContext;
import org.sonar.api.batch.Event;
import org.sonar.api.batch.TimeMachine;
import java.util.Arrays;
import java.util.Date;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.isNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
public class GenerateAlertEventsTest {
private GenerateAlertEvents decorator;
private DecoratorContext context;
}
@Test
- public void shouldNotCreateEventWhenNoAlertStatus() throws DataSetException {
+ public void shouldNotCreateEventWhenNoAlertStatus() {
decorator.decorate(project, context);
verify(context, never()).createEvent(anyString(), anyString(), anyString(), (Date) isNull());
}
@Test
- public void shouldNotCreateEventWhenSameLevel() throws DataSetException {
+ public void shouldNotCreateEventWhenSameLevel() {
when(timeMachine.getMeasures((TimeMachineQuery) anyObject())).thenReturn(Arrays.asList(newAlertStatus(Metric.Level.ERROR, "desc")));
when(context.getMeasure(CoreMetrics.ALERT_STATUS)).thenReturn(newAlertStatus(Metric.Level.ERROR, "desc"));
}
@Test
- public void shouldNotCreateEventIfNoMoreAlertStatus() throws DataSetException {
+ public void shouldNotCreateEventIfNoMoreAlertStatus() {
when(timeMachine.getMeasures((TimeMachineQuery) anyObject())).thenReturn(Arrays.asList(newAlertStatus(Metric.Level.ERROR, "desc")));
when(context.getMeasure(CoreMetrics.ALERT_STATUS)).thenReturn(null);
verify(context, never()).createEvent(anyString(), anyString(), anyString(), (Date) isNull());
}
-
private Measure newAlertStatus(Metric.Level level, String label) {
Measure measure = new Measure(CoreMetrics.ALERT_STATUS, level);
measure.setAlertStatus(level);
*/
package org.sonar.plugins.core.sensors;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.*;
-
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.Event;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
-import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.same;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.when;
+
public class ProfileEventsSensorTest {
private Project project;
}
@Test
- public void shouldDoNothingIfNoProfile() throws ParseException {
+ public void shouldDoNothingIfNoProfile() {
ProfileEventsSensor sensor = new ProfileEventsSensor(null, null);
sensor.analyse(project, context);
}
@Test
- public void shouldDoNothingIfNoProfileChange() throws ParseException {
+ public void shouldDoNothingIfNoProfileChange() {
RulesProfile profile = mockProfileWithVersion(1);
TimeMachine timeMachine = mockTM(project, 22.0, "Foo", 1.0); // Same profile, same version
ProfileEventsSensor sensor = new ProfileEventsSensor(profile, timeMachine);
}
@Test
- public void shouldCreateEventIfProfileChange() throws ParseException {
+ public void shouldCreateEventIfProfileChange() {
RulesProfile profile = mockProfileWithVersion(1);
TimeMachine timeMachine = mockTM(project, 21.0, "Bar", 1.0); // Different profile
ProfileEventsSensor sensor = new ProfileEventsSensor(profile, timeMachine);
}
@Test
- public void shouldCreateEventIfProfileVersionChange() throws ParseException {
+ public void shouldCreateEventIfProfileVersionChange() {
RulesProfile profile = mockProfileWithVersion(2);
TimeMachine timeMachine = mockTM(project, 22.0, "Foo", 1.0); // Same profile, different version
ProfileEventsSensor sensor = new ProfileEventsSensor(profile, timeMachine);
}
@Test
- public void shouldNotCreateEventIfFirstAnalysis() throws ParseException {
+ public void shouldNotCreateEventIfFirstAnalysis() {
RulesProfile profile = mockProfileWithVersion(2);
TimeMachine timeMachine = mockTM(project, null, null);
ProfileEventsSensor sensor = new ProfileEventsSensor(profile, timeMachine);
}
@Test
- public void shouldCreateEventIfFirstAnalysisWithVersionsAndVersionMoreThan1() throws ParseException {
+ public void shouldCreateEventIfFirstAnalysisWithVersionsAndVersionMoreThan1() {
RulesProfile profile = mockProfileWithVersion(2);
TimeMachine timeMachine = mockTM(project, 22.0, "Foo", null);
ProfileEventsSensor sensor = new ProfileEventsSensor(profile, timeMachine);
*/
package org.sonar.plugins.core.sensors;
+import com.google.common.collect.Lists;
+import org.junit.Test;
+import org.sonar.api.batch.Event;
+import org.sonar.api.batch.SensorContext;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.Resource;
+
+import java.util.Date;
+
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-
-import org.junit.Test;
-import org.sonar.api.batch.Event;
-import org.sonar.api.batch.SensorContext;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-
public class VersionEventsSensorTest {
- private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
- private SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMdd HH:mm");
-
@Test
public void shouldDoNothingIfNoVersion() {
VersionEventsSensor sensor = new VersionEventsSensor();
Project project = mock(Project.class);
when(project.getAnalysisVersion()).thenReturn("1.5-SNAPSHOT");
- when(context.getEvents(project)).thenReturn(new ArrayList(Arrays.asList(sameVersionEvent, otherEvent, anotherEvent)));
+ when(context.getEvents(project)).thenReturn(Lists.newArrayList(sameVersionEvent, otherEvent, anotherEvent));
sensor.analyse(project, context);
SensorContext context = mock(SensorContext.class);
Project project = mock(Project.class);
when(project.getAnalysisVersion()).thenReturn("1.5");
- when(context.getEvents(project)).thenReturn(new ArrayList(Arrays.asList(snapshotVersion, otherEvent)));
+ when(context.getEvents(project)).thenReturn(Lists.newArrayList(snapshotVersion, otherEvent));
VersionEventsSensor sensor = new VersionEventsSensor();
sensor.analyse(project, context);
when(event.getName()).thenReturn(version);
return event;
}
-
- private Event mockEvent(String name, String yyyyMMdd) throws ParseException {
- Event event = mock(Event.class);
- when(event.isVersionCategory()).thenReturn(false);
- when(event.isLinkedToSnapshot()).thenReturn(false);
- when(event.getName()).thenReturn(name);
- when(event.getDate()).thenReturn(dateFormat.parse(yyyyMMdd));
- return event;
- }
}
import org.sonar.batch.components.TimeMachineConfiguration;
import org.sonar.jpa.test.AbstractDbUnitTestCase;
-import java.text.ParseException;
import java.util.Arrays;
import static org.mockito.Mockito.mock;
public class TimeMachineConfigurationPersisterTest extends AbstractDbUnitTestCase {
@Test
- public void shouldSaveConfigurationInSnapshotsTable() throws ParseException {
+ public void shouldSaveConfigurationInSnapshotsTable() {
setupData("shared");
TimeMachineConfiguration conf = mock(TimeMachineConfiguration.class);
import org.sonar.api.rules.Violation;
import org.sonar.api.utils.DateUtils;
-import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
-import static org.hamcrest.Matchers.*;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ViolationTrackingDecoratorTest {
private ViolationTrackingDecorator decorator;
- private Date analysisDate = DateUtils.parseDate("2010-12-25");
+ private final Date analysisDate = DateUtils.parseDate("2010-12-25");
@Before
- public void setUp() throws ParseException {
+ public void setUp() {
Project project = mock(Project.class);
when(project.getAnalysisDate()).thenReturn(analysisDate);
decorator = new ViolationTrackingDecorator(project, null, null);
Violation newViolation = newViolation("message", 1, 50, "checksum");
assertThat(newViolation.getCreatedAt(), nullValue());
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(Lists.newArrayList(newViolation), Collections.<RuleFailureModel>emptyList());
+ Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(Lists.newArrayList(newViolation), Collections.<RuleFailureModel> emptyList());
assertThat(mapping.size(), is(0));
assertThat(newViolation.getCreatedAt(), is(analysisDate));
assertThat(newViolation.isNew(), is(true));
referenceViolation.setCreatedAt(referenceDate);
assertThat(newViolation.getCreatedAt(), nullValue());
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(Lists.newArrayList(newViolation), Lists.<RuleFailureModel>newArrayList(referenceViolation));
+ Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(Lists.newArrayList(newViolation), Lists.<RuleFailureModel> newArrayList(referenceViolation));
assertThat(mapping.size(), is(1));
assertThat(newViolation.getCreatedAt(), is(referenceDate));
assertThat(newViolation.isNew(), is(false));
*/
package org.sonar.plugins.cpd;
-import org.sonar.api.*;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.Properties;
+import org.sonar.api.Property;
import org.sonar.api.PropertyType;
+import org.sonar.api.SonarPlugin;
import org.sonar.plugins.cpd.decorators.DuplicationDensityDecorator;
import org.sonar.plugins.cpd.decorators.SumDuplicationsDecorator;
import org.sonar.plugins.cpd.index.IndexFactory;
-import java.util.Arrays;
import java.util.List;
@Properties({
})
public final class CpdPlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(CpdSensor.class, SumDuplicationsDecorator.class, DuplicationDensityDecorator.class,
- IndexFactory.class,
- SonarEngine.class,
- PmdEngine.class,
- SonarBridgeEngine.class);
+ public List<Class<? extends BatchExtension>> getExtensions() {
+ return ImmutableList.of(
+ CpdSensor.class,
+ SumDuplicationsDecorator.class,
+ DuplicationDensityDecorator.class,
+ IndexFactory.class,
+ SonarEngine.class,
+ PmdEngine.class,
+ SonarBridgeEngine.class);
}
}
public void defaultMinimumTokens() {
Project project = createJavaProject().setConfiguration(new PropertiesConfiguration());
- PmdEngine engine = new PmdEngine();
- assertEquals(CoreProperties.CPD_MINIMUM_TOKENS_DEFAULT_VALUE, engine.getMinimumTokens(project));
+ assertEquals(CoreProperties.CPD_MINIMUM_TOKENS_DEFAULT_VALUE, PmdEngine.getMinimumTokens(project));
}
@Test
conf.setProperty("sonar.cpd.minimumTokens", "33");
Project project = createJavaProject().setConfiguration(conf);
- PmdEngine engine = new PmdEngine();
- assertEquals(33, engine.getMinimumTokens(project));
+ assertEquals(33, PmdEngine.getMinimumTokens(project));
}
@Test
Project phpProject = createPhpProject().setConfiguration(conf);
Project javaProject = createJavaProject().setConfiguration(conf);
- PmdEngine engine = new PmdEngine();
- assertEquals(100, engine.getMinimumTokens(javaProject));
- assertEquals(33, engine.getMinimumTokens(phpProject));
+ assertEquals(100, PmdEngine.getMinimumTokens(javaProject));
+ assertEquals(33, PmdEngine.getMinimumTokens(phpProject));
}
private Project createJavaProject() {
*/
package org.sonar.plugins.dbcleaner;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.BatchExtension;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.PropertyType;
import org.sonar.plugins.dbcleaner.api.DbCleanerConstants;
import org.sonar.plugins.dbcleaner.period.DefaultPeriodCleaner;
-import java.util.Arrays;
import java.util.List;
@Properties({
global = true,
project = true,
type = PropertyType.INTEGER)
-}
-)
+})
public final class DbCleanerPlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(DefaultPeriodCleaner.class, DefaultPurgeTask.class, ProjectPurgePostJob.class);
+ public List<Class<? extends BatchExtension>> getExtensions() {
+ return ImmutableList.of(
+ DefaultPeriodCleaner.class,
+ DefaultPurgeTask.class,
+ ProjectPurgePostJob.class);
}
}
import org.sonar.api.utils.DateUtils;
import org.sonar.core.purge.PurgeableSnapshotDto;
-import java.util.Date;
-import java.util.GregorianCalendar;
-
public final class DbCleanerTestUtils {
private DbCleanerTestUtils() {
*/
package org.sonar.plugins.dbcleaner.api;
+import com.google.common.collect.Lists;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.junit.Test;
import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.ResourceModel;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.resources.Scopes;
import org.sonar.jpa.test.AbstractDbUnitTestCase;
-import com.google.common.collect.Lists;
+import javax.persistence.Query;
-import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
-import javax.persistence.Query;
-
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.*;
+import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class PurgeUtilsTest extends AbstractDbUnitTestCase {
}
@Test
- public void purgeSnapshots() throws SQLException {
+ public void purgeSnapshots() {
setupData("purgeSnapshots");
PurgeUtils.deleteSnapshotsData(getSession(), Arrays.asList(3, 4));
when(session.createNativeQuery(anyString())).thenReturn(query);
List<Integer> ids = Lists.newArrayList();
- for (int i = 0; i < PurgeUtils.MAX_IN_ELEMENTS + 1; i++) {
+ for (int i = 0; i < (PurgeUtils.MAX_IN_ELEMENTS + 1); i++) {
ids.add(i);
}
*/
package org.sonar.plugins.design;
-import java.util.List;
-
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.Extension;
import org.sonar.api.SonarPlugin;
import org.sonar.plugins.design.batch.FileTangleIndexDecorator;
import org.sonar.plugins.design.batch.MavenDependenciesSensor;
import org.sonar.plugins.design.ui.widgets.FileDesignWidget;
import org.sonar.plugins.design.ui.widgets.PackageDesignWidget;
-import com.google.common.collect.Lists;
+import java.util.List;
public class DesignPlugin extends SonarPlugin {
- @SuppressWarnings({"unchecked", "rawtypes"})
- public List getExtensions() {
- List extensions = Lists.newArrayList();
-
- // Batch
- extensions.add(MavenDependenciesSensor.class);
- extensions.add(ProjectDsmDecorator.class);
- extensions.add(PackageTangleIndexDecorator.class);
- extensions.add(FileTangleIndexDecorator.class);
- extensions.add(SuspectLcom4DensityDecorator.class);
- extensions.add(GwtLibrariesPage.class);
-
- // UI
- extensions.add(GwtDesignPage.class);
- extensions.add(DependenciesViewer.class);
- extensions.add(FileDesignWidget.class);
- extensions.add(PackageDesignWidget.class);
- extensions.add(ChidamberKemererWidget.class);
-
- return extensions;
+ public List<Class<? extends Extension>> getExtensions() {
+ return ImmutableList.of(
+ // Batch
+ MavenDependenciesSensor.class,
+ ProjectDsmDecorator.class,
+ PackageTangleIndexDecorator.class,
+ FileTangleIndexDecorator.class,
+ SuspectLcom4DensityDecorator.class,
+ GwtLibrariesPage.class,
+
+ // UI
+ GwtDesignPage.class,
+ DependenciesViewer.class,
+ FileDesignWidget.class,
+ PackageDesignWidget.class,
+ ChidamberKemererWidget.class);
}
}
public class DsmSerializerTest {
@Test
- public void serializeEmptyDsm() throws IOException {
+ public void serializeEmptyDsm() {
Dsm dsm = new Dsm(new DirectedGraph());
assertThat(DsmSerializer.serialize(dsm), is("[]"));
}
graph.addVertex(bar);
graph.addEdge(dep);
-
Dsm<Resource> dsm = new Dsm<Resource>(graph);
DsmManualSorter.sort(dsm, bar, foo); // for test reproductibility
String json = IOUtils.toString(getClass().getResourceAsStream("/org/sonar/plugins/design/batch/DsmSerializerTest/dsm.json"));
*/
package org.sonar.plugins.emailnotifications;
-import java.util.Arrays;
-import java.util.List;
-
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.ServerExtension;
import org.sonar.api.SonarPlugin;
import org.sonar.plugins.emailnotifications.newviolations.NewViolationsEmailTemplate;
import org.sonar.plugins.emailnotifications.newviolations.NewViolationsOnMyFavouriteProject;
import org.sonar.plugins.emailnotifications.reviews.ChangesInReviewAssignedToMeOrCreatedByMe;
import org.sonar.plugins.emailnotifications.reviews.ReviewEmailTemplate;
+import java.util.List;
+
public class EmailNotificationsPlugin extends SonarPlugin {
- @SuppressWarnings({"rawtypes", "unchecked"})
- public List getExtensions() {
- return Arrays.asList(
+ public List<Class<? extends ServerExtension>> getExtensions() {
+ return ImmutableList.of(
EmailConfiguration.class,
EmailNotificationChannel.class,
*/
package org.sonar.plugins.findbugs;
-import org.sonar.api.*;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.Extension;
+import org.sonar.api.Properties;
+import org.sonar.api.Property;
import org.sonar.api.PropertyType;
+import org.sonar.api.SonarPlugin;
-import java.util.ArrayList;
import java.util.List;
@Properties({
public class FindbugsPlugin extends SonarPlugin {
public List<Class<? extends Extension>> getExtensions() {
- List<Class<? extends Extension>> list = new ArrayList<Class<? extends Extension>>();
- list.add(FindbugsSensor.class);
- list.add(FindbugsConfiguration.class);
- list.add(FindbugsExecutor.class);
- list.add(FindbugsRuleRepository.class);
- list.add(FindbugsProfileExporter.class);
- list.add(FindbugsProfileImporter.class);
- list.add(SonarWayWithFindbugsProfile.class);
- list.add(FindbugsMavenInitializer.class);
- return list;
+ return ImmutableList.of(
+ FindbugsSensor.class,
+ FindbugsConfiguration.class,
+ FindbugsExecutor.class,
+ FindbugsRuleRepository.class,
+ FindbugsProfileExporter.class,
+ FindbugsProfileImporter.class,
+ SonarWayWithFindbugsProfile.class,
+ FindbugsMavenInitializer.class);
}
}
public class FindbugsProfileImporterTest {
- private FindbugsProfileImporter importer = new FindbugsProfileImporter(new FakeRuleFinder());
+ private final FindbugsProfileImporter importer = new FindbugsProfileImporter(new FakeRuleFinder());
@Test
- public void shouldImportPatterns() throws IOException {
+ public void shouldImportPatterns() {
String findbugsConf = TestUtils.getResourceContent("/org/sonar/plugins/findbugs/shouldImportPatterns.xml");
RulesProfile profile = importer.importProfile(new StringReader(findbugsConf), ValidationMessages.create());
}
@Test
- public void shouldImportCodes() throws IOException {
+ public void shouldImportCodes() {
InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/shouldImportCodes.xml");
RulesProfile profile = importer.importProfile(new InputStreamReader(input), ValidationMessages.create());
List<ActiveRule> results = profile.getActiveRules();
}
@Test
- public void shouldImportCategories() throws IOException {
+ public void shouldImportCategories() {
InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/shouldImportCategories.xml");
RulesProfile profile = importer.importProfile(new InputStreamReader(input), ValidationMessages.create());
List<ActiveRule> results = profile.getActiveRules();
}
@Test
- public void shouldImportConfigurationBugInclude() throws IOException {
+ public void shouldImportConfigurationBugInclude() {
InputStream input = getClass().getResourceAsStream("/org/sonar/plugins/findbugs/findbugs-include.xml");
RulesProfile profile = importer.importProfile(new InputStreamReader(input), ValidationMessages.create());
List<ActiveRule> results = profile.getActiveRules();
}
@Test
- public void testImportingUncorrectXmlFile() throws IOException {
+ public void testImportingUncorrectXmlFile() {
String uncorrectFindbugsXml = TestUtils.getResourceContent("/org/sonar/plugins/findbugs/uncorrectFindbugsXml.xml");
ValidationMessages messages = ValidationMessages.create();
RulesProfile profile = importer.importProfile(new StringReader(uncorrectFindbugsXml), messages);
}
@Test
- public void testImportingXmlFileWithUnknownRule() throws IOException {
+ public void testImportingXmlFileWithUnknownRule() {
String uncorrectFindbugsXml = TestUtils.getResourceContent("/org/sonar/plugins/findbugs/findbugsXmlWithUnknownRule.xml");
ValidationMessages messages = ValidationMessages.create();
RulesProfile profile = importer.importProfile(new StringReader(uncorrectFindbugsXml), messages);
}
@Test
- public void testImportingXmlFileWithUnknownCategory() throws IOException {
+ public void testImportingXmlFileWithUnknownCategory() {
String uncorrectFindbugsXml = TestUtils.getResourceContent("/org/sonar/plugins/findbugs/findbugsXmlWithUnknownCategory.xml");
ValidationMessages messages = ValidationMessages.create();
RulesProfile profile = importer.importProfile(new StringReader(uncorrectFindbugsXml), messages);
}
@Test
- public void testImportingXmlFileWithUnknownCode() throws IOException {
+ public void testImportingXmlFileWithUnknownCode() {
String uncorrectFindbugsXml = TestUtils.getResourceContent("/org/sonar/plugins/findbugs/findbugsXmlWithUnknownCode.xml");
ValidationMessages messages = ValidationMessages.create();
RulesProfile profile = importer.importProfile(new StringReader(uncorrectFindbugsXml), messages);
*/
package org.sonar.plugins.jacoco;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.BatchExtension;
import org.sonar.api.SonarPlugin;
-import java.util.Arrays;
import java.util.List;
public class JaCoCoPlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(
+ public List<Class<? extends BatchExtension>> getExtensions() {
+ return ImmutableList.of(
JacocoConfiguration.class,
JaCoCoAgentDownloader.class,
// Ant
*/
package org.sonar.plugins.l10n;
+import org.sonar.api.Extension;
+
import org.sonar.api.SonarPlugin;
import java.util.Collections;
public final class EnglishPackPlugin extends SonarPlugin {
- public List getExtensions() {
+ public List<Class<? extends Extension>> getExtensions() {
return Collections.emptyList();
}
}
*/
package org.sonar.plugins.pmd;
-import net.sourceforge.pmd.*;
+import net.sourceforge.pmd.PMD;
+import net.sourceforge.pmd.PMDException;
+import net.sourceforge.pmd.Report;
+import net.sourceforge.pmd.RuleContext;
+import net.sourceforge.pmd.RuleSetFactory;
+import net.sourceforge.pmd.RuleSets;
+import net.sourceforge.pmd.SourceType;
import net.sourceforge.pmd.renderers.Renderer;
import net.sourceforge.pmd.renderers.XMLRenderer;
import org.apache.commons.io.FileUtils;
import org.sonar.api.utils.TimeProfiler;
import org.sonar.java.api.JavaUtils;
-import java.io.*;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringWriter;
+import java.io.Writer;
import java.util.List;
public class PmdExecutor implements BatchExtension {
private static final Logger LOG = LoggerFactory.getLogger(PmdExecutor.class);
- private PmdConfiguration configuration;
- private Project project;
+ private final PmdConfiguration configuration;
+ private final Project project;
public PmdExecutor(Project project, PmdConfiguration configuration) {
this.project = project;
this.configuration = configuration;
}
- public Report execute() throws IOException, PMDException {
+ public Report execute() throws IOException {
TimeProfiler profiler = new TimeProfiler().start("Execute PMD " + PmdVersion.getVersion());
ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
*/
package org.sonar.plugins.pmd;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.Extension;
import org.sonar.api.SonarPlugin;
-import java.util.Arrays;
import java.util.List;
public class PmdPlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(
+ public List<Class<? extends Extension>> getExtensions() {
+ return ImmutableList.of(
PmdSensor.class,
PmdConfiguration.class,
PmdExecutor.class,
SonarWayWithFindbugsProfile.class,
SunConventionsProfile.class,
JavaCpdMapping.class
- );
+ );
}
}
*/
package org.sonar.plugins.pmd;
-import net.sourceforge.pmd.PMDException;
+import com.google.common.base.Charsets;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Rule;
import java.io.File;
import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.charset.Charset;
import java.util.Arrays;
import static org.hamcrest.Matchers.nullValue;
public TemporaryFolder temp = new TemporaryFolder();
@Test
- public void executeOnManySourceDirs() throws URISyntaxException, IOException, PMDException {
- final File workDir = temp.getRoot();
+ public void executeOnManySourceDirs() throws IOException {
+ File workDir = temp.getRoot();
Project project = new Project("two-source-dirs");
ProjectFileSystem fs = mock(ProjectFileSystem.class);
File root = new File(getClass().getResource("/org/sonar/plugins/pmd/PmdExecutorTest/executeOnManySourceDirs/").toURI());
when(fs.getSourceFiles(Java.INSTANCE)).thenReturn(Arrays.asList(new File(root, "src1/FirstClass.java"), new File(root, "src2/SecondClass.java")));
- when(fs.getSourceCharset()).thenReturn(Charset.forName("UTF-8"));
+ when(fs.getSourceCharset()).thenReturn(Charsets.UTF_8);
when(fs.getSonarWorkingDirectory()).thenReturn(workDir);
project.setFileSystem(fs);
}
@Test
- public void ignorePmdFailures() throws URISyntaxException, IOException, PMDException {
+ public void ignorePmdFailures() throws IOException {
final File workDir = temp.getRoot();
Project project = new Project("ignorePmdFailures");
ProjectFileSystem fs = mock(ProjectFileSystem.class);
when(fs.getSourceFiles(Java.INSTANCE)).thenReturn(Arrays.asList(new File("test-resources/ignorePmdFailures/DoesNotCompile.java")));
- when(fs.getSourceCharset()).thenReturn(Charset.forName("UTF-8"));
+ when(fs.getSourceCharset()).thenReturn(Charsets.UTF_8);
when(fs.getSonarWorkingDirectory()).thenReturn(workDir);
project.setFileSystem(fs);
*/
package org.sonar.plugins.pmd;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CharSequenceReader;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.sonar.api.platform.ServerFileSystem;
import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.*;
+import org.sonar.api.rules.ActiveRule;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RuleFinder;
+import org.sonar.api.rules.RuleQuery;
+import org.sonar.api.rules.XMLRuleParser;
import org.sonar.api.utils.SonarException;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.plugins.pmd.xml.PmdProperty;
import org.sonar.plugins.pmd.xml.PmdRule;
import org.sonar.test.TestUtils;
-import org.xml.sax.SAXException;
-import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.List;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.mock;
+
public class PmdProfileExporterTest {
- private PmdProfileExporter exporter = new PmdProfileExporter();
+ private final PmdProfileExporter exporter = new PmdProfileExporter();
@Test
- public void testExportProfile() throws IOException, SAXException {
+ public void testExportProfile() {
ServerFileSystem fileSystem = mock(ServerFileSystem.class);
PmdRuleRepository repository = new PmdRuleRepository(fileSystem, new XMLRuleParser());
List<Rule> rules = repository.createRules();
}
private static class IsEqualIgnoringEOL extends TypeSafeMatcher<CharSequence> {
- private String expected;
+ private final String expected;
public IsEqualIgnoringEOL(CharSequence expected) {
this.expected = normalize(expected);
private static class FakeRuleFinder implements RuleFinder {
- private List<Rule> rules;
+ private final List<Rule> rules;
public FakeRuleFinder(List<Rule> rules) {
this.rules = rules;
*/
package org.sonar.plugins.squid;
-import org.sonar.api.*;
-import org.sonar.plugins.squid.decorators.*;
+import com.google.common.collect.ImmutableList;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.Extension;
+import org.sonar.api.Properties;
+import org.sonar.api.Property;
+import org.sonar.api.PropertyType;
+import org.sonar.api.SonarPlugin;
+import org.sonar.plugins.squid.decorators.ChidamberKemererDistributionBuilder;
+import org.sonar.plugins.squid.decorators.ClassesDecorator;
+import org.sonar.plugins.squid.decorators.FileComplexityDistributionDecorator;
+import org.sonar.plugins.squid.decorators.FunctionComplexityDistributionBuilder;
+import org.sonar.plugins.squid.decorators.FunctionsDecorator;
-import java.util.Arrays;
import java.util.List;
@Properties({
})
public final class SquidPlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(
+ public List<Class<? extends Extension>> getExtensions() {
+ return ImmutableList.of(
SquidSensor.class,
SquidRuleRepository.class,
JavaSourceImporter.class,
*/
package org.sonar.java.ast;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.Charset;
-
-import org.apache.commons.lang.CharEncoding;
+import com.google.common.base.Charsets;
import org.junit.Before;
import org.junit.Test;
import org.sonar.java.squid.JavaSquidConfiguration;
import org.sonar.squid.api.SourceProject;
import org.sonar.squid.measures.Metric;
+import java.nio.charset.Charset;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
public class JavaAstScannerTest {
private Squid squid;
@Before
- public void setup() throws UnsupportedEncodingException {
+ public void setup() {
squid = new Squid(new JavaSquidConfiguration(false, Charset.defaultCharset(), 0.9));
}
assertEquals(1, prj.getInt(Metric.FILES));
assertEquals(1, prj.getInt(Metric.COMMENT_LINES));
- assertNotNull(squid.search("ClassWithOnlyComment.java"));//file
- assertNull(squid.search("ClassWithOnlyComment"));//class
+ assertNotNull(squid.search("ClassWithOnlyComment.java"));// file
+ assertNull(squid.search("ClassWithOnlyComment"));// class
}
@Test
try {
System.setProperty("file.encoding", "UTF-16");
Charset defaultEncoding = Charset.defaultCharset();
- if ( !defaultEncoding.displayName().equals("UTF-16")) {
+ if (!defaultEncoding.displayName().equals("UTF-16")) {
return;
}
System.setProperty("file.encoding", "MacRoman");
@Test
public void testUTF8Encoding() {
- squid = new Squid(new JavaSquidConfiguration(false, Charset.forName(CharEncoding.UTF_8)));
+ squid = new Squid(new JavaSquidConfiguration(false, Charsets.UTF_8));
squid.register(JavaAstScanner.class).scanFile(SquidTestUtils.getInputFile("/special_cases/encoding/Utf8Encoding.java"));
SourceProject prj = squid.aggregate();
assertEquals(4, prj.getInt(Metric.METHODS));
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.Lists;
package org.sonar.java.ast.visitor;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
import org.sonar.java.ast.JavaAstScanner;
import org.sonar.java.ast.SquidTestUtils;
*/
package org.sonar.plugins.squid;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.Charset;
-
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.JavaFile;
import org.sonar.api.utils.SonarException;
+import java.io.File;
+import java.nio.charset.Charset;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
public class JavaSourceImporterTest {
@Rule
}
@Test
- public void shouldSetSource() throws IOException {
+ public void shouldSetSource() {
JavaFile javaFile = JavaFile.fromRelativePath("UndocumentedApi.java", true);
when(context.isIndexed(javaFile, true)).thenReturn(true);
importer.importSource(context, javaFile, inputFile, Charset.defaultCharset());
*/
package org.sonar.plugins.squid;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.number.OrderingComparisons.greaterThan;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyDouble;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.atLeast;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-
import org.junit.Test;
import org.sonar.api.batch.SensorContext;
import org.sonar.api.checks.AnnotationCheckFactory;
import org.sonar.api.resources.InputFile;
import org.sonar.api.resources.Project;
import org.sonar.api.resources.Resource;
-import org.sonar.squid.Squid;
import org.sonar.squid.measures.Metric;
import java.io.File;
import java.util.Arrays;
import java.util.Collections;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.number.OrderingComparisons.greaterThan;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyDouble;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.atLeast;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyZeroInteractions;
+
public class SquidExecutorTest {
@Test
}
@Test
- public void doNotScanBytecodeIfNoSources() throws IOException, URISyntaxException {
+ public void doNotScanBytecodeIfNoSources() throws URISyntaxException {
SquidExecutor executor = new SquidExecutor(true, "LOG, logger", createCheckFactory(), Charset.defaultCharset());
executor.scan(Collections.<InputFile> emptyList(), Arrays.asList(SquidTestUtils.getStrutsCoreJar()));
@Test
public void shouldNotHaveBytecode() {
- assertFalse(SquidExecutor.hasBytecode(Collections.<File>emptyList()));
+ assertFalse(SquidExecutor.hasBytecode(Collections.<File> emptyList()));
assertFalse(SquidExecutor.hasBytecode(Arrays.asList(new File("unknown"))));
}
*/
public static Collection<InputFile> getStrutsCoreSources() throws IOException, URISyntaxException {
File sourceDir = new File("target/struts-core-1.3.9-sources");
- if (!sourceDir.exists() || sourceDir.list().length==0) {
+ if (!sourceDir.exists() || (sourceDir.list().length == 0)) {
FileUtils.forceMkdir(sourceDir);
ZipUtils.unzip(new File(SquidTestUtils.class.getResource("/struts-core-1.3.9-sources.jar").toURI()), sourceDir);
}
- Collection<File> javaFiles = FileUtils.listFiles(sourceDir, new String[]{"java"}, true);
+ Collection<File> javaFiles = FileUtils.listFiles(sourceDir, new String[] {"java"}, true);
return InputFileUtils.create(sourceDir, javaFiles);
}
/**
* See http://svn.apache.org/repos/asf/struts/struts1/tags/STRUTS_1_3_9/core
*/
- public static File getStrutsCoreJar() throws IOException, URISyntaxException {
+ public static File getStrutsCoreJar() throws URISyntaxException {
return new File(SquidTestUtils.class.getResource("/struts-core-1.3.9.jar").toURI());
}
}
*/
package org.sonar.plugins.squid.bridges;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
+import com.google.common.base.Charsets;
import org.junit.Before;
import org.junit.BeforeClass;
import org.mockito.invocation.InvocationOnMock;
import java.io.IOException;
import java.net.URISyntaxException;
-import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
public abstract class BridgeTestCase {
protected SensorContext context;
public static void scanStruts() throws IOException, URISyntaxException {
RulesProfile profile = RulesProfile.create();
CheckFactory checkFactory = AnnotationCheckFactory.create(profile, "repo", Collections.<Class> emptyList());
- executor = new SquidExecutor(true, "LOG, logger", checkFactory, Charset.forName("UTF8"));
+ executor = new SquidExecutor(true, "LOG, logger", checkFactory, Charsets.UTF_8);
executor.scan(SquidTestUtils.getStrutsCoreSources(), Arrays.asList(SquidTestUtils.getStrutsCoreJar()));
project = new Project("project");
}
import org.sonar.api.resources.JavaPackage;
import org.sonar.squid.api.SourceFile;
import org.sonar.squid.measures.Metric;
-import org.sonar.squid.measures.MetricDef;
public class ChidamberKemererBridgeTest extends BridgeTestCase {
import org.sonar.api.design.Dependency;
import org.sonar.api.resources.JavaPackage;
import org.sonar.api.resources.Resource;
+import org.sonar.graph.DirectedGraph;
+import org.sonar.graph.Dsm;
+import org.sonar.graph.DsmManualSorter;
import org.sonar.squid.api.SourceCode;
import org.sonar.squid.api.SourceCodeEdge;
import org.sonar.squid.api.SourceCodeEdgeUsage;
import org.sonar.squid.api.SourcePackage;
-import org.sonar.graph.DirectedGraph;
-import org.sonar.graph.Dsm;
-import org.sonar.graph.DsmManualSorter;
import java.io.IOException;
public class DsmSerializerTest {
@Test
- public void serializeEmptyDsm() throws IOException {
+ public void serializeEmptyDsm() {
Dsm dsm = new Dsm(new DirectedGraph());
assertThat(DsmSerializer.serialize(dsm, new DependencyIndex(), new ResourceIndex()), is("[]"));
}
resourceIndex.put(foo, fooSonar);
resourceIndex.put(bar, barSonar);
-
Dsm<SourceCode> dsm = new Dsm<SourceCode>(graph);
DsmManualSorter.sort(dsm, bar, foo); // for test reproductibility
String json = IOUtils.toString(getClass().getResourceAsStream("/org/sonar/plugins/squid/bridges/DsmSerializerTest/dsm.json"));
*/
package org.sonar.plugins.surefire;
+import com.google.common.collect.ImmutableList;
import org.sonar.api.CoreProperties;
import org.sonar.api.Properties;
import org.sonar.api.Property;
import org.sonar.api.SonarPlugin;
-import java.util.Arrays;
import java.util.List;
@Properties({
- @Property(
- key = CoreProperties.SUREFIRE_REPORTS_PATH_PROPERTY,
- name = "Report path",
- description = "Path (absolute or relative) to XML report files.",
- project = true,
- global = false)
+ @Property(
+ key = CoreProperties.SUREFIRE_REPORTS_PATH_PROPERTY,
+ name = "Report path",
+ description = "Path (absolute or relative) to XML report files.",
+ project = true,
+ global = false)
})
public final class SurefirePlugin extends SonarPlugin {
- public List getExtensions() {
- return Arrays.asList(SurefireSensor.class);
+ public List<Class<SurefireSensor>> getExtensions() {
+ return ImmutableList.of(SurefireSensor.class);
}
}
import org.junit.Before;
import org.junit.Test;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.resources.JavaFile;
import org.sonar.api.utils.StaxParser;
import org.sonar.test.TestUtils;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.verify;
public class SurefireStaxHandlerTest {
});
}
- private Server configureProgrammatically() throws URISyntaxException, IOException {
+ private Server configureProgrammatically() throws URISyntaxException {
configureServer();
WebAppContext context = new WebAppContext(getPath("/war/sonar-server"), contextPath);
server.addHandler(context);
server.addHandler(requestLogHandler);
}
- private void configureServer() throws URISyntaxException {
+ private void configureServer() {
QueuedThreadPool threadPool = new QueuedThreadPool();
threadPool.setMinThreads(5);
threadPool.setMaxThreads(50);
List<String> paths = new ArrayList<String>();
paths.add(pluginsDir.getCanonicalPath() + System.getProperty("file.separator"));
- Collection<File> files = FileUtils.listFiles(pluginsDir, new String[]{"jar"}, false);
+ Collection<File> files = FileUtils.listFiles(pluginsDir, new String[] {"jar"}, false);
if (files != null) {
for (File file : files) {
paths.add(file.getCanonicalPath());
import org.sonar.api.resources.Project;
import org.sonar.batch.bootstrap.ProjectFilter;
-import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ProjectTree {
- private ProjectConfigurator configurator;
+ private final ProjectConfigurator configurator;
private ProjectReactor projectReactor;
private List<Project> projects;
private Map<ProjectDefinition, Project> projectsByDef;
private ProjectFilter projectFilter;
- public ProjectTree(ProjectReactor projectReactor, //NOSONAR the unused parameter 'builders' is used for the startup order of components
- ProjectConfigurator projectConfigurator,
- ProjectFilter projectFilter,
- /* Must be executed after ProjectBuilders */ ProjectBuilder[] builders) {
+ public ProjectTree(ProjectReactor projectReactor, // NOSONAR the unused parameter 'builders' is used for the startup order of components
+ ProjectConfigurator projectConfigurator,
+ ProjectFilter projectFilter,
+ /* Must be executed after ProjectBuilders */ProjectBuilder[] builders) {
this(projectReactor, projectConfigurator, projectFilter);
}
- public ProjectTree(ProjectReactor projectReactor, //NOSONAR the unused parameter 'builders' is used for the startup order of components
- ProjectConfigurator projectConfigurator,
- ProjectFilter projectFilter) {
+ public ProjectTree(ProjectReactor projectReactor, // NOSONAR the unused parameter 'builders' is used for the startup order of components
+ ProjectConfigurator projectConfigurator,
+ ProjectFilter projectFilter) {
this.projectReactor = projectReactor;
this.configurator = projectConfigurator;
this.projectFilter = projectFilter;
this.configurator = configurator;
}
- public void start() throws IOException {
+ public void start() {
doStart(projectReactor.getProjects());
}
}
void applyExclusions() {
- for (Iterator<Project> it = projects.iterator(); it.hasNext(); ) {
+ for (Iterator<Project> it = projects.iterator(); it.hasNext();) {
Project project = it.next();
if (projectFilter.isExcluded(project)) {
project.setExcluded(true);
Class<?> lpClass = defineClass("org.sonar.batch.bootstrap.JdbcLeakPrevention", classBytes, 0, offset, this.getClass().getProtectionDomain());
Object obj = lpClass.newInstance();
- @SuppressWarnings("unchecked")
List<String> driverNames = (List<String>) obj.getClass().getMethod("clearJdbcDriverRegistrations").invoke(obj);
for (String name : driverNames) {
*/
package org.sonar.batch;
-import org.apache.commons.io.FileUtils;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
import org.sonar.api.resources.Languages;
import org.sonar.api.resources.Project;
+import org.sonar.test.TestUtils;
import java.io.File;
public class DefaultProjectFileSystem2Test {
@Test
public void shouldIgnoreInexistingSourceDirs() {
- File exists = FileUtils.toFile(getClass().getResource("/org/sonar/batch/DefaultProjectFileSystem2Test/shouldIgnoreInexistingSourceDirs"));
+ File exists = TestUtils.getResource("/org/sonar/batch/DefaultProjectFileSystem2Test/shouldIgnoreInexistingSourceDirs");
File notExists = new File("target/unknown");
ProjectDefinition definition = ProjectDefinition.create().addSourceDirs(exists, notExists);
DefaultProjectFileSystem2 fs = new DefaultProjectFileSystem2(new Project("foo"), new Languages(), definition);
assertThat(fs.getSourceDirs().size(), Is.is(1));
assertThat(fs.getSourceDirs(), hasItem(exists));
-
}
}
*/
package org.sonar.batch;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.StringReader;
-import java.net.URISyntaxException;
-import java.util.Arrays;
-import java.util.Properties;
-
import org.apache.commons.io.FileUtils;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.junit.Test;
import org.sonar.api.CoreProperties;
import org.sonar.api.batch.bootstrap.ProjectDefinition;
+import org.sonar.test.TestUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.StringReader;
+import java.net.URISyntaxException;
+import java.util.Arrays;
+import java.util.Properties;
+
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.fail;
public class MavenProjectConverterTest {
@Test
public void moduleNameShouldEqualArtifactId() throws Exception {
- File rootDir = FileUtils.toFile(getClass().getResource("/org/sonar/batch/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/"));
+ File rootDir = TestUtils.getResource("/org/sonar/batch/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/");
MavenProject parent = loadPom("/org/sonar/batch/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/pom.xml", true);
MavenProject module1 = loadPom("/org/sonar/batch/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/module1/pom.xml", false);
MavenProject module2 = loadPom("/org/sonar/batch/MavenProjectConverterTest/moduleNameShouldEqualArtifactId/module2/pom.xml", false);
@Test
public void moduleNameDifferentThanArtifactId() throws Exception {
- File rootDir = FileUtils.toFile(getClass().getResource("/org/sonar/batch/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/"));
+ File rootDir = TestUtils.getResource("/org/sonar/batch/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/");
MavenProject parent = loadPom("/org/sonar/batch/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/pom.xml", true);
MavenProject module1 = loadPom("/org/sonar/batch/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/path1/pom.xml", false);
MavenProject module2 = loadPom("/org/sonar/batch/MavenProjectConverterTest/moduleNameDifferentThanArtifactId/path2/pom.xml", false);
@Test
public void testSingleProjectWithoutModules() throws Exception {
- File rootDir = FileUtils.toFile(getClass().getResource("/org/sonar/batch/MavenProjectConverterTest/singleProjectWithoutModules/"));
+ File rootDir = TestUtils.getResource("/org/sonar/batch/MavenProjectConverterTest/singleProjectWithoutModules/");
MavenProject pom = loadPom("/org/sonar/batch/MavenProjectConverterTest/singleProjectWithoutModules/pom.xml", true);
ProjectDefinition rootDef = MavenProjectConverter.convert(Arrays.asList(pom), pom);
*/
package org.sonar.batch;
-import org.apache.commons.configuration.PropertiesConfiguration;
-import org.apache.maven.project.MavenProject;
import org.junit.Ignore;
-import org.sonar.api.resources.Project;
import org.sonar.jpa.test.AbstractDbUnitTestCase;
@Ignore
public class ProjectTreeTest extends AbstractDbUnitTestCase {
-// @Test
-// public void keyIncludesBranch() throws IOException, XmlPullParserException, URISyntaxException {
-// MavenProject pom = loadProject("/org/sonar/batch/ProjectTreeTest/keyIncludesBranch/pom.xml", true);
-//
-// ProjectTree tree = new ProjectTree(newConfigurator(), Arrays.asList(pom));
-// tree.start();
-//
-// assertThat(tree.getRootProject().getKey(), is("org.test:project:BRANCH-1.X"));
-// assertThat(tree.getRootProject().getName(), is("Project BRANCH-1.X"));
-// }
-//
-// @Test
-// public void doNotSkipAnyModules() {
-// Project foo = newProjectWithArtifactId("root");
-// Project bar = newProjectWithArtifactId("sub1");
-// Project baz = newProjectWithArtifactId("sub2");
-//
-// ProjectTree tree = new ProjectTree(Arrays.asList(foo, bar, baz));
-// tree.applyExclusions();
-//
-// assertThat(tree.getProjects().size(), is(3));
-// }
-//
-// @Test
-// public void skipModule() throws IOException {
-// Project root = newProjectWithArtifactId("root");
-// root.getConfiguration().setProperty("sonar.skippedModules", "sub1");
-// Project sub1 = newProjectWithArtifactId("sub1");
-// Project sub2 = newProjectWithArtifactId("sub2");
-//
-// ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
-// tree.applyExclusions();
-//
-// assertThat(tree.getProjects().size(), is(2));
-// assertThat(tree.getProjects(), hasItem(root));
-// assertThat(tree.getProjects(), hasItem(sub2));
-// }
-//
-// @Test
-// public void skipModules() {
-// Project root = newProjectWithArtifactId("root");
-// root.getConfiguration().setProperty("sonar.skippedModules", "sub1,sub2");
-// Project sub1 = newProjectWithArtifactId("sub1");
-// Project sub2 = newProjectWithArtifactId("sub2");
-//
-// ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
-// tree.applyExclusions();
-//
-// assertThat(tree.getProjects().size(), is(1));
-// assertThat(tree.getProjects(), hasItem(root));
-// }
-//
-// @Test
-// public void includeModules() {
-// Project root = newProjectWithArtifactId("root");
-// root.getConfiguration().setProperty("sonar.includedModules", "sub1,sub2");
-// Project sub1 = newProjectWithArtifactId("sub1");
-// Project sub2 = newProjectWithArtifactId("sub2");
-//
-// ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
-// tree.applyExclusions();
-//
-// assertThat(tree.getProjects().size(), is(2));
-// assertThat(tree.getProjects(), hasItem(sub1));
-// assertThat(tree.getProjects(), hasItem(sub2));
-// }
-//
-// @Test
-// public void skippedModulesTakePrecedenceOverIncludedModules() {
-// Project root = newProjectWithArtifactId("root");
-// root.getConfiguration().setProperty("sonar.includedModules", "sub1,sub2");
-// root.getConfiguration().setProperty("sonar.skippedModules", "sub1");
-// Project sub1 = newProjectWithArtifactId("sub1");
-// Project sub2 = newProjectWithArtifactId("sub2");
-//
-// ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
-// tree.applyExclusions();
-//
-// assertThat(tree.getProjects().size(), is(1));
-// assertThat(tree.getProjects(), hasItem(sub2));
-// }
+ // @Test
+ // public void keyIncludesBranch() throws IOException, XmlPullParserException, URISyntaxException {
+ // MavenProject pom = loadProject("/org/sonar/batch/ProjectTreeTest/keyIncludesBranch/pom.xml", true);
+ //
+ // ProjectTree tree = new ProjectTree(newConfigurator(), Arrays.asList(pom));
+ // tree.start();
+ //
+ // assertThat(tree.getRootProject().getKey(), is("org.test:project:BRANCH-1.X"));
+ // assertThat(tree.getRootProject().getName(), is("Project BRANCH-1.X"));
+ // }
+ //
+ // @Test
+ // public void doNotSkipAnyModules() {
+ // Project foo = newProjectWithArtifactId("root");
+ // Project bar = newProjectWithArtifactId("sub1");
+ // Project baz = newProjectWithArtifactId("sub2");
+ //
+ // ProjectTree tree = new ProjectTree(Arrays.asList(foo, bar, baz));
+ // tree.applyExclusions();
+ //
+ // assertThat(tree.getProjects().size(), is(3));
+ // }
+ //
+ // @Test
+ // public void skipModule() throws IOException {
+ // Project root = newProjectWithArtifactId("root");
+ // root.getConfiguration().setProperty("sonar.skippedModules", "sub1");
+ // Project sub1 = newProjectWithArtifactId("sub1");
+ // Project sub2 = newProjectWithArtifactId("sub2");
+ //
+ // ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ // tree.applyExclusions();
+ //
+ // assertThat(tree.getProjects().size(), is(2));
+ // assertThat(tree.getProjects(), hasItem(root));
+ // assertThat(tree.getProjects(), hasItem(sub2));
+ // }
+ //
+ // @Test
+ // public void skipModules() {
+ // Project root = newProjectWithArtifactId("root");
+ // root.getConfiguration().setProperty("sonar.skippedModules", "sub1,sub2");
+ // Project sub1 = newProjectWithArtifactId("sub1");
+ // Project sub2 = newProjectWithArtifactId("sub2");
+ //
+ // ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ // tree.applyExclusions();
+ //
+ // assertThat(tree.getProjects().size(), is(1));
+ // assertThat(tree.getProjects(), hasItem(root));
+ // }
+ //
+ // @Test
+ // public void includeModules() {
+ // Project root = newProjectWithArtifactId("root");
+ // root.getConfiguration().setProperty("sonar.includedModules", "sub1,sub2");
+ // Project sub1 = newProjectWithArtifactId("sub1");
+ // Project sub2 = newProjectWithArtifactId("sub2");
+ //
+ // ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ // tree.applyExclusions();
+ //
+ // assertThat(tree.getProjects().size(), is(2));
+ // assertThat(tree.getProjects(), hasItem(sub1));
+ // assertThat(tree.getProjects(), hasItem(sub2));
+ // }
+ //
+ // @Test
+ // public void skippedModulesTakePrecedenceOverIncludedModules() {
+ // Project root = newProjectWithArtifactId("root");
+ // root.getConfiguration().setProperty("sonar.includedModules", "sub1,sub2");
+ // root.getConfiguration().setProperty("sonar.skippedModules", "sub1");
+ // Project sub1 = newProjectWithArtifactId("sub1");
+ // Project sub2 = newProjectWithArtifactId("sub2");
+ //
+ // ProjectTree tree = new ProjectTree(Arrays.asList(root, sub1, sub2));
+ // tree.applyExclusions();
+ //
+ // assertThat(tree.getProjects().size(), is(1));
+ // assertThat(tree.getProjects(), hasItem(sub2));
+ // }
- private Project newProjectWithArtifactId(String artifactId) {
- MavenProject pom = new MavenProject();
- pom.setArtifactId(artifactId);
- return new Project("org.example:" + artifactId).setPom(pom).setConfiguration(new PropertiesConfiguration());
- }
+ // private Project newProjectWithArtifactId(String artifactId) {
+ // MavenProject pom = new MavenProject();
+ // pom.setArtifactId(artifactId);
+ // return new Project("org.example:" + artifactId).setPom(pom).setConfiguration(new PropertiesConfiguration());
+ // }
}
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
-import java.text.ParseException;
-
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ServerMetadataTest {
@Test
- public void testLoadProperties() throws ParseException {
+ public void testLoadProperties() {
Settings settings = new Settings();
settings.setProperty(CoreProperties.SERVER_ID, "123");
settings.setProperty(CoreProperties.SERVER_VERSION, "2.2");
* The maven plugin fails if the property sonar.host.url ends with a slash
*/
@Test
- public void urlMustNotEndWithSlash() throws ParseException {
+ public void urlMustNotEndWithSlash() {
Settings settings = new Settings();
settings.setProperty("sonar.host.url", "http://localhost:80/");
Map<PluginMetadata, Plugin> result = Maps.newHashMap();
result.put(METADATA,
new SonarPlugin() {
- public List getExtensions() {
+ public List<Class> getExtensions() {
return Arrays.asList(classes);
}
}
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
import org.sonar.core.plugins.RemotePlugin;
+import org.sonar.test.TestUtils;
import java.io.File;
import java.io.IOException;
@After
public void tearDown() {
- if (repository!=null) {
+ if (repository != null) {
repository.stop();
}
}
assertThat(repository.getPlugin("checkstyle"), not(nullValue()));
assertThat(repository.getMetadata().size(), Matchers.is(1));
assertThat(repository.getMetadata("checkstyle").getName(), Matchers.is("Checkstyle"));
- assertThat(repository.getMetadata("checkstyle").getDeployedFiles().size(), Matchers.is(5)); // plugin + 3 dependencies + 1 deprecated extension
+ assertThat(repository.getMetadata("checkstyle").getDeployedFiles().size(), Matchers.is(5)); // plugin + 3 dependencies + 1 deprecated
+ // extension
}
@Test
}
private List<File> copyFiles(String... filenames) throws IOException {
- List files = Lists.newArrayList();
+ List<File> files = Lists.newArrayList();
for (String filename : filenames) {
- File file = FileUtils.toFile(getClass().getResource("/org/sonar/batch/bootstrap/BatchPluginRepositoryTest/" + filename));
+ File file = TestUtils.getResource("/org/sonar/batch/bootstrap/BatchPluginRepositoryTest/" + filename);
File tempDir = new File("target/test-tmp/BatchPluginRepositoryTest");
FileUtils.forceMkdir(tempDir);
FileUtils.copyFileToDirectory(file, tempDir);
return files;
}
-
@Test
public void shouldAlwaysAcceptIfNoWhiteListAndBlackList() {
repository = new BatchPluginRepository(mock(ArtifactDownloader.class), new Settings());
*/
package org.sonar.batch.bootstrap;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import org.apache.maven.project.MavenProject;
import org.junit.Test;
-import org.sonar.api.*;
+import org.sonar.api.BatchExtension;
+import org.sonar.api.CoreProperties;
+import org.sonar.api.Extension;
+import org.sonar.api.Plugin;
+import org.sonar.api.ServerExtension;
+import org.sonar.api.SonarPlugin;
import org.sonar.api.batch.CoverageExtension;
import org.sonar.api.batch.InstantiationStrategy;
import org.sonar.api.batch.SupportedEnvironment;
import org.sonar.api.resources.Project;
import org.sonar.batch.bootstrapper.EnvironmentInformation;
-import java.util.Arrays;
import java.util.List;
import java.util.Map;
-import static org.hamcrest.Matchers.*;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
BatchPluginRepository pluginRepository = mock(BatchPluginRepository.class);
Map<String, Plugin> pluginsMap = Maps.newHashMap();
pluginsMap.put("fooPlugin", new SonarPlugin() {
- public List getExtensions() {
- return Arrays.asList(BatchService.class, ProjectService.class, ServerService.class);
+ public List<Class<? extends Extension>> getExtensions() {
+ return ImmutableList.of(BatchService.class, ProjectService.class, ServerService.class);
}
});
when(pluginRepository.getPluginsByKey()).thenReturn(pluginsMap);
BatchPluginRepository pluginRepository = mock(BatchPluginRepository.class);
Map<String, Plugin> pluginsMap = Maps.newHashMap();
pluginsMap.put("fooPlugin", new SonarPlugin() {
- public List getExtensions() {
- return Arrays.asList(MavenService.class, BuildToolService.class);
+ public List<Class<? extends BatchExtension>> getExtensions() {
+ return ImmutableList.of(MavenService.class, BuildToolService.class);
}
});
when(pluginRepository.getPluginsByKey()).thenReturn(pluginsMap);
}
-
@SupportedEnvironment("maven")
public static class MavenService implements BatchExtension {
}
@After
- public void after() throws IOException {
+ public void after() {
if (tempDirectories != null) {
tempDirectories.stop();
}
}
@Test
- public void shouldCreateRoot() throws IOException {
+ public void shouldCreateRoot() {
assertNotNull(tempDirectories.getRoot());
assertThat(tempDirectories.getRoot().exists(), is(true));
assertThat(tempDirectories.getRoot().isDirectory(), is(true));
}
@Test
- public void shouldCreateDirectory() throws IOException {
+ public void shouldCreateDirectory() {
File findbugsDir = tempDirectories.getDir("findbugs");
assertNotNull(findbugsDir);
assertThat(findbugsDir.exists(), is(true));
}
@Test
- public void shouldStopAndDeleteDirectory() throws IOException {
+ public void shouldStopAndDeleteDirectory() {
File root = tempDirectories.getRoot();
File findbugsDir = tempDirectories.getDir("findbugs");
assertThat(findbugsDir.exists(), is(true));
tempDirectories.stop();
-
+
assertThat(root.exists(), is(false));
assertThat(findbugsDir.exists(), is(false));
}
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Test
- public void shouldGetNextSnapshot() throws ParseException {
+ public void shouldGetNextSnapshot() {
setupData("shared");
Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
}
@Test
- public void shouldIgnoreUnprocessedSnapshots() throws ParseException {
+ public void shouldIgnoreUnprocessedSnapshots() {
setupData("shared");
Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
}
@Test
- public void shouldNotFindSelf() throws ParseException {
+ public void shouldNotFindSelf() {
setupData("shouldNotFindSelf");
Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1009); // 2008-11-16
newSnapshot(2, "2010-10-03"),// -2 days
newSnapshot(3, "2010-10-08"),// +3 days
newSnapshot(4, "2010-10-12") // + 7 days
- );
+ );
assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15).getId(), is(2));
}
newSnapshot(2, "2010-10-01"),// -4 days
newSnapshot(3, "2010-10-08"),// +3 days
newSnapshot(4, "2010-10-12") // + 7 days
- );
+ );
assertThat(PastSnapshotFinderByDays.getNearestToTarget(snapshots, current, 15).getId(), is(3));
}
*/
package org.sonar.batch.components;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.core.IsNull.nullValue;
-import static org.junit.Assert.assertThat;
-
import org.junit.Test;
import org.sonar.api.database.model.Snapshot;
import org.sonar.jpa.test.AbstractDbUnitTestCase;
-import java.text.ParseException;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.core.IsNull.nullValue;
+import static org.junit.Assert.assertThat;
public class PastSnapshotFinderByPreviousAnalysisTest extends AbstractDbUnitTestCase {
@Test
- public void shouldFindPreviousAnalysis() throws ParseException {
+ public void shouldFindPreviousAnalysis() {
setupData("shouldFindPreviousAnalysis");
Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
}
@Test
- public void shouldReturnPastSnapshotEvenWhenNoPreviousAnalysis() throws ParseException {
+ public void shouldReturnPastSnapshotEvenWhenNoPreviousAnalysis() {
setupData("shouldNotFindPreviousAnalysis");
Snapshot projectSnapshot = getSession().getSingleResult(Snapshot.class, "id", 1010);
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.*;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class PastSnapshotFinderTest {
}
@Test
- public void shouldNotFindByDate() throws ParseException {
+ public void shouldNotFindByDate() {
when(finderByDate.findByDate((Snapshot) anyObject(), (Date) anyObject())).thenReturn(null);
PastSnapshot variationSnapshot = finder.find(null, 2, "2010-05-18");
@Test
public void shouldNotFailIfUnknownFormat() {
- when(finderByPreviousAnalysis.findByPreviousAnalysis(null)).thenReturn(new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS, new Date(), new Snapshot())); // should not be called
+ when(finderByPreviousAnalysis.findByPreviousAnalysis(null)).thenReturn(new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_ANALYSIS, new Date(), new Snapshot())); // should
+ // not
+ // be
+ // called
assertNull(finder.find(null, 2, "foooo"));
}
moduleB1.setParent(moduleB);
}
-
@Test
public void shouldSaveNewProject() {
setupData("shared");
ResourcePersister persister = new DefaultResourcePersister(getSession());
persister.saveProject(singleProject, null);
- checkTablesWithExcludedColumns("shouldSaveNewProject", new String[]{"build_date"}, "projects", "snapshots");
+ checkTablesWithExcludedColumns("shouldSaveNewProject", new String[] {"build_date"}, "projects", "snapshots");
}
@Test
- public void shouldSaveNewMultiModulesProject() throws ParseException {
+ public void shouldSaveNewMultiModulesProject() {
setupData("shared");
ResourcePersister persister = new DefaultResourcePersister(getSession());
persister.saveProject(moduleB, multiModuleProject);
persister.saveProject(moduleB1, moduleB);
- checkTablesWithExcludedColumns("shouldSaveNewMultiModulesProject", new String[]{"build_date"}, "projects", "snapshots");
+ checkTablesWithExcludedColumns("shouldSaveNewMultiModulesProject", new String[] {"build_date"}, "projects", "snapshots");
}
@Test
persister.saveResource(singleProject, new JavaPackage("org.foo").setEffectiveKey("foo:org.foo"));
// check that the directory is attached to the project
- checkTablesWithExcludedColumns("shouldSaveNewDirectory", new String[]{"build_date"}, "projects", "snapshots");
+ checkTablesWithExcludedColumns("shouldSaveNewDirectory", new String[] {"build_date"}, "projects", "snapshots");
}
@Test
persister.saveResource(singleProject, new Library("junit:junit", "4.8.2").setEffectiveKey("junit:junit"));// do nothing, already saved
persister.saveResource(singleProject, new Library("junit:junit", "3.2").setEffectiveKey("junit:junit"));
- checkTablesWithExcludedColumns("shouldSaveNewLibrary", new String[]{"build_date"}, "projects", "snapshots");
+ checkTablesWithExcludedColumns("shouldSaveNewLibrary", new String[] {"build_date"}, "projects", "snapshots");
}
@Test
singleProject.setDescription("new description");
persister.saveProject(singleProject, null);
- checkTablesWithExcludedColumns("shouldUpdateExistingResource", new String[]{"build_date"}, "projects", "snapshots");
+ checkTablesWithExcludedColumns("shouldUpdateExistingResource", new String[] {"build_date"}, "projects", "snapshots");
}
// SONAR-1700
ResourcePersister persister = new DefaultResourcePersister(getSession());
persister.saveProject(singleProject, null);
- checkTablesWithExcludedColumns("shouldRemoveRootIndexIfResourceIsProject", new String[]{"build_date"}, "projects", "snapshots");
+ checkTablesWithExcludedColumns("shouldRemoveRootIndexIfResourceIsProject", new String[] {"build_date"}, "projects", "snapshots");
}
}
*/
package org.sonar.check;
-import org.junit.Test;
-
-import java.lang.reflect.Field;
-import java.util.List;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.*;
-
@Check(isoCategory = IsoCategory.Portability, priority = Priority.CRITICAL)
class SimplestCheck {
}
@Test
- public void defineNewLanguage() throws IOException {
+ public void defineNewLanguage() {
}
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.Environment;
-import org.apache.ibatis.session.*;
+import org.apache.ibatis.session.Configuration;
+import org.apache.ibatis.session.ExecutorType;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
+import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.slf4j.LoggerFactory;
import org.sonar.api.BatchComponent;
import org.sonar.api.ServerComponent;
-import org.sonar.core.dashboard.*;
+import org.sonar.core.dashboard.ActiveDashboardDto;
+import org.sonar.core.dashboard.ActiveDashboardMapper;
+import org.sonar.core.dashboard.DashboardDto;
+import org.sonar.core.dashboard.DashboardMapper;
+import org.sonar.core.dashboard.WidgetDto;
+import org.sonar.core.dashboard.WidgetMapper;
+import org.sonar.core.dashboard.WidgetPropertyDto;
+import org.sonar.core.dashboard.WidgetPropertyMapper;
import org.sonar.core.duplication.DuplicationMapper;
import org.sonar.core.duplication.DuplicationUnitDto;
import org.sonar.core.properties.PropertiesMapper;
import org.sonar.core.purge.PurgeMapper;
import org.sonar.core.purge.PurgeVendorMapper;
import org.sonar.core.purge.PurgeableSnapshotDto;
-import org.sonar.core.resource.*;
+import org.sonar.core.resource.ResourceDto;
+import org.sonar.core.resource.ResourceIndexDto;
+import org.sonar.core.resource.ResourceIndexerMapper;
+import org.sonar.core.resource.ResourceMapper;
+import org.sonar.core.resource.SnapshotDto;
import org.sonar.core.review.ReviewDto;
import org.sonar.core.review.ReviewMapper;
import org.sonar.core.rule.RuleDto;
import org.sonar.core.user.AuthorDto;
import org.sonar.core.user.AuthorMapper;
-import java.io.IOException;
import java.io.InputStream;
public class MyBatis implements BatchComponent, ServerComponent {
- private Database database;
+ private final Database database;
private SqlSessionFactory sessionFactory;
public MyBatis(Database database) {
this.database = database;
}
- public MyBatis start() throws IOException {
+ public MyBatis start() {
LogFactory.useSlf4jLogging();
Configuration conf = new Configuration();
conf.setEnvironment(new Environment("production", createTransactionFactory(), database.getDataSource()));
}
}
- private void loadMapper(Configuration conf, Class mapperClass) throws IOException {
+ private void loadMapper(Configuration conf, Class mapperClass) {
// trick to use database-specific XML files for a single Mapper Java interface
InputStream input = getPathToMapper(mapperClass);
try {
private InputStream getPathToMapper(Class mapperClass) {
InputStream input = getClass().getResourceAsStream(
- "/" + StringUtils.replace(mapperClass.getName(), ".", "/") + "-" + database.getDialect().getId() + ".xml");
+ "/" + StringUtils.replace(mapperClass.getName(), ".", "/") + "-" + database.getDialect().getId() + ".xml");
if (input == null) {
input = getClass().getResourceAsStream("/" + StringUtils.replace(mapperClass.getName(), ".", "/") + ".xml");
}
import org.sonar.core.persistence.dialect.Oracle;
import org.sonar.core.persistence.dialect.PostgreSql;
-import java.sql.SQLException;
import java.util.Properties;
import static org.hamcrest.Matchers.nullValue;
DerbyUtils.fixDerbyLogs();
}
-
@Test
public void shouldLoadDefaultValues() {
DefaultDatabase db = new DefaultDatabase(new Settings());
}
@Test
- public void shouldStart() throws SQLException {
+ public void shouldStart() {
Settings settings = new Settings();
settings.setProperty("sonar.jdbc.url", "jdbc:derby:memory:sonar;create=true;user=sonar;password=sonar");
settings.setProperty("sonar.jdbc.driverClassName", "org.apache.derby.jdbc.EmbeddedDriver");
}
}
-
@Test
public void shouldInitSchema() {
Settings settings = new Settings();
Connection connection = db.getDataSource().getConnection();
assertNotNull(connection);
- ResultSet resultSet = connection.getMetaData().getTables("", null, null, new String[]{"TABLE"});
+ ResultSet resultSet = connection.getMetaData().getTables("", null, null, new String[] {"TABLE"});
while (resultSet.next()) {
tables++;
}
-
} finally {
db.stop();
}
}
@Test
- public void shouldLimitThePoolSize() throws SQLException {
+ public void shouldLimitThePoolSize() {
InMemoryDatabase db = new InMemoryDatabase();
try {
db.startDatabase();
- assertThat(((BasicDataSource)db.getDataSource()).getMaxActive(), Is.is(2));
- assertThat(((BasicDataSource)db.getDataSource()).getMaxIdle(), Is.is(2));
+ assertThat(((BasicDataSource) db.getDataSource()).getMaxActive(), Is.is(2));
+ assertThat(((BasicDataSource) db.getDataSource()).getMaxIdle(), Is.is(2));
} finally {
db.stop();
import org.junit.Test;
import org.sonar.core.rule.RuleMapper;
-import java.io.IOException;
-
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
private static InMemoryDatabase database;
@BeforeClass
- public static void start() throws IOException {
+ public static void start() {
database = new InMemoryDatabase();
myBatis = new MyBatis(database.start());
myBatis.start();
}
@AfterClass
- public static void stop() throws IOException {
+ public static void stop() {
database.stop();
}
@Test
- public void shouldConfigureMyBatis() throws IOException {
+ public void shouldConfigureMyBatis() {
Configuration conf = myBatis.getSessionFactory().getConfiguration();
assertThat(conf.isUseGeneratedKeys(), Is.is(true));
assertThat(conf.hasMapper(RuleMapper.class), Is.is(true));
}
@Test
- public void shouldOpenBatchSession() throws IOException {
+ public void shouldOpenBatchSession() {
SqlSession session = myBatis.openBatchSession();
try {
assertThat(session.getConnection(), notNullValue());
import java.io.File;
import java.io.FilenameFilter;
-import java.io.IOException;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class AbstractLanguageTest {
@Test
- public void shouldCreateCorrectFilenameFilterForExtensions() throws IOException {
+ public void shouldCreateCorrectFilenameFilterForExtensions() {
AbstractLanguage language = new AbstractLanguage(null, "java") {
};
*/
package org.sonar.duplications.java;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.number.OrderingComparisons.greaterThan;
-import static org.junit.Assert.assertThat;
-
-import java.io.*;
-import java.nio.charset.Charset;
-import java.util.List;
-
+import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.duplications.DuplicationsTestUtil;
import org.sonar.duplications.statement.StatementChunker;
import org.sonar.duplications.token.TokenChunker;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.util.List;
+
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.number.OrderingComparisons.greaterThan;
+import static org.junit.Assert.assertThat;
+
public class JavaStatementBuilderTest {
- private TokenChunker tokenChunker = JavaTokenProducer.build();
- private StatementChunker statementChunker = JavaStatementBuilder.build();
+ private final TokenChunker tokenChunker = JavaTokenProducer.build();
+ private final StatementChunker statementChunker = JavaStatementBuilder.build();
private List<Statement> chunk(String sourceCode) {
return statementChunker.chunk(tokenChunker.chunk(sourceCode));
@Test
public void shouldHandleAnnotation() {
List<Statement> statements = chunk("" +
- "@Entity" +
- "@Table(name = \"properties\")" +
- "@Column(updatable = true, nullable = true)");
+ "@Entity" +
+ "@Table(name = \"properties\")" +
+ "@Column(updatable = true, nullable = true)");
assertThat(statements.size(), is(3));
assertThat(statements.get(0).getValue(), is("@Entity"));
assertThat(statements.get(1).getValue(), is("@Table(name=$CHARS)"));
@Test
public void shouldHandleSwitch() {
List<Statement> statements = chunk("" +
- "switch (month) {" +
- " case 1 : monthString=\"January\"; break;" +
- " case 2 : monthString=\"February\"; break;" +
- " default: monthString=\"Invalid\";" +
- "}");
+ "switch (month) {" +
+ " case 1 : monthString=\"January\"; break;" +
+ " case 2 : monthString=\"February\"; break;" +
+ " default: monthString=\"Invalid\";" +
+ "}");
assertThat(statements.size(), is(6));
assertThat(statements.get(0).getValue(), is("switch(month)"));
assertThat(statements.get(1).getValue(), is("case$NUMBER:monthString=$CHARS"));
@Test
public void shouldHandleNestedSwitch() {
List<Statement> statements = chunk("" +
- "switch (a) {" +
- " case 'a': case 'b': case 'c': something(); break;" +
- " case 'd': case 'e': case 'f': somethingOther(); break;" +
- "}");
+ "switch (a) {" +
+ " case 'a': case 'b': case 'c': something(); break;" +
+ " case 'd': case 'e': case 'f': somethingOther(); break;" +
+ "}");
assertThat(statements.size(), is(5));
assertThat(statements.get(0).getValue(), is("switch(a)"));
assertThat(statements.get(1).getValue(), is("case$CHARS:case$CHARS:case$CHARS:something()"));
private List<Statement> chunk(File file) {
Reader reader = null;
try {
- reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
+ reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8);
return statementChunker.chunk(tokenChunker.chunk(reader));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
*/
package org.sonar.duplications.java;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.number.OrderingComparisons.greaterThan;
-import static org.junit.Assert.assertThat;
+import com.google.common.base.Charsets;
+import com.google.common.collect.Lists;
+import org.apache.commons.io.IOUtils;
+import org.hamcrest.Matcher;
+import org.junit.Test;
+import org.sonar.duplications.DuplicationsTestUtil;
+import org.sonar.duplications.token.Token;
+import org.sonar.duplications.token.TokenChunker;
+import org.sonar.duplications.token.TokenQueue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
-import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
-import org.apache.commons.io.IOUtils;
-import org.hamcrest.Matcher;
-import org.junit.Test;
-import org.sonar.duplications.DuplicationsTestUtil;
-import org.sonar.duplications.token.Token;
-import org.sonar.duplications.token.TokenChunker;
-import org.sonar.duplications.token.TokenQueue;
-
-import com.google.common.collect.Lists;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.number.OrderingComparisons.greaterThan;
+import static org.junit.Assert.assertThat;
public class JavaTokenProducerTest {
- private TokenChunker chunker = JavaTokenProducer.build();
+ private final TokenChunker chunker = JavaTokenProducer.build();
/**
* <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.6">White Space</a>
private TokenQueue chunk(File file) {
Reader reader = null;
try {
- reader = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
+ reader = new InputStreamReader(new FileInputStream(file), Charsets.UTF_8);
return chunker.chunk(reader);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
*/
package org.sonar.graph;
-import java.io.IOException;
-
import org.junit.Test;
import static org.junit.Assert.assertEquals;
}
@Test(expected = IllegalStateException.class)
- public void sortCyclicGraph() throws IOException {
+ public void sortCyclicGraph() {
StringPrintWriter textDsm = new StringPrintWriter();
textDsm.println(" | A | B | C | D |");
textDsm.println("A | | | | |");
}
@Test
- public void sortCyclicGraphWithManuallyFlaggedFeedbackEdges() throws IOException {
+ public void sortCyclicGraphWithManuallyFlaggedFeedbackEdges() {
StringPrintWriter textDsm = new StringPrintWriter();
textDsm.println(" | A | B | C | D |");
textDsm.println("A | | | | |");
}
@Test
- public void sortCyclicGraphWithFlaggedFeedbackEdges() throws IOException {
+ public void sortCyclicGraphWithFlaggedFeedbackEdges() {
DirectedGraph<String, StringEdge> dcg = DirectedGraph.createStringDirectedGraph();
dcg.addEdge("A", "B", 3).addEdge("B", "A", 1);
CycleDetector<String> cycleDetector = new CycleDetector<String>(dcg);
import org.junit.Test;
-import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
-import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import org.sonar.wsclient.gwt.GwtUtils;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
+
import java.io.File;
import java.io.IOException;
-import java.security.InvalidKeyException;
import java.security.Key;
-import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
-import java.security.spec.InvalidKeySpecException;
final class AesCipher extends Cipher {
this.settings = settings;
}
+ @Override
String encrypt(String clearText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_KEY);
}
}
+ @Override
String decrypt(String encryptedText) {
try {
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(CRYPTO_KEY);
return false;
}
- private Key loadSecretFile() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException {
+ private Key loadSecretFile() throws IOException {
String path = getPathToSecretKey();
return loadSecretFileFromFile(path);
}
@VisibleForTesting
- Key loadSecretFileFromFile(@Nullable String path) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException {
+ Key loadSecretFileFromFile(@Nullable String path) throws IOException {
if (StringUtils.isBlank(path)) {
throw new IllegalStateException("Secret key not found. Please set the property " + CoreProperties.ENCRYPTION_SECRET_KEY_PATH);
}
*/
public final class AnnotationProfileParser implements ServerComponent {
- private RuleFinder ruleFinder;
+ private final RuleFinder ruleFinder;
public AnnotationProfileParser(RuleFinder ruleFinder) {
this.ruleFinder = ruleFinder;
public RulesProfile parse(String repositoryKey, String profileName, String language, Collection<Class> annotatedClasses, ValidationMessages messages) {
RulesProfile profile = RulesProfile.create(profileName, language);
- for (Class aClass : annotatedClasses) {
- BelongsToProfile belongsToProfile = (BelongsToProfile) aClass.getAnnotation(BelongsToProfile.class);
+ for (Class<?> aClass : annotatedClasses) {
+ BelongsToProfile belongsToProfile = aClass.getAnnotation(BelongsToProfile.class);
addRule(aClass, belongsToProfile, profile, repositoryKey, messages);
}
return profile;
}
private void addRule(Class aClass, BelongsToProfile annotation, RulesProfile profile, String repositoryKey, ValidationMessages messages) {
- if (annotation != null && StringUtils.equals(annotation.title(), profile.getName())) {
+ if ((annotation != null) && StringUtils.equals(annotation.title(), profile.getName())) {
String ruleKey = RuleAnnotationUtils.getRuleKey(aClass);
Rule rule = ruleFinder.findByKey(repositoryKey, ruleKey);
if (rule == null) {
*/
package org.sonar.api.profiles;
+import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;
-import org.codehaus.stax2.XMLInputFactory2;
import org.codehaus.staxmate.SMInputFactory;
import org.codehaus.staxmate.in.SMHierarchicCursor;
import org.codehaus.staxmate.in.SMInputCursor;
import org.sonar.api.utils.Logs;
import org.sonar.api.utils.ValidationMessages;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamException;
+
import java.io.InputStreamReader;
import java.io.Reader;
-import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-
/**
* TODO should be an interface
*
*/
public final class XMLProfileParser implements ServerComponent {
- private RuleFinder ruleFinder;
+ private final RuleFinder ruleFinder;
private MetricFinder metricFinder;
/**
}
public RulesProfile parseResource(ClassLoader classloader, String xmlClassPath, ValidationMessages messages) {
- Reader reader = new InputStreamReader(classloader.getResourceAsStream(xmlClassPath), Charset.forName(CharEncoding.UTF_8));
+ Reader reader = new InputStreamReader(classloader.getResourceAsStream(xmlClassPath), Charsets.UTF_8);
try {
return parse(reader, messages);
}
private SMInputFactory initStax() {
- XMLInputFactory xmlFactory = XMLInputFactory2.newInstance();
+ XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
// just so it won't try to load DTD in if there's DOCTYPE
for (Map.Entry<String, String> entry : parameters.entrySet()) {
if (rule.getParam(entry.getKey()) == null) {
messages.addWarningText("The parameter '" + entry.getKey() + "' does not exist in the rule: [repository=" + repositoryKey
- + ", key=" + key + "]");
+ + ", key=" + key + "]");
} else {
activeRule.setParameter(entry.getKey(), entry.getValue());
}
import org.junit.Before;
import org.junit.Test;
import org.mockito.exceptions.verification.junit.ArgumentsAreDifferent;
-import org.sonar.api.resources.*;
+import org.sonar.api.resources.Java;
+import org.sonar.api.resources.JavaFile;
+import org.sonar.api.resources.Language;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.ProjectFileSystem;
+import org.sonar.api.resources.Resource;
import java.io.File;
-import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.*;
-import static org.mockito.Mockito.*;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Matchers.argThat;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class AbstractSourceImporterTest {
@Before
public void setup() throws UnsupportedEncodingException {
- aClaess = new String(new byte[] { 65, 67, 108, 97, -61, -88, 115, 115, 40, 41 }, CharEncoding.UTF_8);
- explicacao = new String(new byte[] { 101, 120, 112, 108, 105, 99, 97, -61, -89, -61, -93, 111, 40, 41 }, CharEncoding.UTF_8);
+ aClaess = new String(new byte[] {65, 67, 108, 97, -61, -88, 115, 115, 40, 41}, CharEncoding.UTF_8);
+ explicacao = new String(new byte[] {101, 120, 112, 108, 105, 99, 97, -61, -89, -61, -93, 111, 40, 41}, CharEncoding.UTF_8);
importer = new FakeSourceImporter();
}
}
@Test
- public void doNotSaveSourceIfNullResource() throws IOException {
+ public void doNotSaveSourceIfNullResource() {
AbstractSourceImporter nullImporter = new AbstractSourceImporter(Java.INSTANCE) {
@Override
*/
package org.sonar.api.batch.maven;
+import com.google.common.base.Charsets;
import org.apache.maven.project.MavenProject;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.test.MavenTestUtils;
import java.nio.charset.Charset;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
public class MavenUtilsTest {
private MavenProject pom;
@Test
public void testSourceEncoding() {
MavenProject pom = MavenTestUtils.loadPom("/org/sonar/api/batch/maven/MavenPomWithSourceEncoding.xml");
- assertEquals(MavenUtils.getSourceCharset(pom), Charset.forName("UTF-16"));
+ assertEquals(MavenUtils.getSourceCharset(pom), Charsets.UTF_16);
}
}
import org.jfree.chart.ChartUtilities;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
-import static org.junit.Assert.assertTrue;
-import javax.swing.*;
-import java.awt.*;
+import javax.swing.JPanel;
+
+import java.awt.Dimension;
+import java.awt.Graphics;
import java.awt.image.BufferedImage;
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
+import static org.junit.Assert.assertTrue;
+
public abstract class AbstractChartTest {
protected void assertChartSizeGreaterThan(BufferedImage img, int size) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
}
- protected static void displayTestPanel(BufferedImage image) throws IOException {
+ protected static void displayTestPanel(BufferedImage image) {
ApplicationFrame frame = new ApplicationFrame("testframe");
BufferedPanel imgPanel = new BufferedPanel(image);
frame.setContentPane(imgPanel);
}
private static class BufferedPanel extends JPanel {
- private BufferedImage chartImage;
+ private final BufferedImage chartImage;
public BufferedPanel(BufferedImage chartImage) {
this.chartImage = chartImage;
import java.util.Arrays;
-import static org.hamcrest.Matchers.*;
+import static org.hamcrest.Matchers.hasItems;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThat;
public class AnnotationCheckFactoryTest {
public void createCheckWithoutProperties() {
RulesProfile profile = RulesProfile.create("repo", "java");
ActiveRule activeRule = profile.activateRule(Rule.create("repo", "org.sonar.api.checks.CheckWithoutProperties", ""), null);
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithoutProperties.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithoutProperties.class));
Object check = factory.getCheck(activeRule);
assertNotNull(check);
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("pattern", "foo");
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithStringProperty.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithStringProperty.class));
Object check = factory.getCheck(activeRule);
assertNotNull(check);
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("unknown", "bar");
- AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithStringProperty.class));
+ AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithStringProperty.class));
}
@Test
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("max", "300");
activeRule.setParameter("ignore", "true");
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithPrimitiveProperties.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithPrimitiveProperties.class));
Object check = factory.getCheck(activeRule);
assertThat(((CheckWithPrimitiveProperties) check).getMax(), is(300));
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("max", "300");
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithIntegerProperty.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithIntegerProperty.class));
Object check = factory.getCheck(activeRule);
assertThat(((CheckWithIntegerProperty) check).getMax(), is(300));
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("max", "300");
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(ImplementedCheck.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(ImplementedCheck.class));
Object check = factory.getCheck(activeRule);
assertThat(((ImplementedCheck) check).getMax(), is(300));
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("max", "300");
- AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithUnsupportedPropertyType.class));
+ AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithUnsupportedPropertyType.class));
}
@Test
ActiveRule activeRule = profile.activateRule(rule, null);
activeRule.setParameter("maximum", "300");
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithOverriddenPropertyKey.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithOverriddenPropertyKey.class));
Object check = factory.getCheck(activeRule);
assertThat(((CheckWithOverriddenPropertyKey) check).getMax(), is(300));
profile.activateRule(rule, null);
profile.activateRule(clonedRule, null);
- AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class>asList(CheckWithKey.class));
+ AnnotationCheckFactory factory = AnnotationCheckFactory.create(profile, "repo", Arrays.<Class> asList(CheckWithKey.class));
assertThat(factory.getChecks(), (Matcher) not(hasItems(nullValue())));
}
import org.sonar.api.rules.RulePriority;
import org.sonar.api.utils.ValidationMessages;
-import java.io.UnsupportedEncodingException;
-
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertNotNull;
public class XMLProfileParserTest {
@Test
- public void importProfile() throws UnsupportedEncodingException {
+ public void importProfile() {
ValidationMessages validation = ValidationMessages.create();
RulesProfile profile = parse("importProfile.xml", validation);
}
@Test
- public void nameAndLanguageShouldBeMandatory() throws UnsupportedEncodingException {
+ public void nameAndLanguageShouldBeMandatory() {
ValidationMessages validation = ValidationMessages.create();
parse("nameAndLanguageShouldBeMandatory.xml", validation);
}
@Test
- public void importProfileWithRuleParameters() throws UnsupportedEncodingException {
+ public void importProfileWithRuleParameters() {
ValidationMessages validation = ValidationMessages.create();
RulesProfile profile = parse("importProfileWithRuleParameters.xml", validation);
}
@Test
- public void importProfileWithUnknownRuleParameter() throws UnsupportedEncodingException {
+ public void importProfileWithUnknownRuleParameter() {
ValidationMessages validation = ValidationMessages.create();
RulesProfile profile = parse("importProfileWithUnknownRuleParameter.xml", validation);
import org.junit.rules.TemporaryFolder;
import java.io.File;
-import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
public class JavaFileTest {
}
@Test
- public void oneLevelPackage() throws IOException {
+ public void oneLevelPackage() {
JavaFile clazz = new JavaFile("onelevel.MyFile");
assertEquals("onelevel.MyFile", clazz.getKey());
assertEquals("onelevel", clazz.getParent().getKey());
assertThat((javaFile.getParent()).isDefault(), is(false));
}
-
@Test
- public void shouldResolveClassFromAbsolutePath() throws IOException {
+ public void shouldResolveClassFromAbsolutePath() {
File sources1 = newDir("source1");
File sources2 = newDir("source2");
List<File> sources = Arrays.asList(sources1, sources2);
}
@Test
- public void shouldResolveFromAbsolutePathEvenIfDefaultPackage() throws IOException {
+ public void shouldResolveFromAbsolutePathEvenIfDefaultPackage() {
File source1 = newDir("source1");
File source2 = newDir("source2");
List<File> sources = Arrays.asList(source1, source2);
}
@Test
- public void shouldResolveOnlyJavaFromAbsolutePath() throws IOException {
+ public void shouldResolveOnlyJavaFromAbsolutePath() {
File source1 = newDir("source1");
List<File> sources = Arrays.asList(source1);
assertNull(JavaFile.fromAbsolutePath(absPath(source1, "foo/bar/my_file.sql"), sources, false));
}
@Test
- public void shouldNotFailWhenResolvingUnknownClassFromAbsolutePath() throws IOException {
+ public void shouldNotFailWhenResolvingUnknownClassFromAbsolutePath() {
File source1 = newDir("source1");
List<File> sources = Arrays.asList(source1);
assertNull(JavaFile.fromAbsolutePath("/home/other/src/main/java/foo/bar/MyClass.java", sources, false));
assertFalse(unitTest.matchFilePattern("**/*"));
}
-
- private File newDir(String dirName) throws IOException {
+ private File newDir(String dirName) {
return tempFolder.newFolder(dirName);
}
- private String absPath(File dir, String filePath) throws IOException {
+ private String absPath(File dir, String filePath) {
return new File(dir, filePath).getPath();
}
}
@Test
public void shouldFormatMapOfStrings() {
- Map<String,String> map = Maps.newLinkedHashMap();
+ Map<String, String> map = Maps.newLinkedHashMap();
map.put("lucky", "luke");
map.put("aste", "rix");
String s = KeyValueFormat.format(map);
@Test
public void shouldFormatMapOfIntegerString() {
- Map<Integer,String> map = Maps.newLinkedHashMap();
+ Map<Integer, String> map = Maps.newLinkedHashMap();
map.put(3, "three");
map.put(5, "five");
String s = KeyValueFormat.formatIntString(map);
@Test
public void shouldFormatMapOfIntDouble() {
- Map<Integer,Double> map = Maps.newLinkedHashMap();
+ Map<Integer, Double> map = Maps.newLinkedHashMap();
map.put(13, 2.0);
map.put(5, 5.75);
String s = KeyValueFormat.formatIntDouble(map);
@Test
public void shouldSetEmptyFieldWhenNullValue() {
- Map<Integer,Double> map = Maps.newLinkedHashMap();
+ Map<Integer, Double> map = Maps.newLinkedHashMap();
map.put(13, null);
map.put(5, 5.75);
String s = KeyValueFormat.formatIntDouble(map);
@Test
public void shouldFormatBlank() {
- Map<Integer,String> map = Maps.newTreeMap();
+ Map<Integer, String> map = Maps.newTreeMap();
String s = KeyValueFormat.formatIntString(map);
assertThat(s, is(""));
}
@Test
public void shouldFormatDate() throws ParseException {
- Map<Integer,Date> map = Maps.newLinkedHashMap();
+ Map<Integer, Date> map = Maps.newLinkedHashMap();
map.put(4, new SimpleDateFormat("yyyy-MM-dd").parse("2010-12-25"));
map.put(20, new SimpleDateFormat("yyyy-MM-dd").parse("2009-05-28"));
map.put(12, null);
}
@Test
- public void shouldParseStrings() throws ParseException {
- Map<String,String> map = KeyValueFormat.parse("one=un;two=deux");
+ public void shouldParseStrings() {
+ Map<String, String> map = KeyValueFormat.parse("one=un;two=deux");
assertThat(map.size(), is(2));
assertThat(map.get("one"), is("un"));
assertThat(map.get("two"), is("deux"));
- assertThat(map.keySet().iterator().next(), is("one"));//same order as in string
+ assertThat(map.keySet().iterator().next(), is("one"));// same order as in string
}
@Test
- public void shouldParseBlank() throws ParseException {
- Map<String,String> map = KeyValueFormat.parse("");
+ public void shouldParseBlank() {
+ Map<String, String> map = KeyValueFormat.parse("");
assertThat(map.size(), is(0));
}
@Test
- public void shouldParseNull() throws ParseException {
- Map<String,String> map = KeyValueFormat.parse(null);
+ public void shouldParseNull() {
+ Map<String, String> map = KeyValueFormat.parse(null);
assertThat(map.size(), is(0));
}
@Test
- public void shouldParseEmptyFields() throws ParseException {
- Map<Integer,Double> map = KeyValueFormat.parseIntDouble("4=4.2;2=;6=6.68");
+ public void shouldParseEmptyFields() {
+ Map<Integer, Double> map = KeyValueFormat.parseIntDouble("4=4.2;2=;6=6.68");
assertThat(map.size(), is(3));
assertThat(map.get(4), is(4.2));
assertThat(map.get(2), nullValue());
*/
package org.sonar.api.utils;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
import org.junit.Before;
import org.junit.Test;
-import java.io.IOException;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
public class ServerHttpClientTest {
- private String serverUrl = "http://test";
-
+ private final String serverUrl = "http://test";
+
private ServerHttpClient serverHttpClient;
@Before
}
@Test
- public void shouldReturnAValidResult() throws IOException {
+ public void shouldReturnAValidResult() {
final String validContent = "valid";
ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl) {
@Override
}
@Test(expected = ServerHttpClient.ServerApiEmptyContentException.class)
- public void shouldThrowAnExceptionIfResultIsEmpty() throws IOException {
+ public void shouldThrowAnExceptionIfResultIsEmpty() {
final String invalidContent = " ";
ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl) {
@Override
import org.slf4j.LoggerFactory;
import org.sonar.api.charts.Chart;
import org.sonar.api.charts.ChartParameters;
-import org.sonar.server.charts.deprecated.*;
+import org.sonar.server.charts.deprecated.BarChart;
+import org.sonar.server.charts.deprecated.BaseChartWeb;
+import org.sonar.server.charts.deprecated.CustomBarChart;
+import org.sonar.server.charts.deprecated.DeprecatedChart;
+import org.sonar.server.charts.deprecated.PieChart;
+import org.sonar.server.charts.deprecated.SparkLinesChart;
import org.sonar.server.platform.Platform;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
return false;
}
- public void deprecatedDoGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ public void deprecatedDoGet(HttpServletRequest request, HttpServletResponse response) {
Map<String, String> params = Maps.newHashMap();
params.put(BaseChartWeb.CHART_PARAM_TYPE, request.getParameter(BaseChartWeb.CHART_PARAM_TYPE));
params.put(BaseChartWeb.CHART_PARAM_VALUES, request.getParameter(BaseChartWeb.CHART_PARAM_VALUES));
import org.sonar.api.platform.PluginMetadata;
import org.sonar.api.platform.PluginRepository;
import org.sonar.api.platform.ServerFileSystem;
-import org.sonar.server.plugins.ClassLoaderUtils;
import javax.annotation.Nullable;
+
import java.io.File;
import java.io.IOException;
private static final Logger LOG = LoggerFactory.getLogger(ApplicationDeployer.class);
private static final String ROR_PATH = "org/sonar/ror/";
- private ServerFileSystem fileSystem;
- private PluginRepository pluginRepository;
+ private final ServerFileSystem fileSystem;
+ private final PluginRepository pluginRepository;
public ApplicationDeployer(ServerFileSystem fileSystem, PluginRepository pluginRepository) {
this.fileSystem = fileSystem;
this.pluginRepository = pluginRepository;
}
- public void start() throws IOException {
+ public void start() {
deployRubyRailsApps();
}
private static final Logger LOG = LoggerFactory.getLogger(PluginDeployer.class);
- private DefaultServerFileSystem fileSystem;
- private Map<String, PluginMetadata> pluginByKeys = Maps.newHashMap();
- private PluginInstaller installer;
+ private final DefaultServerFileSystem fileSystem;
+ private final Map<String, PluginMetadata> pluginByKeys = Maps.newHashMap();
+ private final PluginInstaller installer;
public PluginDeployer(DefaultServerFileSystem fileSystem) {
this(fileSystem, new PluginInstaller());
this.installer = installer;
}
- public void start() throws IOException {
+ public void start() {
TimeProfiler profiler = new TimeProfiler().start("Install plugins");
deleteUninstalledPlugins();
}
}
- private void loadUserPlugins() throws IOException {
+ private void loadUserPlugins() {
for (File file : fileSystem.getUserPlugins()) {
registerPlugin(file, false, false);
}
}
- private void registerPlugin(File file, boolean isCore, boolean canDelete) throws IOException {
+ private void registerPlugin(File file, boolean isCore, boolean canDelete) {
DefaultPluginMetadata metadata = installer.extractMetadata(file, isCore);
if (StringUtils.isNotBlank(metadata.getKey())) {
PluginMetadata existing = pluginByKeys.get(metadata.getKey());
} else {
throw new ServerStartException("Found two plugins with the same key '" + metadata.getKey() + "': " + metadata.getFile().getName() + " and "
- + existing.getFile().getName());
+ + existing.getFile().getName());
}
}
pluginByKeys.put(metadata.getKey(), metadata);
}
}
- private void moveAndLoadDownloadedPlugins() throws IOException {
+ private void moveAndLoadDownloadedPlugins() {
if (fileSystem.getDownloadedPluginsDir().exists()) {
- Collection<File> jars = FileUtils.listFiles(fileSystem.getDownloadedPluginsDir(), new String[]{"jar"}, false);
+ Collection<File> jars = FileUtils.listFiles(fileSystem.getDownloadedPluginsDir(), new String[] {"jar"}, false);
for (File jar : jars) {
File movedJar = moveDownloadedFile(jar);
if (movedJar != null) {
}
}
- private void loadCorePlugins() throws IOException {
+ private void loadCorePlugins() {
for (File file : fileSystem.getCorePlugins()) {
registerPlugin(file, true, false);
}
public void uninstall(String pluginKey) {
PluginMetadata metadata = pluginByKeys.get(pluginKey);
- if (metadata != null && !metadata.isCore()) {
+ if ((metadata != null) && !metadata.isCore()) {
try {
File masterFile = new File(fileSystem.getUserPluginsDir(), metadata.getFile().getName());
FileUtils.moveFileToDirectory(masterFile, fileSystem.getRemovedPluginsDir(), true);
public List<String> getUninstalls() {
List<String> names = Lists.newArrayList();
if (fileSystem.getRemovedPluginsDir().exists()) {
- List<File> files = (List<File>) FileUtils.listFiles(fileSystem.getRemovedPluginsDir(), new String[]{"jar"}, false);
+ List<File> files = (List<File>) FileUtils.listFiles(fileSystem.getRemovedPluginsDir(), new String[] {"jar"}, false);
for (File file : files) {
names.add(file.getName());
}
public void cancelUninstalls() {
if (fileSystem.getRemovedPluginsDir().exists()) {
- List<File> files = (List<File>) FileUtils.listFiles(fileSystem.getRemovedPluginsDir(), new String[]{"jar"}, false);
+ List<File> files = (List<File>) FileUtils.listFiles(fileSystem.getRemovedPluginsDir(), new String[] {"jar"}, false);
for (File file : files) {
try {
FileUtils.moveFileToDirectory(file, fileSystem.getUserPluginsDir(), false);
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
-import javax.swing.*;
-import java.awt.*;
+import javax.swing.JPanel;
+
+import java.awt.Dimension;
+import java.awt.Graphics;
import java.awt.image.BufferedImage;
-import java.io.*;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
}
- protected static void displayTestPanel(BufferedImage image) throws IOException {
+ protected static void displayTestPanel(BufferedImage image) {
ApplicationFrame frame = new ApplicationFrame("testframe");
BufferedPanel imgPanel = new BufferedPanel(image);
frame.setContentPane(imgPanel);
}
private static class BufferedPanel extends JPanel {
- private BufferedImage chartImage;
+ private final BufferedImage chartImage;
public BufferedPanel(BufferedImage chartImage) {
this.chartImage = chartImage;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Test;
-import java.text.ParseException;
import java.util.Date;
import static org.hamcrest.CoreMatchers.is;
public class DateCriterionTest {
@Test
- public void ignoreTime() throws ParseException {
+ public void ignoreTime() {
DateCriterion criterion = new DateCriterion().setDate(3);
Date date = criterion.getDate();
assertThat(date.getHours(), is(0));
}
@Test
- public void testDaysAgo() throws ParseException {
+ public void testDaysAgo() {
DateCriterion criterion = new DateCriterion().setDate(3);
Date date = criterion.getDate();
assertThat(date.getMinutes(), is(0));
private static File home = getHome();
@Test
- public void shouldLoadPropertiesFile() throws URISyntaxException {
+ public void shouldLoadPropertiesFile() {
ServerSettings settings = new ServerSettings(new PropertyDefinitions(), new BaseConfiguration(), new File("."), home);
assertThat(settings.getString("hello"), is("world"));
}
@Test
- public void systemPropertiesShouldOverridePropertiesFile() throws URISyntaxException {
+ public void systemPropertiesShouldOverridePropertiesFile() {
System.setProperty("ServerSettingsTestEnv", "in_env");
ServerSettings settings = new ServerSettings(new PropertyDefinitions(), new BaseConfiguration(), new File("."), home);
}
@Test
- public void shouldActivateDatabaseSettings() throws URISyntaxException {
+ public void shouldActivateDatabaseSettings() {
setupData("db/shared");
ServerSettings settings = new ServerSettings(new PropertyDefinitions(), new BaseConfiguration(), new File("."), home);
*/
package org.sonar.server.plugins;
-import org.apache.commons.io.FileUtils;
import org.hamcrest.core.Is;
import org.junit.After;
import org.junit.Test;
import org.sonar.api.SonarPlugin;
import org.sonar.api.platform.PluginMetadata;
import org.sonar.core.plugins.DefaultPluginMetadata;
+import org.sonar.test.TestUtils;
import java.io.File;
import java.util.Arrays;
@Test
public void testStart() {
PluginDeployer deployer = mock(PluginDeployer.class);
- File pluginFile = FileUtils.toFile(getClass().getResource("/org/sonar/server/plugins/DefaultServerPluginRepositoryTest/sonar-artifact-size-plugin-0.2.jar"));
+ File pluginFile = TestUtils.getResource("/org/sonar/server/plugins/DefaultServerPluginRepositoryTest/sonar-artifact-size-plugin-0.2.jar");
PluginMetadata plugin = DefaultPluginMetadata.create(pluginFile)
.setKey("artifactsize")
.setMainClass("org.sonar.plugins.artifactsize.ArtifactSizePlugin")
newMetadata("checkstyle", null),
newMetadata("checkstyle-extensions", "checkstyle"),
newMetadata("sqale", null)
- );
+ );
when(deployer.getMetadata()).thenReturn(metadata);
DefaultServerPluginRepository repository = new DefaultServerPluginRepository(deployer);
newMetadata("checkstyle", null),
newMetadata("checkstyle-extensions", "checkstyle"),
newMetadata("sqale", null)
- );
+ );
when(deployer.getMetadata()).thenReturn(metadata);
DefaultServerPluginRepository repository = new DefaultServerPluginRepository(deployer);
}
public static class FakePlugin extends SonarPlugin {
- private List<Class> extensions;
+ private final List<Class> extensions;
public FakePlugin(List<Class> extensions) {
this.extensions = extensions;
}
- public List getExtensions() {
+ public List<Class> getExtensions() {
return extensions;
}
}
import org.sonar.test.TestUtils;
import java.io.File;
-import java.io.IOException;
-import java.text.ParseException;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public TestName name = new TestName();
@Before
- public void start() throws ParseException {
+ public void start() {
homeDir = TestUtils.getResource(PluginDeployerTest.class, name.getMethodName());
deployDir = TestUtils.getTestTempDir(PluginDeployerTest.class, name.getMethodName() + "/deploy");
fileSystem = new DefaultServerFileSystem(null, homeDir, deployDir);
}
@Test
- public void deployPlugin() throws IOException {
+ public void deployPlugin() {
deployer.start();
// check that the plugin is registered
assertThat(plugin.getDeployedFiles().size(), is(1));
assertThat(plugin.isCore(), is(false));
assertThat(plugin.isUseChildFirstClassLoader(), is(false));
-
+
// check that the file is deployed
File deployedJar = new File(deployDir, "plugins/foo/foo-plugin.jar");
assertThat(deployedJar.exists(), is(true));
}
@Test
- public void deployDeprecatedPlugin() throws IOException, ClassNotFoundException {
+ public void deployDeprecatedPlugin() {
deployer.start();
// check that the plugin is registered
}
@Test
- public void deployPluginExtensions() throws IOException {
+ public void deployPluginExtensions() {
deployer.start();
- // check that the plugin is registered
+ // check that the plugin is registered
assertThat(deployer.getMetadata().size(), Is.is(1)); // no more checkstyle
PluginMetadata plugin = deployer.getMetadata("foo");
}
@Test
- public void ignoreJarsWhichAreNotPlugins() throws IOException {
+ public void ignoreJarsWhichAreNotPlugins() {
deployer.start();
assertThat(deployer.getMetadata().size(), Is.is(0));
}
@Test(expected = ServerStartException.class)
- public void failIfTwoPluginsWithSameKey() throws IOException {
+ public void failIfTwoPluginsWithSameKey() {
deployer.start();
}
@Test(expected = ServerStartException.class)
- public void failIfTwoDeprecatedPluginsWithSameKey() throws IOException {
+ public void failIfTwoDeprecatedPluginsWithSameKey() {
deployer.start();
}
this.extensions = extensions;
}
- public List getExtensions() {
+ public List<Class> getExtensions() {
return extensions;
}
}
import org.sonar.core.persistence.DatabaseVersion;
import org.sonar.jpa.test.AbstractDbUnitTestCase;
-import java.sql.SQLException;
import java.util.List;
import static org.hamcrest.Matchers.is;
public class DeleteDeprecatedMeasuresTest extends AbstractDbUnitTestCase {
@Test
- public void shouldDeleteMeasuresWithCategory() throws SQLException {
+ public void shouldDeleteMeasuresWithCategory() {
setupData("sharedFixture");
ServerUpgradeStatus upgradeStatus = mock(ServerUpgradeStatus.class);
}
@Test
- public void shouldDeleteMeasuresWithPriority() throws SQLException {
+ public void shouldDeleteMeasuresWithPriority() {
setupData("sharedFixture");
ServerUpgradeStatus upgradeStatus = mock(ServerUpgradeStatus.class);
*/
package org.sonar.server.startup;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
import org.junit.Test;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.jpa.dao.MeasuresDao;
import org.sonar.jpa.test.AbstractDbUnitTestCase;
-import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
public class RegisterMetricsTest extends AbstractDbUnitTestCase {
@Test
}
@Test
- public void enableOnlyLoadedMetrics() throws SQLException {
+ public void enableOnlyLoadedMetrics() {
setupData("enableOnlyLoadedMetrics");
RegisterMetrics loader = new RegisterMetrics(getSession(), new MeasuresDao(getSession()), null);
}
@Test
- public void cleanAlerts() throws SQLException {
+ public void cleanAlerts() {
setupData("cleanAlerts");
RegisterMetrics loader = new RegisterMetrics(getSession(), new MeasuresDao(getSession()), null);
@Test
public void read() throws IOException {
- String[] lines = { "import java.util.*;", "//NOSONAR comment", };
+ String[] lines = {"import java.util.*;", "//NOSONAR comment",};
StringArrayReader reader = new StringArrayReader(lines);
assertEquals('i', reader.read());
assertEquals('m', reader.read());
@Test
public void testLFEndOfLineDelimiter() throws IOException {
- String[] lines = { ";", ";", };
+ String[] lines = {";", ";",};
StringArrayReader reader = new StringArrayReader(lines, EndOfLineDelimiter.LF);
assertEquals(';', reader.read());
assertEquals('\n', reader.read());
@Test
public void testCREndOfLineDelimiter() throws IOException {
- String[] lines = { ";", ";", };
+ String[] lines = {";", ";",};
StringArrayReader reader = new StringArrayReader(lines, EndOfLineDelimiter.CR);
assertEquals(';', reader.read());
assertEquals('\r', reader.read());
@Test
public void testCRPlusLFEndOfLineDelimiter() throws IOException {
- String[] lines = { ";", ";", };
+ String[] lines = {";", ";",};
StringArrayReader reader = new StringArrayReader(lines, EndOfLineDelimiter.CR_PLUS_LF);
assertEquals(';', reader.read());
assertEquals('\r', reader.read());
@Test
public void ready() throws IOException {
- String[] lines = { ";", "//NOSONAR", };
+ String[] lines = {";", "//NOSONAR",};
StringArrayReader reader = new StringArrayReader(lines);
assertTrue(reader.ready());
}
@Test
- public void markSupported() throws IOException {
+ public void markSupported() {
String[] lines = {};
StringArrayReader reader = new StringArrayReader(lines);
assertTrue(reader.markSupported());
@Test
public void mark() throws IOException {
- String[] lines = { ";", "//NOSONAR", };
+ String[] lines = {";", "//NOSONAR",};
StringArrayReader reader = new StringArrayReader(lines);
reader.read(new char[4], 0, 4);
reader.mark(4);
@Test(expected = IOException.class)
public void close() throws IOException {
- String[] lines = { ";", "//NOSONAR", };
+ String[] lines = {";", "//NOSONAR",};
StringArrayReader reader = new StringArrayReader(lines);
assertTrue(reader.ready());
reader.close();
@Test
public void readEndOfArray() throws IOException {
- String[] lines = { ";" };
+ String[] lines = {";"};
StringArrayReader reader = new StringArrayReader(lines);
assertEquals(';', reader.read());
assertEquals(-1, reader.read());
@Test
public void readMultipleCharacters() throws IOException {
- String[] lines = { ";", "//NOSONAR", };
+ String[] lines = {";", "//NOSONAR",};
StringArrayReader reader = new StringArrayReader(lines);
char[] chars = new char[4];
assertEquals(4, reader.read(chars, 0, 4));
@Test
public void readMultipleCharactersTillEndOfArray() throws IOException {
- String[] lines = { ";", "//NOSONAR", };
+ String[] lines = {";", "//NOSONAR",};
StringArrayReader reader = new StringArrayReader(lines);
char[] chars = new char[11];
assertEquals(11, reader.read(chars, 0, 11));
@Test
public void readMultipleCharactersWithEmptyLineAtEnd() throws IOException {
- String[] lines = { ";", "//NOSONAR", "", "" };
+ String[] lines = {";", "//NOSONAR", "", ""};
StringArrayReader reader = new StringArrayReader(lines);
char[] cbuf = new char[10000];
assertEquals(13, reader.read(cbuf, 0, 10000));
@Test
public void readOneCharacter() throws IOException {
- String[] lines = { ";", "//NOSONAR" };
+ String[] lines = {";", "//NOSONAR"};
StringArrayReader reader = new StringArrayReader(lines);
char[] chars = new char[1];
assertEquals(1, reader.read(chars, 0, 1));
@Test
public void readBlankLines() throws IOException {
- String[] lines = { "", "", "" };
+ String[] lines = {"", "", ""};
StringArrayReader reader = new StringArrayReader(lines);
assertEquals('\n', reader.read());
assertEquals('\n', reader.read());
@Test
public void skip() throws IOException {
- String[] lines = { "//NOSONAR", };
+ String[] lines = {"//NOSONAR",};
StringArrayReader reader = new StringArrayReader(lines);
reader.skip(2);
assertEquals('N', reader.read());
StringArrayReader reader = new StringArrayReader(emptyLines);
assertEquals(-1, reader.read());
- String[] lines = { "a" };
+ String[] lines = {"a"};
reader = new StringArrayReader(lines);
assertEquals('a', reader.read());
assertEquals(-1, reader.read());
package org.sonar.wsclient.services;
import org.junit.Test;
-import org.sonar.wsclient.Sonar;
-
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
public class ManualMeasureUnmarshallerTest extends UnmarshallerTestCase {
package org.sonar.wsclient.unmarshallers;
import org.junit.Test;
-import org.sonar.wsclient.services.Server;
import org.sonar.wsclient.services.ServerSetup;
import static org.hamcrest.CoreMatchers.nullValue;