package org.sonar.batch;
import org.apache.commons.configuration.Configuration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.Plugins;
-import org.sonar.api.resources.Project;
-import org.sonar.api.utils.HttpDownloader;
-import org.sonar.api.utils.ServerHttpClient;
-import org.sonar.batch.bootstrap.BatchPluginRepository;
-import org.sonar.batch.bootstrap.BootstrapClassLoader;
-import org.sonar.batch.bootstrap.ExtensionDownloader;
-import org.sonar.batch.bootstrap.TempDirectories;
-import org.sonar.batch.components.*;
-import org.sonar.batch.index.*;
-import org.sonar.core.components.CacheMetricFinder;
-import org.sonar.core.components.CacheRuleFinder;
-import org.sonar.core.plugin.JpaPluginDao;
-import org.sonar.jpa.dao.MeasuresDao;
-import org.sonar.jpa.session.DatabaseSessionProvider;
-import org.sonar.jpa.session.DriverDatabaseConnector;
-import org.sonar.jpa.session.ThreadLocalDatabaseSessionFactory;
+import org.sonar.batch.bootstrap.BootstrapModule;
+import org.sonar.batch.bootstrap.Module;
-import java.net.URLClassLoader;
-import java.util.Arrays;
+public final class Batch {
-public class Batch {
+ private Module bootstrapModule;
- private static final Logger LOG = LoggerFactory.getLogger(Batch.class);
-
- private Configuration configuration;
- private Object[] components;
+ public Batch(Configuration configuration, Object... bootstrapperComponents) {
+ this.bootstrapModule = new BootstrapModule(configuration, bootstrapperComponents).init();
+ }
- public Batch(Configuration configuration, Object... components) {
- this.configuration = configuration;
- this.components = components;
+ /**
+ * for unit tests
+ */
+ Batch(Module bootstrapModule) {
+ this.bootstrapModule = bootstrapModule;
}
public void execute() {
- Module bootstrapComponents = null;
try {
- bootstrapComponents = new BootstrapComponents().init().start();
- analyzeModules(bootstrapComponents);
+ bootstrapModule.start();
} finally {
- if (bootstrapComponents != null) {
- try {
- bootstrapComponents.stop();
- } catch (Exception e) {
- // See http://jira.codehaus.org/browse/SONAR-2346
- // This exception must not override the exception thrown during start() phase.
- LOG.error("Fail to stop IoC container", e);
- }
- }
- }
- }
-
- private void analyzeModules(Module bootstrapComponents) {
- Module batchComponents = bootstrapComponents.installChild(new BatchComponents());
- batchComponents.start();
-
- ProjectTree projectTree = batchComponents.getComponent(ProjectTree.class);
- DefaultIndex index = batchComponents.getComponent(DefaultIndex.class);
- analyzeModule(batchComponents, index, projectTree.getRootProject());
-
- // batchContainer is stopped by its parent
- }
-
- private static class BatchComponents extends Module {
- @Override
- protected void configure() {
- addComponent(ProjectTree.class);
- addComponent(DefaultResourceCreationLock.class);
- addComponent(DefaultIndex.class);
- addComponent(DefaultPersistenceManager.class);
- addComponent(DependencyPersister.class);
- addComponent(EventPersister.class);
- addComponent(LinkPersister.class);
- addComponent(MeasurePersister.class);
- addComponent(MemoryOptimizer.class);
- addComponent(DefaultResourcePersister.class);
- addComponent(SourcePersister.class);
- addComponent(ViolationPersister.class);
- addComponent(JpaPluginDao.class);
- addComponent(BatchPluginRepository.class);
- addComponent(Plugins.class);
- addComponent(ServerHttpClient.class);
- addComponent(MeasuresDao.class);
- addComponent(CacheRuleFinder.class);
- addComponent(CacheMetricFinder.class);
- addComponent(PastSnapshotFinderByDate.class);
- addComponent(PastSnapshotFinderByDays.class);
- addComponent(PastSnapshotFinderByPreviousAnalysis.class);
- addComponent(PastSnapshotFinderByVersion.class);
- addComponent(PastMeasuresLoader.class);
- addComponent(PastSnapshotFinder.class);
+ bootstrapModule.stop();
}
}
-
- private class BootstrapComponents extends Module {
- @Override
- protected void configure() {
- addComponent(configuration);
- addComponent(ServerMetadata.class);// registered here because used by BootstrapClassLoader
- addComponent(TempDirectories.class);// registered here because used by BootstrapClassLoader
- addComponent(HttpDownloader.class);// registered here because used by BootstrapClassLoader
- addComponent(ExtensionDownloader.class);// registered here because used by BootstrapClassLoader
- addComponent(BootstrapClassLoader.class);
-
- URLClassLoader bootstrapClassLoader = getComponent(BootstrapClassLoader.class).getClassLoader();
- // set as the current context classloader for hibernate, else it does not find the JDBC driver.
- Thread.currentThread().setContextClassLoader(bootstrapClassLoader);
-
- addComponent(new DriverDatabaseConnector(configuration, bootstrapClassLoader));
- addComponent(ThreadLocalDatabaseSessionFactory.class);
- addAdapter(new DatabaseSessionProvider());
- for (Object component : components) {
- addComponent(component);
- }
- if (!isMavenPluginExecutorRegistered()) {
- addComponent(FakeMavenPluginExecutor.class);
- }
- }
- }
-
- boolean isMavenPluginExecutorRegistered() {
- for (Object component : components) {
- if (component instanceof Class && MavenPluginExecutor.class.isAssignableFrom((Class<?>) component)) {
- return true;
- }
- }
- return false;
- }
-
- private void analyzeModule(Module batchComponents, DefaultIndex index, Project project) {
- for (Project module : project.getModules()) {
- analyzeModule(batchComponents, index, module);
- }
- LOG.info("------------- Analyzing {}", project.getName());
-
- String[] exclusionPatterns = project.getExclusionPatterns();
- if (exclusionPatterns != null && exclusionPatterns.length > 0) {
- LOG.info("Excluded sources : {}", Arrays.toString(exclusionPatterns));
- }
-
- new ProjectBatch(batchComponents).execute(index, project);
- }
}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.batch;
-
-import java.util.List;
-
-import org.picocontainer.Characteristics;
-import org.picocontainer.ComponentAdapter;
-import org.picocontainer.MutablePicoContainer;
-import org.sonar.api.utils.IocContainer;
-
-/**
- * Module describes group of components - {@link #configure()}.
- * Several modules can be grouped together - {@link #install(Module)}, {@link #installChild(Module)}.
- */
-public abstract class Module {
-
- private MutablePicoContainer container;
-
- /**
- * @return this
- */
- public final Module init() {
- this.container = IocContainer.buildPicoContainer();
- configure();
- return this;
- }
-
- /**
- * @return this
- */
- private Module init(MutablePicoContainer container) {
- this.container = container;
- configure();
- return this;
- }
-
- /**
- * Installs module into this module.
- *
- * @return this
- */
- public final Module install(Module module) {
- module.init(container);
- return this;
- }
-
- /**
- * Installs module into new scope - see http://picocontainer.org/scopes.html
- *
- * @return installed module
- */
- public final Module installChild(Module module) {
- MutablePicoContainer child = container.makeChildContainer();
- // register container as a component, because it used for example in BatchExtensionDictionnary,
- // but in fact this is anti-pattern - http://picocontainer.codehaus.org/container-dependency-antipattern.html
- child.addComponent(new IocContainer(child));
- child.setName(module.toString());
- module.init(child);
- return module;
- }
-
- public final void uninstallChild(Module module) {
- container.removeChildContainer(module.container);
- }
-
- /**
- * @return this
- */
- public Module start() {
- container.start();
- return this;
- }
-
- /**
- * @return this
- */
- public Module stop() {
- container.stop();
- return this;
- }
-
- /**
- * Implementation of this method must not contain conditional logic and just should contain several invocations of
- * {@link #addComponent(Object)}, {@link #addComponent(Object, Object)} or {@link #addAdapter(ComponentAdapter)}.
- */
- protected abstract void configure();
-
- protected final void addComponent(Object component) {
- container.as(Characteristics.CACHE).addComponent(component);
- }
-
- protected final void addComponent(Object componentKey, Object component) {
- container.as(Characteristics.CACHE).addComponent(componentKey, component);
- }
-
- protected final void addAdapter(ComponentAdapter<?> componentAdapter) {
- container.addAdapter(componentAdapter);
- }
-
- public final <T> T getComponent(Class<T> componentType) {
- return container.getComponent(componentType);
- }
-
- public final <T> List<T> getComponents(Class<T> componentType) {
- return container.getComponents(componentType);
- }
-
- /**
- * @TODO should not be used and should be removed
- */
- public final MutablePicoContainer getContainer() {
- return container;
- }
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.batch;
-
-import org.apache.maven.project.MavenProject;
-import org.sonar.api.batch.BatchExtensionDictionnary;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.Metrics;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.resources.Language;
-import org.sonar.api.resources.Languages;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.ProjectFileSystem;
-import org.sonar.api.rules.DefaultRulesManager;
-import org.sonar.api.utils.SonarException;
-import org.sonar.batch.bootstrap.BatchPluginRepository;
-import org.sonar.batch.bootstrapper.ProjectDefinition;
-import org.sonar.batch.components.PastViolationsLoader;
-import org.sonar.batch.components.TimeMachineConfiguration;
-import org.sonar.batch.events.EventBus;
-import org.sonar.batch.index.DefaultIndex;
-import org.sonar.batch.index.DefaultResourcePersister;
-import org.sonar.batch.phases.Phases;
-import org.sonar.batch.phases.PhasesTimeProfiler;
-import org.sonar.core.components.DefaultModelFinder;
-import org.sonar.jpa.dao.*;
-
-public class ProjectBatch {
-
- private Module globalComponents;
-
- public ProjectBatch(Module globalComponents) {
- this.globalComponents = globalComponents;
- }
-
- public void execute(DefaultIndex index, Project project) {
- Module projectComponents = null;
- try {
- projectComponents = startChildContainer(index, project);
-
- projectComponents.getComponent(Phases.class).execute(project);
-
- } finally {
- if (projectComponents != null) {
- try {
- globalComponents.uninstallChild(projectComponents);
- projectComponents.stop();
- } catch (Exception e) {
- // do not log
- }
- }
- }
- }
-
- public Module startChildContainer(DefaultIndex index, Project project) {
- Module projectComponents = globalComponents.installChild(new ProjectComponents(project));
- projectComponents.install(new ProjectCoreComponents());
- projectComponents.start();
-
- // post-initializations
-
- Language language = projectComponents.getComponent(Languages.class).get(project.getLanguageKey());
- if (language == null) {
- throw new SonarException("Language with key '" + project.getLanguageKey() + "' not found");
- }
- project.setLanguage(language);
-
- index.setCurrentProject(project,
- projectComponents.getComponent(ResourceFilters.class),
- projectComponents.getComponent(ViolationFilters.class),
- projectComponents.getComponent(RulesProfile.class));
-
- // TODO See http://jira.codehaus.org/browse/SONAR-2126
- // previously MavenProjectBuilder was responsible for creation of ProjectFileSystem
- project.setFileSystem(projectComponents.getComponent(ProjectFileSystem.class));
-
- return projectComponents;
- }
-
- private static class ProjectComponents extends Module {
- private Project project;
-
- public ProjectComponents(Project project) {
- this.project = project;
- }
-
- @Override
- protected void configure() {
- ProjectDefinition projectDefinition = getComponent(ProjectTree.class).getProjectDefinition(project);
- addComponent(projectDefinition);
- for (Object component : projectDefinition.getContainerExtensions()) {
- addComponent(component);
- if (component instanceof MavenProject) {
- // For backward compatibility we must set POM and actual packaging
- MavenProject pom = (MavenProject) component;
- project.setPom(pom);
- project.setPackaging(pom.getPackaging());
- }
- }
-
- addComponent(project);
- addComponent(DefaultProjectClasspath.class);
- addComponent(DefaultProjectFileSystem2.class);
- addComponent(project.getConfiguration());
-
- // need to be registered after the Configuration
- getComponent(BatchPluginRepository.class).registerPlugins(getContainer());
-
- addComponent(DaoFacade.class);
- addComponent(RulesDao.class);
-
- // the Snapshot component will be removed when asynchronous measures are improved (required for AsynchronousMeasureSensor)
- addComponent(getComponent(DefaultResourcePersister.class).getSnapshot(project));
-
- addComponent(org.sonar.api.database.daos.MeasuresDao.class);
- addComponent(ProfilesDao.class);
- addComponent(AsyncMeasuresDao.class);
- addComponent(AsyncMeasuresService.class);
- addComponent(DefaultRulesManager.class);
- addComponent(DefaultSensorContext.class);
- addComponent(Languages.class);
- addComponent(BatchExtensionDictionnary.class);
- addComponent(DefaultTimeMachine.class);
- addComponent(ViolationFilters.class);
- addComponent(ResourceFilters.class);
- addComponent(DefaultModelFinder.class);
- addComponent(TimeMachineConfiguration.class);
- addComponent(PastViolationsLoader.class);
- addComponent(ProfileLoader.class, DefaultProfileLoader.class);
-
- addAdapter(new ProfileProvider());
- addAdapter(new CheckProfileProvider());
- }
- }
-
- private static class ProjectCoreComponents extends Module {
- @Override
- protected void configure() {
- addComponent(EventBus.class);
- addComponent(Phases.class);
- addComponent(PhasesTimeProfiler.class);
- for (Class clazz : Phases.getPhaseClasses()) {
- addComponent(clazz);
- }
- for (Metric metric : CoreMetrics.getMetrics()) {
- addComponent(metric.getKey(), metric);
- }
- for (Metrics metricRepo : getComponents(Metrics.class)) {
- for (Metric metric : metricRepo.getMetrics()) {
- addComponent(metric.getKey(), metric);
- }
- }
- }
- }
-
-}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.sonar.api.BatchComponent;
+import org.sonar.api.ExtensionProvider;
+import org.sonar.api.Plugin;
+import org.sonar.api.batch.CoverageExtension;
+import org.sonar.api.batch.InstanciationStrategy;
+import org.sonar.batch.bootstrapper.EnvironmentInformation;
+
+import java.util.List;
+
+public final class BatchExtensionInstaller implements BatchComponent {
+
+ private BatchPluginRepository pluginRepository;
+ private EnvironmentInformation environment;
+
+ public BatchExtensionInstaller(BatchPluginRepository pluginRepository, EnvironmentInformation environment) {
+ this.pluginRepository = pluginRepository;
+ this.environment = environment;
+ }
+
+ public void install(Module module) {
+ for (Plugin plugin : pluginRepository.getPlugins()) {
+ for (Object extension : plugin.getExtensions()) {
+ installExtension(module, extension);
+ }
+ }
+ installExtensionProviders(module);
+ }
+
+ void installExtensionProviders(Module module) {
+ List<ExtensionProvider> providers = module.getComponents(ExtensionProvider.class);
+ for (ExtensionProvider provider : providers) {
+ Object obj = provider.provide();
+ if (obj instanceof Iterable) {
+ for (Object extension : (Iterable) obj) {
+ installExtension(module, extension);
+ }
+ } else {
+ installExtension(module, obj);
+ }
+ }
+ }
+
+ void installExtension(Module module, Object extension) {
+ if (ExtensionUtils.isBatchExtension(extension) &&
+ ExtensionUtils.isSupportedEnvironment(extension, environment) &&
+ ExtensionUtils.isInstantiationStrategy(extension, InstanciationStrategy.PER_BATCH)) {
+ if (ExtensionUtils.isType(extension, CoverageExtension.class)) {
+ throw new IllegalArgumentException("Instantiation strategy " + InstanciationStrategy.PER_BATCH + " is not supported on CoverageExtension components: " + extension);
+ }
+ module.addComponent(extension);
+ }
+ }
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.sonar.api.Plugins;
+import org.sonar.api.resources.Project;
+import org.sonar.api.utils.ServerHttpClient;
+import org.sonar.batch.DefaultResourceCreationLock;
+import org.sonar.batch.ProjectTree;
+import org.sonar.batch.components.*;
+import org.sonar.batch.index.*;
+import org.sonar.core.components.CacheMetricFinder;
+import org.sonar.core.components.CacheRuleFinder;
+import org.sonar.jpa.dao.MeasuresDao;
+
+/**
+ * Level-2 components. Connected to database.
+ */
+public class BatchModule extends Module {
+ @Override
+ protected void configure() {
+ addComponent(ProjectTree.class);
+ addComponent(DefaultResourceCreationLock.class);
+ addComponent(DefaultIndex.class);
+ addComponent(DefaultPersistenceManager.class);
+ addComponent(DependencyPersister.class);
+ addComponent(EventPersister.class);
+ addComponent(LinkPersister.class);
+ addComponent(MeasurePersister.class);
+ addComponent(MemoryOptimizer.class);
+ addComponent(DefaultResourcePersister.class);
+ addComponent(SourcePersister.class);
+ addComponent(ViolationPersister.class);
+ addComponent(Plugins.class);
+ addComponent(ServerHttpClient.class);
+ addComponent(MeasuresDao.class);
+ addComponent(CacheRuleFinder.class);
+ addComponent(CacheMetricFinder.class);
+ addComponent(PastSnapshotFinderByDate.class);
+ addComponent(PastSnapshotFinderByDays.class);
+ addComponent(PastSnapshotFinderByPreviousAnalysis.class);
+ addComponent(PastSnapshotFinderByVersion.class);
+ addComponent(PastMeasuresLoader.class);
+ addComponent(PastSnapshotFinder.class);
+ addBatchExtensions();
+ }
+
+ private void addBatchExtensions() {
+ BatchExtensionInstaller installer = getComponent(BatchExtensionInstaller.class);
+ installer.install(this);
+ }
+
+ @Override
+ protected void doStart() {
+ ProjectTree projectTree = getComponent(ProjectTree.class);
+ analyze(projectTree.getRootProject());
+ }
+
+ private void analyze(Project project) {
+ for (Project subProject : project.getModules()) {
+ analyze(subProject);
+ }
+
+ Module projectComponents = installChild(new ProjectModule(project));
+ try {
+ projectComponents.start();
+ } finally {
+ projectComponents.stop();
+ uninstallChild(projectComponents);
+ }
+ }
+}
*/
package org.sonar.batch.bootstrap;
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.List;
-
import com.google.common.collect.Lists;
-import org.apache.commons.configuration.Configuration;
-import org.apache.commons.lang.ArrayUtils;
+import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
-import org.picocontainer.MutablePicoContainer;
-import org.picocontainer.PicoContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.sonar.api.BatchExtension;
import org.sonar.api.Plugin;
-import org.sonar.api.batch.AbstractCoverageExtension;
-import org.sonar.api.batch.CoverageExtension;
-import org.sonar.api.batch.SupportedEnvironment;
-import org.sonar.api.resources.Java;
-import org.sonar.api.resources.Project;
-import org.sonar.api.utils.AnnotationUtils;
+import org.sonar.api.Properties;
+import org.sonar.api.Property;
+import org.sonar.api.platform.PluginRepository;
import org.sonar.api.utils.SonarException;
-import org.sonar.batch.bootstrapper.EnvironmentInformation;
import org.sonar.core.classloaders.ClassLoadersCollection;
-import org.sonar.core.plugin.AbstractPluginRepository;
import org.sonar.core.plugin.JpaPlugin;
import org.sonar.core.plugin.JpaPluginDao;
import org.sonar.core.plugin.JpaPluginFile;
-public class BatchPluginRepository extends AbstractPluginRepository {
+import java.io.File;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class BatchPluginRepository implements PluginRepository {
private static final Logger LOG = LoggerFactory.getLogger(BatchPluginRepository.class);
private JpaPluginDao dao;
+ private ExtensionDownloader artifactDownloader;
+ private Map<String, Plugin> pluginsByKey;
- private ClassLoadersCollection classLoaders;
- private ExtensionDownloader extensionDownloader;
- private EnvironmentInformation environment;
- private List<JpaPlugin> register;
-
- public BatchPluginRepository(JpaPluginDao dao, ExtensionDownloader extensionDownloader, EnvironmentInformation environment) {
+ public BatchPluginRepository(JpaPluginDao dao, ExtensionDownloader artifactDownloader) {
this.dao = dao;
- this.extensionDownloader = extensionDownloader;
- this.environment = environment;
- LOG.info("Execution environment: {} {}", environment.getKey(), environment.getVersion());
- }
-
- /**
- * for unit tests only
- */
- BatchPluginRepository() {
- }
-
- private List<URL> download(JpaPlugin pluginMetadata) {
- List<URL> urls = Lists.newArrayList();
- for (JpaPluginFile pluginFile : pluginMetadata.getFiles()) {
- File file = extensionDownloader.downloadExtension(pluginFile);
- try {
- urls.add(file.toURI().toURL());
-
- } catch (MalformedURLException e) {
- throw new SonarException("Can not get the URL of: " + file, e);
- }
- }
- return urls;
+ this.artifactDownloader = artifactDownloader;
+// TODO reactivate somewhere else: LOG.info("Execution environment: {} {}", environment.getKey(), environment.getVersion());
}
public void start() {
- register = Lists.newArrayList();
- classLoaders = new ClassLoadersCollection(Thread.currentThread().getContextClassLoader());
+ List<JpaPlugin> pluginsMetadata = Lists.newArrayList();
+ pluginsByKey = Maps.newHashMap();
+ ClassLoadersCollection classLoaders = new ClassLoadersCollection(Thread.currentThread().getContextClassLoader());
List<JpaPlugin> jpaPlugins = dao.getPlugins();
String key = pluginMetadata.getKey();
List<URL> urls = download(pluginMetadata);
classLoaders.createClassLoader(key, urls, pluginMetadata.isUseChildFirstClassLoader() == Boolean.TRUE);
- register.add(pluginMetadata);
+ pluginsMetadata.add(pluginMetadata);
}
}
LOG.debug("Plugin {} extends {}", pluginKey, basePluginKey);
List<URL> urls = download(pluginMetadata);
classLoaders.extend(basePluginKey, pluginKey, urls);
- register.add(pluginMetadata);
+ pluginsMetadata.add(pluginMetadata);
+
} else {
// Ignored, because base plugin doesn't exists
LOG.warn("Plugin {} extends nonexistent plugin {}", pluginKey, basePluginKey);
}
}
- classLoaders.done();
- }
-
- public void registerPlugins(MutablePicoContainer pico) {
- for (JpaPlugin pluginMetadata : register) {
+ for (JpaPlugin pluginMetadata : jpaPlugins) {
try {
Class claz = classLoaders.get(pluginMetadata.getKey()).loadClass(pluginMetadata.getPluginClass());
Plugin plugin = (Plugin) claz.newInstance();
- registerPlugin(pico, plugin, pluginMetadata.getKey());
+ pluginsByKey.put(pluginMetadata.getKey(), plugin);
} catch (Exception e) {
- throw new SonarException("Fail to load extensions from plugin " + pluginMetadata.getKey(), e);
+ throw new SonarException("Fail to load plugin " + pluginMetadata.getKey(), e);
}
}
- invokeExtensionProviders(pico);
+
+ classLoaders.done();
}
- @Override
- protected boolean shouldRegisterExtension(PicoContainer container, String pluginKey, Object extension) {
- boolean ok = isType(extension, BatchExtension.class);
- if (ok && !isSupportsEnvironment(extension)) {
- ok = false;
- LOG.debug("The following extension is ignored: " + extension + " due to execution environment.");
- }
- if (ok && isType(extension, CoverageExtension.class)) {
- ok = shouldRegisterCoverageExtension(pluginKey, container.getComponent(Project.class), container.getComponent(Configuration.class));
- if (!ok) {
- LOG.debug("The following extension is ignored: " + extension + ". See the parameter " + AbstractCoverageExtension.PARAM_PLUGIN);
+ private List<URL> download(JpaPlugin pluginMetadata) {
+ List<URL> urls = Lists.newArrayList();
+ for (JpaPluginFile pluginFile : pluginMetadata.getFiles()) {
+ File file = artifactDownloader.downloadExtension(pluginFile);
+ try {
+ urls.add(file.toURI().toURL());
+
+ } catch (MalformedURLException e) {
+ throw new SonarException("Can not get the URL of: " + file, e);
}
}
- return ok;
+ return urls;
}
- private boolean isSupportsEnvironment(Object extension) {
- Class clazz = (extension instanceof Class ? (Class) extension : extension.getClass());
- SupportedEnvironment env = AnnotationUtils.getClassAnnotation(clazz, SupportedEnvironment.class);
- if (env == null) {
- return true;
- }
- for (String supported : env.value()) {
- if (StringUtils.equalsIgnoreCase(environment.getKey(), supported)) {
- return true;
- }
- }
- return false;
+ public Collection<Plugin> getPlugins() {
+ return pluginsByKey.values();
}
- boolean shouldRegisterCoverageExtension(String pluginKey, Project project, Configuration conf) {
- if (!project.getAnalysisType().isDynamic(true)) {
- // not dynamic and not reuse reports
- return false;
- }
- if (StringUtils.equals(project.getLanguageKey(), Java.KEY)) {
- String[] selectedPluginKeys = conf.getStringArray(AbstractCoverageExtension.PARAM_PLUGIN);
- if (ArrayUtils.isEmpty(selectedPluginKeys)) {
- selectedPluginKeys = new String[] { AbstractCoverageExtension.DEFAULT_PLUGIN };
+ public Plugin getPlugin(String key) {
+ return pluginsByKey.get(key);
+ }
+
+ public Map<String, Plugin> getPluginsByKey() {
+ return Collections.unmodifiableMap(pluginsByKey);
+ }
+
+ // TODO remove this method. Not used in batch.
+ public Property[] getProperties(Plugin plugin) {
+ if (plugin != null) {
+ Class<? extends Plugin> classInstance = plugin.getClass();
+ if (classInstance.isAnnotationPresent(Properties.class)) {
+ return classInstance.getAnnotation(Properties.class).value();
}
- return ArrayUtils.contains(selectedPluginKeys, pluginKey);
}
- return true;
+ return new Property[0];
}
}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.apache.commons.configuration.Configuration;
+import org.sonar.api.Plugin;
+import org.sonar.api.utils.HttpDownloader;
+import org.sonar.batch.FakeMavenPluginExecutor;
+import org.sonar.batch.MavenPluginExecutor;
+import org.sonar.batch.ServerMetadata;
+import org.sonar.core.plugin.JpaPluginDao;
+import org.sonar.jpa.session.DatabaseSessionProvider;
+import org.sonar.jpa.session.DriverDatabaseConnector;
+import org.sonar.jpa.session.ThreadLocalDatabaseSessionFactory;
+
+import java.net.URLClassLoader;
+
+/**
+ * Level 1 components
+ */
+public class BootstrapModule extends Module {
+
+ private Configuration configuration;
+ private Object[] boostrapperComponents;
+
+ public BootstrapModule(Configuration configuration, Object... boostrapperComponents) {
+ this.configuration = configuration;
+ this.boostrapperComponents = boostrapperComponents;
+ }
+
+ @Override
+ protected void configure() {
+ addComponent(configuration);
+ addComponent(ServerMetadata.class);// registered here because used by BootstrapClassLoader
+ addComponent(TempDirectories.class);// registered here because used by BootstrapClassLoader
+ addComponent(HttpDownloader.class);// registered here because used by BootstrapClassLoader
+ addComponent(ExtensionDownloader.class);// registered here because used by BootstrapClassLoader
+ addComponent(BootstrapClassLoader.class);
+
+ URLClassLoader bootstrapClassLoader = getComponent(BootstrapClassLoader.class).getClassLoader();
+ // set as the current context classloader for hibernate, else it does not find the JDBC driver.
+ Thread.currentThread().setContextClassLoader(bootstrapClassLoader);
+
+ addComponent(new DriverDatabaseConnector(configuration, bootstrapClassLoader));
+ addComponent(ThreadLocalDatabaseSessionFactory.class);
+ addAdapter(new DatabaseSessionProvider());
+ for (Object component : boostrapperComponents) {
+ addComponent(component);
+ }
+ if (!isMavenPluginExecutorRegistered()) {
+ addComponent(FakeMavenPluginExecutor.class);
+ }
+
+ // LIMITATION : list of plugins to download is currently loaded from database. It should be loaded from
+ // remote HTTP index.
+ addComponent(JpaPluginDao.class);
+ addComponent(BatchPluginRepository.class);
+ addComponent(BatchExtensionInstaller.class);
+ addComponent(ProjectExtensionInstaller.class);
+ }
+
+ boolean isMavenPluginExecutorRegistered() {
+ for (Object component : boostrapperComponents) {
+ if (component instanceof Class && MavenPluginExecutor.class.isAssignableFrom((Class<?>) component)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ protected void doStart() {
+ addPlugins();
+ Module batchComponents = installChild(new BatchModule());
+ batchComponents.start();
+ }
+
+ private void addPlugins() {
+ // Plugins have been loaded during the startup of BatchPluginRepository.
+ // In a perfect world BatchPluginRepository should be a factory which injects new components into container, but
+ // (it seems that) this feature does not exist in PicoContainer.
+ // Limitation: the methods start() and stop() are not called on org.sonar.api.Plugin instances.
+ for (Plugin plugin : getComponent(BatchPluginRepository.class).getPlugins()) {
+ addComponent(plugin);
+ }
+ }
+}
*/
package org.sonar.batch.bootstrap;
+import org.sonar.api.BatchComponent;
import org.sonar.api.utils.HttpDownloader;
import org.sonar.api.utils.SonarException;
import org.sonar.batch.ServerMetadata;
import java.net.URI;
import java.net.URISyntaxException;
-public final class ExtensionDownloader {
+/**
+ * TODO this class should be renamed ArtifactDownloader, because it does not relate only to plugin extensions.
+ */
+public final class ExtensionDownloader implements BatchComponent {
private HttpDownloader httpDownloader;
private TempDirectories workingDirectories;
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.apache.commons.lang.StringUtils;
+import org.sonar.api.BatchExtension;
+import org.sonar.api.Extension;
+import org.sonar.api.batch.InstanciationStrategy;
+import org.sonar.api.batch.SupportedEnvironment;
+import org.sonar.api.utils.AnnotationUtils;
+import org.sonar.batch.bootstrapper.EnvironmentInformation;
+
+public final class ExtensionUtils {
+
+ private ExtensionUtils() {
+ // only static methods
+ }
+
+ static boolean isInstantiationStrategy(Object extension, String strategy) {
+ Class clazz = (extension instanceof Class ? (Class) extension : extension.getClass());
+ InstanciationStrategy extStrategy = AnnotationUtils.getClassAnnotation(clazz, InstanciationStrategy.class);
+ if (extStrategy != null) {
+ return strategy.equals(extStrategy.value());
+ }
+ return InstanciationStrategy.PER_PROJECT.equals(strategy);
+ }
+
+ static boolean isBatchExtension(Object extension) {
+ return isType(extension, BatchExtension.class);
+ }
+
+ static boolean isSupportedEnvironment(Object extension, EnvironmentInformation environment) {
+ Class clazz = (extension instanceof Class ? (Class) extension : extension.getClass());
+ SupportedEnvironment env = AnnotationUtils.getClassAnnotation(clazz, SupportedEnvironment.class);
+ if (env == null) {
+ return true;
+ }
+ for (String supported : env.value()) {
+ if (StringUtils.equalsIgnoreCase(environment.getKey(), supported)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ static boolean isType(Object extension, Class<? extends Extension> extensionClass) {
+ Class clazz = (extension instanceof Class ? (Class) extension : extension.getClass());
+ return extensionClass.isAssignableFrom(clazz);
+ }
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.picocontainer.Characteristics;
+import org.picocontainer.ComponentAdapter;
+import org.picocontainer.MutablePicoContainer;
+import org.sonar.api.utils.IocContainer;
+
+import java.util.List;
+
+/**
+ * Module describes group of components - {@link #configure()}.
+ * Several modules can be grouped together - {@link #install(Module)}, {@link #installChild(Module)}.
+ * <p/>
+ * TODO Move to org.sonar.batch.bootstrap ?
+ */
+public abstract class Module {
+
+ private MutablePicoContainer container;
+
+ /**
+ * @return this
+ */
+ public final Module init() {
+ return init(IocContainer.buildPicoContainer());
+ }
+
+ /**
+ * @return this
+ */
+ private Module init(MutablePicoContainer container) {
+ this.container = container;
+ configure();
+ return this;
+ }
+
+ /**
+ * Installs module into this module.
+ *
+ * @return this
+ */
+ public final Module install(Module module) {
+ module.init(container);
+ return this;
+ }
+
+ /**
+ * Installs module into new scope - see http://picocontainer.org/scopes.html
+ *
+ * @return installed module
+ */
+ public final Module installChild(Module child) {
+ MutablePicoContainer childContainer = container.makeChildContainer();
+ // register container as a component, because it used for example in BatchExtensionDictionnary,
+ // but in fact this is anti-pattern - http://picocontainer.codehaus.org/container-dependency-antipattern.html
+ childContainer.addComponent(new IocContainer(childContainer));
+ childContainer.setName(child.toString());
+ child.init(childContainer);
+ return child;
+ }
+
+ public final void uninstallChild(Module child) {
+ container.removeChildContainer(child.container);
+ }
+
+ /**
+ * @return this
+ */
+ public final Module start() {
+ container.start();
+ doStart();
+ return this;
+ }
+
+ protected void doStart() {
+ // empty method to be overridden
+ }
+
+ /**
+ * @return this
+ */
+ public final Module stop() {
+ try {
+ doStop();
+ container.stop();
+ } catch (Exception e) {
+ // ignore
+ }
+ return this;
+ }
+
+ protected void doStop() {
+ // empty method to be overridden
+ }
+
+ /**
+ * Implementation of this method must not contain conditional logic and just should contain several invocations of
+ * {@link #addComponent(Object)}, {@link #addComponent(Object, Object)} or {@link #addAdapter(ComponentAdapter)}.
+ */
+ protected abstract void configure();
+
+ protected final void addComponent(Object component) {
+ if (component instanceof Class) {
+ container.as(Characteristics.CACHE).addComponent(component);
+ } else {
+ container.as(Characteristics.CACHE).addComponent(component.getClass().getCanonicalName() + "-" + component.toString(), component);
+ }
+ }
+
+ protected final void addComponent(Object componentKey, Object component) {
+ container.as(Characteristics.CACHE).addComponent(componentKey, component);
+ }
+
+ protected final void addAdapter(ComponentAdapter<?> componentAdapter) {
+ container.addAdapter(componentAdapter);
+ }
+
+ public final <T> T getComponent(Class<T> componentType) {
+ return container.getComponent(componentType);
+ }
+
+ public final <T> List<T> getComponents(Class<T> componentType) {
+ return container.getComponents(componentType);
+ }
+
+ /**
+ * TODO should not be used and should be removed
+ */
+ public final MutablePicoContainer getContainer() {
+ return container;
+ }
+
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang.StringUtils;
+import org.sonar.api.BatchComponent;
+import org.sonar.api.ExtensionProvider;
+import org.sonar.api.Plugin;
+import org.sonar.api.batch.AbstractCoverageExtension;
+import org.sonar.api.batch.CoverageExtension;
+import org.sonar.api.batch.InstanciationStrategy;
+import org.sonar.api.resources.Java;
+import org.sonar.api.resources.Project;
+import org.sonar.batch.bootstrapper.EnvironmentInformation;
+
+import java.util.List;
+import java.util.Map;
+
+public final class ProjectExtensionInstaller implements BatchComponent {
+
+ private BatchPluginRepository pluginRepository;
+ private EnvironmentInformation environment;
+
+ public ProjectExtensionInstaller(BatchPluginRepository pluginRepository, EnvironmentInformation environment) {
+ this.pluginRepository = pluginRepository;
+ this.environment = environment;
+ }
+
+ public void install(Module module, Project project) {
+ for (Map.Entry<String, Plugin> entry : pluginRepository.getPluginsByKey().entrySet()) {
+ for (Object extension : entry.getValue().getExtensions()) {
+ installExtension(module, extension, project, entry.getKey());
+ }
+ }
+
+ installExtensionProviders(module, project);
+ }
+
+ void installExtensionProviders(Module module, Project project) {
+ List<ExtensionProvider> providers = module.getComponents(ExtensionProvider.class);
+ for (ExtensionProvider provider : providers) {
+ Object obj = provider.provide();
+ if (obj instanceof Iterable) {
+ for (Object extension : (Iterable) obj) {
+ installExtension(module, extension, project, "");
+ }
+ } else {
+ installExtension(module, obj, project, "");
+ }
+ }
+ }
+
+ private Object installExtension(Module module, Object extension, Project project, String pluginKey) {
+ if (ExtensionUtils.isBatchExtension(extension) &&
+ ExtensionUtils.isSupportedEnvironment(extension, environment) &&
+ ExtensionUtils.isInstantiationStrategy(extension, InstanciationStrategy.PER_PROJECT) &&
+ !isDeactivatedCoverageExtension(extension, project, pluginKey)) {
+
+ module.addComponent(extension);
+ return extension;
+ }
+ return null;
+ }
+
+ /**
+ * TODO this code is specific to Java projects and should be moved somewhere else
+ */
+ boolean isDeactivatedCoverageExtension(Object extension, Project project, String pluginKey) {
+ if (!ExtensionUtils.isType(extension, CoverageExtension.class)) {
+ return false;
+ }
+
+ if (!project.getAnalysisType().isDynamic(true)) {
+ // not dynamic and not reuse reports
+ return true;
+ }
+
+ if (StringUtils.equals(project.getLanguageKey(), Java.KEY)) {
+ String[] selectedPluginKeys = project.getConfiguration().getStringArray(AbstractCoverageExtension.PARAM_PLUGIN);
+ if (ArrayUtils.isEmpty(selectedPluginKeys)) {
+ selectedPluginKeys = new String[]{AbstractCoverageExtension.DEFAULT_PLUGIN};
+ }
+ return !ArrayUtils.contains(selectedPluginKeys, pluginKey);
+ }
+ return false;
+ }
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.apache.maven.project.MavenProject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.sonar.api.batch.BatchExtensionDictionnary;
+import org.sonar.api.measures.CoreMetrics;
+import org.sonar.api.measures.Metric;
+import org.sonar.api.measures.Metrics;
+import org.sonar.api.profiles.RulesProfile;
+import org.sonar.api.resources.Language;
+import org.sonar.api.resources.Languages;
+import org.sonar.api.resources.Project;
+import org.sonar.api.resources.ProjectFileSystem;
+import org.sonar.api.rules.DefaultRulesManager;
+import org.sonar.api.utils.SonarException;
+import org.sonar.batch.*;
+import org.sonar.batch.bootstrapper.ProjectDefinition;
+import org.sonar.batch.components.PastViolationsLoader;
+import org.sonar.batch.components.TimeMachineConfiguration;
+import org.sonar.batch.events.EventBus;
+import org.sonar.batch.index.DefaultIndex;
+import org.sonar.batch.index.DefaultResourcePersister;
+import org.sonar.batch.phases.Phases;
+import org.sonar.batch.phases.PhasesTimeProfiler;
+import org.sonar.core.components.DefaultModelFinder;
+import org.sonar.jpa.dao.*;
+
+import java.util.Arrays;
+
+public class ProjectModule extends Module {
+ private static final Logger LOG = LoggerFactory.getLogger(ProjectModule.class);
+ private Project project;
+
+ public ProjectModule(Project project) {
+ this.project = project;
+ }
+
+ @Override
+ protected void configure() {
+ logSettings();
+ addCoreComponents();
+ addProjectComponents();
+ addProjectPluginExtensions();
+ }
+
+
+ private void addProjectComponents() {
+ ProjectDefinition projectDefinition = getComponent(ProjectTree.class).getProjectDefinition(project);
+ addComponent(projectDefinition);
+ for (Object component : projectDefinition.getContainerExtensions()) {
+ addComponent(component);
+ if (component instanceof MavenProject) {
+ // For backward compatibility we must set POM and actual packaging
+ MavenProject pom = (MavenProject) component;
+ project.setPom(pom);
+ project.setPackaging(pom.getPackaging());
+ }
+ }
+
+ addComponent(project);
+ addComponent(DefaultProjectClasspath.class);
+ addComponent(DefaultProjectFileSystem2.class);
+ addComponent(project.getConfiguration());
+ addComponent(DaoFacade.class);
+ addComponent(RulesDao.class);
+
+ // the Snapshot component will be removed when asynchronous measures are improved (required for AsynchronousMeasureSensor)
+ addComponent(getComponent(DefaultResourcePersister.class).getSnapshot(project));
+ addComponent(org.sonar.api.database.daos.MeasuresDao.class);
+ addComponent(ProfilesDao.class);
+ addComponent(AsyncMeasuresDao.class);
+ addComponent(AsyncMeasuresService.class);
+ addComponent(DefaultRulesManager.class);
+ addComponent(DefaultSensorContext.class);
+ addComponent(Languages.class);
+ addComponent(BatchExtensionDictionnary.class);
+ addComponent(DefaultTimeMachine.class);
+ addComponent(ViolationFilters.class);
+ addComponent(ResourceFilters.class);
+ addComponent(DefaultModelFinder.class);
+ addComponent(TimeMachineConfiguration.class);
+ addComponent(PastViolationsLoader.class);
+ addComponent(ProfileLoader.class, DefaultProfileLoader.class);
+ addAdapter(new ProfileProvider());
+ addAdapter(new CheckProfileProvider());
+ }
+
+ private void addCoreComponents() {
+ addComponent(EventBus.class);
+ addComponent(Phases.class);
+ addComponent(PhasesTimeProfiler.class);
+ for (Class clazz : Phases.getPhaseClasses()) {
+ addComponent(clazz);
+ }
+
+ // TODO move metrics to BatchComponents
+ for (Metric metric : CoreMetrics.getMetrics()) {
+ addComponent(metric.getKey(), metric);
+ }
+ for (Metrics metricRepo : getComponents(Metrics.class)) {
+ for (Metric metric : metricRepo.getMetrics()) {
+ addComponent(metric.getKey(), metric);
+ }
+ }
+ }
+
+ private void addProjectPluginExtensions() {
+ ProjectExtensionInstaller installer = getComponent(ProjectExtensionInstaller.class);
+ installer.install(this, project);
+ }
+
+
+ private void logSettings() {
+ // TODO move these logs in a dedicated component
+ LOG.info("------------- Analyzing {}", project.getName());
+
+ String[] exclusionPatterns = project.getExclusionPatterns();
+ if (exclusionPatterns != null && exclusionPatterns.length > 0) {
+ LOG.info("Excluded sources : {}", Arrays.toString(exclusionPatterns));
+ }
+ }
+
+ /**
+ * Analyze project
+ */
+ @Override
+ protected void doStart() {
+ Language language = getComponent(Languages.class).get(project.getLanguageKey());
+ if (language == null) {
+ throw new SonarException("Language with key '" + project.getLanguageKey() + "' not found");
+ }
+ project.setLanguage(language);
+
+ DefaultIndex index = getComponent(DefaultIndex.class);
+ index.setCurrentProject(project,
+ getComponent(ResourceFilters.class),
+ getComponent(ViolationFilters.class),
+ getComponent(RulesProfile.class));
+
+ // TODO See http://jira.codehaus.org/browse/SONAR-2126
+ // previously MavenProjectBuilder was responsible for creation of ProjectFileSystem
+ project.setFileSystem(getComponent(ProjectFileSystem.class));
+
+ getComponent(Phases.class).execute(project);
+ }
+}
package org.sonar.batch;
import org.junit.Test;
-import org.sonar.api.batch.maven.MavenPluginHandler;
-import org.sonar.api.resources.Project;
+import org.sonar.batch.bootstrap.Module;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class BatchTest {
- class MyMavenPluginExecutor implements MavenPluginExecutor {
- public void execute(Project project, String goal) {
- }
+ @Test
+ public void shouldExecute() {
+ FakeModule module = new FakeModule();
+ module.init();
+ new Batch(module).execute();
- public MavenPluginHandler execute(Project project, MavenPluginHandler handler) {
- return handler;
- }
+ assertThat(module.started, is(true));
+ assertThat(module.stopped, is(true));
}
- @Test
- public void shouldSearchMavenPluginExecutor() {
- Batch batch;
+ public static class FakeModule extends Module {
+ private boolean started=false;
+ private boolean stopped=false;
- batch = new Batch(null, MyMavenPluginExecutor.class);
- assertThat(batch.isMavenPluginExecutorRegistered(), is(true));
+ @Override
+ protected void doStart() {
+ started = true;
+ }
- batch = new Batch(null);
- assertThat(batch.isMavenPluginExecutorRegistered(), is(false));
+ @Override
+ protected void doStop() {
+ if (!started) {
+ throw new IllegalStateException("Not started");
+ }
+ stopped = true;
+ }
+
+ @Override
+ protected void configure() {
+ }
}
+
}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.junit.Test;
+import org.sonar.api.*;
+import org.sonar.api.batch.CoverageExtension;
+import org.sonar.api.batch.InstanciationStrategy;
+import org.sonar.batch.bootstrapper.EnvironmentInformation;
+
+import java.util.Arrays;
+import java.util.List;
+
+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;
+
+public class BatchExtensionInstallerTest {
+
+ @Test
+ public void shouldInstallExtensionsWithBatchInstantiationStrategy() {
+ BatchPluginRepository pluginRepository = mock(BatchPluginRepository.class);
+ when(pluginRepository.getPlugins()).thenReturn(Arrays.asList((Plugin) new SonarPlugin() {
+ public List getExtensions() {
+ return Arrays.asList(BatchService.class, ProjectService.class, ServerService.class);
+ }
+ }));
+ Module module = new FakeModule().init();
+ BatchExtensionInstaller installer = new BatchExtensionInstaller(pluginRepository, new EnvironmentInformation("ant", "1.7"));
+
+ installer.install(module);
+
+ assertThat(module.getComponent(BatchService.class), not(nullValue()));
+ assertThat(module.getComponent(ProjectService.class), nullValue());
+ assertThat(module.getComponent(ServerService.class), nullValue());
+ }
+
+ @Test
+ public void shouldInstallProvidersWithBatchInstantiationStrategy() {
+ BatchPluginRepository pluginRepository = mock(BatchPluginRepository.class);
+ when(pluginRepository.getPlugins()).thenReturn(Arrays.asList((Plugin) new SonarPlugin(){
+ public List getExtensions() {
+ return Arrays.asList(BatchServiceProvider.class, ProjectServiceProvider.class);
+ }
+ }));
+ Module module = new FakeModule().init();
+ BatchExtensionInstaller installer = new BatchExtensionInstaller(pluginRepository, new EnvironmentInformation("ant", "1.7"));
+
+ installer.install(module);
+
+ assertThat(module.getComponent(BatchService.class), not(nullValue()));
+ assertThat(module.getComponent(ProjectService.class), nullValue());
+ assertThat(module.getComponent(ServerService.class), nullValue());
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void shouldNotSupportCoverageExtensionsWithBatchInstantiationStrategy() {
+ // the reason is that CoverageExtensions currently depend on Project
+ BatchPluginRepository pluginRepository = mock(BatchPluginRepository.class);
+ when(pluginRepository.getPlugins()).thenReturn(Arrays.asList((Plugin) new SonarPlugin(){
+ public List getExtensions() {
+ return Arrays.asList(InvalidCoverageExtension.class);
+ }
+ }));
+ Module module = new FakeModule().init();
+ BatchExtensionInstaller installer = new BatchExtensionInstaller(pluginRepository, new EnvironmentInformation("ant", "1.7"));
+
+ installer.install(module);
+ }
+
+ public static class FakeModule extends Module {
+ @Override
+ protected void configure() {
+ }
+ }
+
+ @InstanciationStrategy(InstanciationStrategy.PER_BATCH)
+ public static class BatchService implements BatchExtension {
+
+ }
+
+ public static class ProjectService implements BatchExtension {
+
+ }
+
+ public static class ServerService implements ServerExtension {
+
+ }
+
+ @InstanciationStrategy(InstanciationStrategy.PER_BATCH)
+ public static class BatchServiceProvider extends ExtensionProvider implements BatchExtension {
+
+ @Override
+ public Object provide() {
+ return Arrays.asList(BatchService.class, ServerService.class);
+ }
+ }
+
+ public static class ProjectServiceProvider extends ExtensionProvider implements BatchExtension {
+ @Override
+ public Object provide() {
+ return ProjectService.class;
+ }
+ }
+
+ @InstanciationStrategy(InstanciationStrategy.PER_BATCH)
+ public static class InvalidCoverageExtension implements CoverageExtension {
+ // strategy PER_BATCH is not allowed
+ }
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.junit.Ignore;
+
+@Ignore
+public class BatchModuleTest {
+
+}
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.PropertiesConfiguration;
+import org.junit.Ignore;
import org.junit.Test;
import org.picocontainer.MutablePicoContainer;
import org.sonar.api.BatchExtension;
import org.sonar.api.resources.Project.AnalysisType;
import org.sonar.api.utils.IocContainer;
+@Ignore
public class BatchPluginRepositoryTest {
- @Test
- public void shouldRegisterBatchExtension() {
- MutablePicoContainer pico = IocContainer.buildPicoContainer();
- pico.addComponent(new PropertiesConfiguration());
- BatchPluginRepository repository = new BatchPluginRepository();
-
- // check classes
- assertThat(repository.shouldRegisterExtension(pico, "foo", FakeBatchExtension.class), is(true));
- assertThat(repository.shouldRegisterExtension(pico, "foo", FakeServerExtension.class), is(false));
- assertThat(repository.shouldRegisterExtension(pico, "foo", String.class), is(false));
-
- // check objects
- assertThat(repository.shouldRegisterExtension(pico, "foo", new FakeBatchExtension()), is(true));
- assertThat(repository.shouldRegisterExtension(pico, "foo", new FakeServerExtension()), is(false));
- assertThat(repository.shouldRegisterExtension(pico, "foo", "bar"), is(false));
- }
-
- @Test
- public void shouldRegisterOnlyCoberturaExtensionByDefault() {
- BatchPluginRepository repository = new BatchPluginRepository();
- PropertiesConfiguration conf = new PropertiesConfiguration();
- assertThat(repository.shouldRegisterCoverageExtension("cobertura", newJavaProject(), conf), is(true));
- assertThat(repository.shouldRegisterCoverageExtension("clover", newJavaProject(), conf), is(false));
- }
-
- @Test
- public void shouldRegisterCustomCoverageExtension() {
- Configuration conf = new PropertiesConfiguration();
- conf.setProperty(AbstractCoverageExtension.PARAM_PLUGIN, "clover,phpunit");
- BatchPluginRepository repository = new BatchPluginRepository();
- assertThat(repository.shouldRegisterCoverageExtension("cobertura", newJavaProject(), conf), is(false));
- assertThat(repository.shouldRegisterCoverageExtension("clover", newJavaProject(), conf), is(true));
- assertThat(repository.shouldRegisterCoverageExtension("phpunit", newJavaProject(), conf), is(true));
- assertThat(repository.shouldRegisterCoverageExtension("other", newJavaProject(), conf), is(false));
- }
-
- @Test
- public void shouldNotCheckCoverageExtensionsOnNonJavaProjects() {
- Configuration conf = new PropertiesConfiguration();
- conf.setProperty(AbstractCoverageExtension.PARAM_PLUGIN, "cobertura");
- BatchPluginRepository repository = new BatchPluginRepository();
-
- assertThat(repository.shouldRegisterCoverageExtension("groovy", newGroovyProject(), conf), is(true));
- assertThat(repository.shouldRegisterCoverageExtension("groovy", newJavaProject(), conf), is(false));
- }
-
- private static Project newJavaProject() {
- return new Project("foo").setLanguageKey(Java.KEY).setAnalysisType(AnalysisType.DYNAMIC);
- }
-
- private static Project newGroovyProject() {
- return new Project("foo").setLanguageKey("grvy").setAnalysisType(AnalysisType.DYNAMIC);
- }
-
- public static class FakeBatchExtension implements BatchExtension {
-
- }
-
- public static class FakeServerExtension implements ServerExtension {
-
- }
+// @Test
+// public void shouldRegisterBatchExtension() {
+// MutablePicoContainer pico = IocContainer.buildPicoContainer();
+// pico.addComponent(new PropertiesConfiguration());
+// BatchPluginRepository repository = new BatchPluginRepository();
+//
+// // check classes
+// assertThat(repository.shouldRegisterExtension(pico, "foo", FakeBatchExtension.class), is(true));
+// assertThat(repository.shouldRegisterExtension(pico, "foo", FakeServerExtension.class), is(false));
+// assertThat(repository.shouldRegisterExtension(pico, "foo", String.class), is(false));
+//
+// // check objects
+// assertThat(repository.shouldRegisterExtension(pico, "foo", new FakeBatchExtension()), is(true));
+// assertThat(repository.shouldRegisterExtension(pico, "foo", new FakeServerExtension()), is(false));
+// assertThat(repository.shouldRegisterExtension(pico, "foo", "bar"), is(false));
+// }
+//
+// @Test
+// public void shouldRegisterOnlyCoberturaExtensionByDefault() {
+// BatchPluginRepository repository = new BatchPluginRepository();
+// PropertiesConfiguration conf = new PropertiesConfiguration();
+// assertThat(repository.shouldRegisterCoverageExtension("cobertura", newJavaProject(), conf), is(true));
+// assertThat(repository.shouldRegisterCoverageExtension("clover", newJavaProject(), conf), is(false));
+// }
+//
+// @Test
+// public void shouldRegisterCustomCoverageExtension() {
+// Configuration conf = new PropertiesConfiguration();
+// conf.setProperty(AbstractCoverageExtension.PARAM_PLUGIN, "clover,phpunit");
+// BatchPluginRepository repository = new BatchPluginRepository();
+// assertThat(repository.shouldRegisterCoverageExtension("cobertura", newJavaProject(), conf), is(false));
+// assertThat(repository.shouldRegisterCoverageExtension("clover", newJavaProject(), conf), is(true));
+// assertThat(repository.shouldRegisterCoverageExtension("phpunit", newJavaProject(), conf), is(true));
+// assertThat(repository.shouldRegisterCoverageExtension("other", newJavaProject(), conf), is(false));
+// }
+//
+// @Test
+// public void shouldNotCheckCoverageExtensionsOnNonJavaProjects() {
+// Configuration conf = new PropertiesConfiguration();
+// conf.setProperty(AbstractCoverageExtension.PARAM_PLUGIN, "cobertura");
+// BatchPluginRepository repository = new BatchPluginRepository();
+//
+// assertThat(repository.shouldRegisterCoverageExtension("groovy", newGroovyProject(), conf), is(true));
+// assertThat(repository.shouldRegisterCoverageExtension("groovy", newJavaProject(), conf), is(false));
+// }
+//
+// private static Project newJavaProject() {
+// return new Project("foo").setLanguageKey(Java.KEY).setAnalysisType(AnalysisType.DYNAMIC);
+// }
+//
+// private static Project newGroovyProject() {
+// return new Project("foo").setLanguageKey("grvy").setAnalysisType(AnalysisType.DYNAMIC);
+// }
+//
+// public static class FakeBatchExtension implements BatchExtension {
+//
+// }
+//
+// public static class FakeServerExtension implements ServerExtension {
+//
+// }
}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.junit.Test;
+import org.sonar.api.batch.maven.MavenPluginHandler;
+import org.sonar.api.resources.Project;
+import org.sonar.batch.MavenPluginExecutor;
+
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+public class BootstrapModuleTest {
+
+ class MyMavenPluginExecutor implements MavenPluginExecutor {
+ public void execute(Project project, String goal) {
+ }
+
+ public MavenPluginHandler execute(Project project, MavenPluginHandler handler) {
+ return handler;
+ }
+ }
+
+ @Test
+ public void shouldSearchMavenPluginExecutor() {
+ BootstrapModule module = new BootstrapModule(null, MyMavenPluginExecutor.class);
+ assertThat(module.isMavenPluginExecutorRegistered(), is(true));
+
+ module = new BootstrapModule(null);
+ assertThat(module.isMavenPluginExecutorRegistered(), is(false));
+ }
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.junit.Test;
+import org.sonar.api.BatchExtension;
+import org.sonar.api.ServerExtension;
+import org.sonar.api.batch.InstanciationStrategy;
+import org.sonar.api.batch.SupportedEnvironment;
+import org.sonar.batch.bootstrapper.EnvironmentInformation;
+
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class ExtensionUtilsTest {
+
+ @Test
+ public void shouldBeBatchInstantiationStrategy() {
+ assertThat(ExtensionUtils.isInstantiationStrategy(BatchService.class, InstanciationStrategy.PER_BATCH), is(true));
+ assertThat(ExtensionUtils.isInstantiationStrategy(new BatchService(), InstanciationStrategy.PER_BATCH), is(true));
+ assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstanciationStrategy.PER_BATCH), is(false));
+ assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstanciationStrategy.PER_BATCH), is(false));
+ assertThat(ExtensionUtils.isInstantiationStrategy(DefaultService.class, InstanciationStrategy.PER_BATCH), is(false));
+ assertThat(ExtensionUtils.isInstantiationStrategy(new DefaultService(), InstanciationStrategy.PER_BATCH), is(false));
+ }
+
+ @Test
+ public void shouldBeProjectInstantiationStrategy() {
+ assertThat(ExtensionUtils.isInstantiationStrategy(BatchService.class, InstanciationStrategy.PER_PROJECT), is(false));
+ assertThat(ExtensionUtils.isInstantiationStrategy(new BatchService(), InstanciationStrategy.PER_PROJECT), is(false));
+ assertThat(ExtensionUtils.isInstantiationStrategy(ProjectService.class, InstanciationStrategy.PER_PROJECT), is(true));
+ assertThat(ExtensionUtils.isInstantiationStrategy(new ProjectService(), InstanciationStrategy.PER_PROJECT), is(true));
+ assertThat(ExtensionUtils.isInstantiationStrategy(DefaultService.class, InstanciationStrategy.PER_PROJECT), is(true));
+ assertThat(ExtensionUtils.isInstantiationStrategy(new DefaultService(), InstanciationStrategy.PER_PROJECT), is(true));
+ }
+
+ @Test
+ public void testIsBatchExtension() {
+ assertThat(ExtensionUtils.isBatchExtension(BatchService.class), is(true));
+ assertThat(ExtensionUtils.isBatchExtension(new BatchService()), is(true));
+
+ assertThat(ExtensionUtils.isBatchExtension(ServerService.class), is(false));
+ assertThat(ExtensionUtils.isBatchExtension(new ServerService()), is(false));
+ }
+
+ @Test
+ public void shouldCheckEnvironment() {
+ assertThat(ExtensionUtils.isSupportedEnvironment(new MavenService(), new EnvironmentInformation("maven", "2.2.1")), is(true));
+ assertThat(ExtensionUtils.isSupportedEnvironment(new BuildToolService(), new EnvironmentInformation("maven", "2.2.1")), is(true));
+ assertThat(ExtensionUtils.isSupportedEnvironment(new DefaultService(), new EnvironmentInformation("maven", "2.2.1")), is(true));
+
+ assertThat(ExtensionUtils.isSupportedEnvironment(new BuildToolService(), new EnvironmentInformation("eclipse", "0.1")), is(false));
+ }
+
+ @InstanciationStrategy(InstanciationStrategy.PER_BATCH)
+ public static class BatchService implements BatchExtension {
+
+ }
+
+ @InstanciationStrategy(InstanciationStrategy.PER_PROJECT)
+ public static class ProjectService implements BatchExtension {
+
+ }
+
+ public static class DefaultService implements BatchExtension {
+
+ }
+
+ public static class ServerService implements ServerExtension {
+
+ }
+
+ @SupportedEnvironment("maven")
+ public static class MavenService implements BatchExtension {
+
+ }
+
+ @SupportedEnvironment({"maven", "ant", "gradle"})
+ public static class BuildToolService implements BatchExtension {
+
+ }
+}
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.batch.bootstrap;
+
+import org.hamcrest.Matchers;
+import org.junit.Test;
+import org.sonar.batch.bootstrap.Module;
+
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+public class ModuleTest {
+
+ @Test
+ public void shouldInitModule() {
+ Module module = new FakeModule(FakeService.class).init();
+
+ FakeService service = module.getComponent(FakeService.class);
+ assertThat(service, not(nullValue()));
+ assertThat(service.started, is(false));
+ assertThat(module.getContainer(), not(nullValue()));
+ }
+
+ @Test
+ public void shouldStartAndStopModule() {
+ Module module = new FakeModule(FakeService.class).init();
+ module.start();
+
+ FakeService service = module.getComponent(FakeService.class);
+ assertThat(service.started, is(true));
+
+ module.stop();
+ assertThat(service.started, is(false));
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void shouldNotIgnoreStartFailures() {
+ Module module = new FakeModule(NonStartableService.class).init();
+ module.start();
+ }
+
+ @Test
+ public void shouldIgnoreStopFailures() {
+ Module module = new FakeModule(NonStoppableService.class).init();
+ module.start();
+ module.stop(); // no exception is raised
+ }
+
+ @Test
+ public void componentsShouldBeSingletons() {
+ Module module = new FakeModule(FakeService.class).init();
+
+ assertThat(module.getComponent(FakeService.class)==module.getComponent(FakeService.class), is(true));
+ }
+
+ @Test
+ public void shouldInstallChildModule() {
+ Module parent = new FakeModule(FakeService.class).init();
+ parent.start();
+
+ Module child = parent.installChild(new FakeModule(ChildService.class));
+
+ assertThat(parent.getComponent(ChildService.class), Matchers.nullValue());// child not accessible from parent
+ assertThat(child.getComponent(FakeService.class), not(nullValue()));
+ assertThat(child.getComponent(ChildService.class).started, is(false));
+ assertThat(child.getComponent(ChildService.class).dependency, not(nullValue()));
+
+ child.start();
+ assertThat(child.getComponent(ChildService.class).started, is(true));
+
+ child.stop();
+ assertThat(child.getComponent(ChildService.class).started, is(false));
+ }
+
+ public static class FakeModule extends Module {
+ private Class[] components;
+
+ public FakeModule(Class... components) {
+ this.components = components;
+ }
+
+ @Override
+ protected void configure() {
+ for (Class component : components) {
+ addComponent(component);
+ }
+ }
+
+ public boolean equals(Object obj) {
+ return false;
+ }
+ }
+
+ public static class FakeService {
+ boolean started = false;
+
+ public void start() {
+ this.started = true;
+ }
+
+ public void stop() {
+ this.started = false;
+ }
+ }
+
+ public static class ChildService {
+ private FakeService dependency;
+ private boolean started = false;
+
+ public ChildService(FakeService dependency) {
+ this.dependency = dependency;
+ }
+
+ public void start() {
+ this.started = true;
+ }
+
+ public void stop() {
+ this.started = false;
+ }
+ }
+
+ public static class NonStoppableService {
+ public void stop() {
+ throw new IllegalStateException("Can not stop !");
+ }
+ }
+
+ public static class NonStartableService {
+ public void start() {
+ throw new IllegalStateException("Can not start !");
+ }
+ }
+
+}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.check.AnnotationIntrospector;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public class AnnotationCheckTemplateFactory {
-
- private static final Logger LOG = LoggerFactory.getLogger(AnnotationCheckTemplateFactory.class);
-
- private Collection<Class> annotatedClasses;
-
- public AnnotationCheckTemplateFactory(Collection<Class> annotatedClasses) {
- this.annotatedClasses = annotatedClasses;
- }
-
- public List<CheckTemplate> create() {
- List<CheckTemplate> templates = new ArrayList<CheckTemplate>();
- for (Class annotatedClass : annotatedClasses) {
- BundleCheckTemplate template = create(annotatedClass);
- if (template != null) {
- templates.add(template);
- }
- }
- return templates;
- }
-
-
- protected BundleCheckTemplate create(Class annotatedClass) {
- org.sonar.check.Check checkAnnotation = AnnotationIntrospector.getCheckAnnotation(annotatedClass);
- if (checkAnnotation == null) {
- LOG.warn("The class " + annotatedClass.getCanonicalName() + " is not a check template. It should be annotated with " + CheckTemplate.class);
- return null;
- }
-
- BundleCheckTemplate check = toTemplate(annotatedClass, checkAnnotation);
- Field[] fields = annotatedClass.getDeclaredFields();
- if (fields != null) {
- for (Field field : fields) {
- BundleCheckTemplateProperty property = toProperty(check, field);
- if (property != null) {
- check.addProperty(property);
- }
- }
- }
- return check;
- }
-
- private static BundleCheckTemplate toTemplate(Class annotatedClass, org.sonar.check.Check checkAnnotation) {
- String key = AnnotationIntrospector.getCheckKey(annotatedClass);
- String bundle = getBundleBaseName(checkAnnotation, annotatedClass);
-
- BundleCheckTemplate check = new BundleCheckTemplate(key, bundle);
- check.setDefaultDescription(checkAnnotation.description());
- check.setDefaultTitle(checkAnnotation.title());
- check.setIsoCategory(checkAnnotation.isoCategory());
- check.setPriority(checkAnnotation.priority());
-
- return check;
- }
-
- private static String getBundleBaseName(org.sonar.check.Check checkAnnotation, Class annotatedClass) {
- String bundle = checkAnnotation.bundle();
- if (StringUtils.isBlank(bundle)) {
- bundle = annotatedClass.getCanonicalName();
- }
- return bundle;
- }
-
- private static BundleCheckTemplateProperty toProperty(BundleCheckTemplate check, Field field) {
- org.sonar.check.CheckProperty propertyAnnotation = field.getAnnotation(org.sonar.check.CheckProperty.class);
- if (propertyAnnotation != null) {
- String fieldKey = propertyAnnotation.key();
- if (fieldKey==null || "".equals(fieldKey)) {
- fieldKey = field.getName();
- }
- BundleCheckTemplateProperty property = new BundleCheckTemplateProperty(check, fieldKey);
- property.setDefaultTitle(propertyAnnotation.title());
- property.setDefaultDescription(propertyAnnotation.description());
- return property;
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Locale;
-import java.util.MissingResourceException;
-import java.util.ResourceBundle;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public class BundleCheckTemplate extends CheckTemplate {
- private static final Logger LOG = LoggerFactory.getLogger(BundleCheckTemplate.class);
-
- private String bundleBaseName;
- private String defaultTitle;
- private String defaultDescription;
-
- protected BundleCheckTemplate(String key, String bundleBaseName) {
- super(key);
- this.bundleBaseName = bundleBaseName;
- }
-
- protected BundleCheckTemplate(String key, Class bundleClass) {
- this(key, bundleClass.getCanonicalName());
- }
-
- protected String getDefaultTitle() {
- if (defaultTitle == null || "".equals(defaultTitle)) {
- return getKey();
- }
- return defaultTitle;
- }
-
- protected void setDefaultTitle(String defaultTitle) {
- this.defaultTitle = defaultTitle;
- }
-
- protected String getDefaultDescription() {
- return defaultDescription;
- }
-
- protected void setDefaultDescription(String defaultDescription) {
- this.defaultDescription = defaultDescription;
- }
-
- @Override
- public String getTitle(Locale locale) {
- return getText("title", locale, getDefaultTitle());
- }
-
- @Override
- public String getDescription(Locale locale) {
- return getText("description", locale, getDefaultDescription());
- }
-
- @Override
- public String getMessage(Locale locale, String key, Object... params) {
- return null;
- }
-
- protected String getText(String key, Locale locale, String defaultValue) {
- String result = null;
- ResourceBundle bundle = getBundle(locale);
- if (bundle != null) {
- try {
- result = bundle.getString(key);
- } catch (MissingResourceException e) {
- LOG.debug(e.getMessage());
- }
- }
- if (result == null) {
- result = defaultValue;
- }
- return result;
- }
-
- protected ResourceBundle getBundle(Locale locale) {
- try {
- if (locale != null) {
- return ResourceBundle.getBundle(bundleBaseName, locale);
- }
- } catch (MissingResourceException e) {
- // do nothing : use the default values
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import java.util.Locale;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public class BundleCheckTemplateProperty extends CheckTemplateProperty {
-
- private BundleCheckTemplate check;
- private String defaultTitle;
- private String defaultDescription;
-
- public BundleCheckTemplateProperty(BundleCheckTemplate check, String key) {
- setKey(key);
- this.check = check;
- }
-
- public String getDefaultTitle() {
- if (defaultTitle == null || "".equals(defaultTitle)) {
- return getKey();
- }
- return defaultTitle;
- }
-
- public void setDefaultTitle(String s) {
- this.defaultTitle = s;
- }
-
-
- @Override
- public String getTitle(Locale locale) {
- return check.getText("property." + getKey() + ".title", locale, getDefaultTitle());
- }
-
- public String getDefaultDescription() {
- return defaultDescription;
- }
-
- public void setDefaultDescription(String s) {
- this.defaultDescription = s;
- }
-
- @Override
- public String getDescription(Locale locale) {
- return check.getText("property." + getKey() + ".description", locale, getDefaultDescription());
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.sonar.check.IsoCategory;
-import org.sonar.check.Priority;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public abstract class CheckTemplate {
-
- protected String key;
- protected String configKey;
- protected Priority priority;
- protected IsoCategory isoCategory;
- protected List<CheckTemplateProperty> properties;
-
- public CheckTemplate(String key) {
- this.key = key;
- }
-
- public CheckTemplate() {
- }
-
- public String getKey() {
- return key;
- }
-
- public void setKey(String s) {
- this.key = s;
- }
-
- public Priority getPriority() {
- return priority;
- }
-
- public void setPriority(Priority p) {
- this.priority = p;
- }
-
- public IsoCategory getIsoCategory() {
- return isoCategory;
- }
-
- public void setIsoCategory(IsoCategory c) {
- this.isoCategory = c;
- }
-
- public String getConfigKey() {
- return configKey;
- }
-
- public void setConfigKey(String configKey) {
- this.configKey = configKey;
- }
-
- public abstract String getTitle(Locale locale);
-
- public abstract String getDescription(Locale locale);
-
- public abstract String getMessage(Locale locale, String key, Object... params);
-
- public List<CheckTemplateProperty> getProperties() {
- if (properties==null) {
- return Collections.emptyList();
- }
- return properties;
- }
-
- public void addProperty(CheckTemplateProperty p) {
- if (properties==null) {
- properties = new ArrayList<CheckTemplateProperty>();
- }
- properties.add(p);
- }
-
- public CheckTemplateProperty getProperty(String key) {
- if (properties!=null) {
- for (CheckTemplateProperty property : properties) {
- if (property.getKey().equals(key)) {
- return property;
- }
- }
- }
- return null;
- }
-
- /**
- * Checks are equal within the same plugin. Two plugins can have two different checks with the same key.
- */
- @Override
- public final boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof CheckTemplate)) {
- return false;
- }
-
- CheckTemplate checkTemplate = (CheckTemplate) o;
- return key.equals(checkTemplate.key);
- }
-
- @Override
- public final int hashCode() {
- return key.hashCode();
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import java.util.Collection;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public abstract class CheckTemplateFactory {
-
- public abstract Collection<CheckTemplate> create();
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import java.util.Locale;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public abstract class CheckTemplateProperty implements Comparable<CheckTemplateProperty> {
-
- protected String key;
-
- public String getKey() {
- return key;
- }
-
- public void setKey(String s) {
- this.key = s;
- }
-
- public abstract String getTitle(Locale locale);
-
- public String getDescription() {
- return getDescription(Locale.ENGLISH);
- }
-
-
- public abstract String getDescription(Locale locale);
-
- @Override
- public final boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (!(o instanceof CheckTemplateProperty)) {
- return false;
- }
-
- CheckTemplateProperty that = (CheckTemplateProperty) o;
- return key.equals(that.key);
- }
-
- @Override
- public final int hashCode() {
- return key.hashCode();
- }
-
- public int compareTo(CheckTemplateProperty o) {
- return getKey().compareTo(o.getKey());
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.sonar.api.ServerExtension;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public class CheckTemplateRepositories implements ServerExtension {
-
- private Map<String, CheckTemplateRepository> repositoriesByKey = new HashMap<String, CheckTemplateRepository>();
-
- public CheckTemplateRepositories(CheckTemplateRepository[] repositories) {
- if (repositories != null) {
- for (CheckTemplateRepository templateRepository : repositories) {
- repositoriesByKey.put(templateRepository.getKey(), templateRepository);
- }
- }
- }
-
- public CheckTemplateRepositories() {
- // DO NOT REMOVE THIS CONSTRUCTOR. It is used by Picocontainer when no repositories are available.
- }
-
- public CheckTemplateRepository getRepository(String key) {
- return repositoriesByKey.get(key);
- }
-
- public Collection<CheckTemplateRepository> getRepositories() {
- return repositoriesByKey.values();
- }
-
- public CheckTemplate getTemplate(String repositoryKey, String templateKey) {
- CheckTemplateRepository repo = getRepository(repositoryKey);
- if (repo != null) {
- return repo.getTemplate(templateKey);
- }
- return null;
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.apache.commons.io.IOUtils;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.resources.Language;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleParam;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.RulesRepository;
-
-import java.io.InputStream;
-import java.util.*;
-
-/**
- * @since 2.1 (experimental)
- * @deprecated since 2.3
- */
-@Deprecated
-public class CheckTemplateRepository implements RulesRepository {
-
- private String key;
- private Language language;
- private List<CheckTemplate> templates;
- private Map<String, CheckTemplate> templatesByKey;
-
- public CheckTemplateRepository() {
- }
-
- public CheckTemplateRepository(String key) {
- if (key == null) {
- throw new IllegalArgumentException("Key can not be null");
- }
- this.key = key;
- }
-
- public String getKey() {
- return key;
- }
-
- public CheckTemplateRepository setKey(String key) {
- this.key = key;
- return this;
- }
-
- public Language getLanguage() {
- return language;
- }
-
- public CheckTemplateRepository setLanguage(Language l) {
- this.language = l;
- return this;
- }
-
- public List<CheckTemplate> getTemplates() {
- if (templates == null) {
- return Collections.emptyList();
- }
- return templates;
- }
-
- public CheckTemplateRepository setTemplates(List<CheckTemplate> c) {
- this.templates = c;
- return this;
- }
-
- public CheckTemplate getTemplate(String key) {
- if (templatesByKey == null || templatesByKey.isEmpty()) {
- templatesByKey = new HashMap<String, CheckTemplate>();
- for (CheckTemplate template : templates) {
- templatesByKey.put(template.getKey(), template);
- }
- }
- return templatesByKey.get(key);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- CheckTemplateRepository that = (CheckTemplateRepository) o;
- return key.equals(that.key);
-
- }
-
- @Override
- public int hashCode() {
- return key.hashCode();
- }
-
- public static CheckTemplateRepository createFromXml(String repositoryKey, Language language, String pathToXml) {
- InputStream input = CheckTemplateRepository.class.getResourceAsStream(pathToXml);
- try {
- List<CheckTemplate> templates = new XmlCheckTemplateFactory().parse(input);
- CheckTemplateRepository repository = new CheckTemplateRepository(repositoryKey);
- repository.setTemplates(templates);
- repository.setLanguage(language);
- return repository;
-
- } finally {
- IOUtils.closeQuietly(input);
- }
- }
-
- public static CheckTemplateRepository createFromAnnotatedClasses(String repositoryKey, Language language, Collection<Class> classes) {
- AnnotationCheckTemplateFactory factory = new AnnotationCheckTemplateFactory(classes);
- CheckTemplateRepository repository = new CheckTemplateRepository(repositoryKey);
- repository.setTemplates(factory.create());
- repository.setLanguage(language);
- return repository;
- }
-
- /*
- * CODE FOR BACKWARD COMPATIBLITY
- * This class should not extend RulesRepository in next versions
- */
-
- public List<Rule> getInitialReferential() {
- List<Rule> rules = new ArrayList<Rule>();
- for (CheckTemplate checkTemplate : getTemplates()) {
- rules.add(toRule(checkTemplate));
- }
- return rules;
- }
-
- private Rule toRule(CheckTemplate checkTemplate) {
- Rule rule = new Rule(getKey(), checkTemplate.getKey());
- rule.setDescription(checkTemplate.getDescription(Locale.ENGLISH));
- rule.setName(checkTemplate.getTitle(Locale.ENGLISH));
- rule.setSeverity(RulePriority.fromCheckPriority(checkTemplate.getPriority()));
- for (CheckTemplateProperty checkTemplateProperty : checkTemplate.getProperties()) {
- RuleParam param = rule.createParameter(checkTemplateProperty.getKey());
- param.setDescription(checkTemplateProperty.getDescription(Locale.ENGLISH));
- param.setType("s");
- }
-
- return rule;
- }
-
- public List<Rule> parseReferential(String fileContent) {
- return Collections.emptyList();
- }
-
- public List<RulesProfile> getProvidedProfiles() {
- return Collections.emptyList();
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-
-import java.util.Locale;
-
-/**
- * EXPERIMENTAL - will be used in version 2.2
- *
- * Non-internationalized check
- *
- * @since 2.1
- */
-public class DefaultCheckTemplate extends CheckTemplate {
-
- private String title;
- private String description;
-
- public DefaultCheckTemplate() {
- }
-
- public DefaultCheckTemplate(String key) {
- super(key);
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @Override
- public String getTitle(Locale locale) {
- if (title == null || "".equals(title)) {
- return getKey();
- }
- return title;
- }
-
- @Override
- public String getDescription(Locale locale) {
- return description;
- }
-
- @Override
- public String getMessage(Locale locale, String key, Object... params) {
- return null;
- }
-
- @Override
- public String toString() {
- return new ToStringBuilder(this)
- .append("key", key)
- .append("title", title)
- .append("configKey", configKey)
- .append("priority", priority)
- .append("isoCategory", isoCategory)
- .toString();
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.sonar.api.checks.templates.CheckTemplateProperty;
-
-import java.util.Locale;
-
-/**
- * @since 2.1
- */
-public class DefaultCheckTemplateProperty extends CheckTemplateProperty {
-
- private String title;
- private String description;
-
- public String getTitle() {
- if (title == null || "".equals(title)) {
- return getKey();
- }
- return title;
- }
-
- @Override
- public String getTitle(Locale locale) {
- return getTitle();
- }
-
- public void setTitle(String s) {
- this.title = s;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String s) {
- this.description = s;
- }
-
- @Override
- public String getDescription(Locale locale) {
- return getDescription();
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.CharEncoding;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleParam;
-import org.sonar.api.rules.StandardRulesXmlParser;
-import org.sonar.api.utils.SonarException;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * EXPERIMENTAL - will be used in version 2.2
- *
- * @since 2.1
- */
-public class XmlCheckTemplateFactory {
-
- public List<CheckTemplate> parseXml(String xml) {
- InputStream input = null;
- try {
- input = IOUtils.toInputStream(xml, CharEncoding.UTF_8);
- return parse(input);
-
- } catch (IOException e) {
- throw new SonarException("Can't parse xml file", e);
-
- } finally {
- IOUtils.closeQuietly(input);
- }
- }
-
- public List<CheckTemplate> parse(Reader reader) {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- List<Rule> rules = parser.parse(reader);
- return toCheckTemplates(rules);
-
- }
-
- public List<CheckTemplate> parse(InputStream input) {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- List<Rule> rules = parser.parse(input);
- return toCheckTemplates(rules);
-
- }
-
- private List<CheckTemplate> toCheckTemplates(List<Rule> rules) {
- List<CheckTemplate> templates = new ArrayList<CheckTemplate>();
- if (rules != null) {
- for (Rule rule : rules) {
- DefaultCheckTemplate template = new DefaultCheckTemplate(rule.getKey());
- templates.add(template);
-
- template.setConfigKey(rule.getConfigKey());
- template.setDescription(rule.getDescription());
- template.setPriority(rule.getSeverity().toCheckPriority());
- template.setTitle(rule.getName());
-
- if (rule.getParams() != null) {
- for (RuleParam param : rule.getParams()) {
- template.addProperty(toProperty(param));
- }
- }
- }
- }
- return templates;
- }
-
- private CheckTemplateProperty toProperty(RuleParam param) {
- DefaultCheckTemplateProperty property = new DefaultCheckTemplateProperty();
- property.setKey(param.getKey());
- property.setTitle(param.getKey());
- property.setDescription(param.getDescription());
- return property;
- }
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.CharEncoding;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.resources.Language;
-import org.sonar.api.utils.SonarException;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-@Deprecated
-public abstract class AbstractImportableRulesRepository<LANG extends Language, MAPPER extends RulePriorityMapper<?, ?>> extends AbstractRulesRepository<LANG, MAPPER> implements ConfigurationImportable {
-
- public AbstractImportableRulesRepository(LANG language, MAPPER mapper) {
- super(language, mapper);
- }
-
- /**
- * A map a of profiles to import, The profile name as key, and the xml profile file name in the classpath
- *
- * @return
- */
- public abstract Map<String, String> getBuiltInProfiles();
-
- public final List<RulesProfile> getProvidedProfiles() {
- List<RulesProfile> profiles = new ArrayList<RulesProfile>();
-
- Map<String, String> defaultProfiles = new TreeMap<String, String>(getBuiltInProfiles());
- for (Map.Entry<String, String> entry : defaultProfiles.entrySet()) {
- profiles.add(loadProvidedProfile(entry.getKey(), getCheckResourcesBase() + entry.getValue()));
- }
- return profiles;
- }
-
- public final RulesProfile loadProvidedProfile(String name, String fileName) {
- InputStream input = null;
- try {
- input = getClass().getResourceAsStream(fileName);
- RulesProfile profile = new RulesProfile(name, getLanguage().getKey());
- profile.setActiveRules(importConfiguration(IOUtils.toString(input, CharEncoding.UTF_8), getInitialReferential()));
- return profile;
-
- } catch (IOException e) {
- throw new SonarException("Configuration file not found for the profile : " + name, e);
-
- } finally {
- IOUtils.closeQuietly(input);
- }
- }
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import org.apache.commons.io.IOUtils;
-import org.sonar.api.resources.Language;
-import org.sonar.api.utils.SonarException;
-
-import java.io.InputStream;
-import java.util.List;
-
-@Deprecated
-public abstract class AbstractRulesRepository<LANG extends Language, MAPPER extends RulePriorityMapper<?, ?>> implements RulesRepository<LANG> {
-
- private MAPPER priorityMapper;
- private LANG language;
-
- public AbstractRulesRepository(LANG language, MAPPER priorityMapper) {
- super();
- this.priorityMapper = priorityMapper;
- this.language = language;
- }
-
- public LANG getLanguage() {
- return language;
- }
-
- public abstract String getRepositoryResourcesBase();
-
- public final List<Rule> getInitialReferential() {
- String baseCP = getCheckResourcesBase();
- InputStream input = getClass().getResourceAsStream(baseCP + "rules.xml");
- if (input == null) {
- throw new SonarException("Resource not found : " + baseCP + "rules.xml");
- }
- try {
- return new StandardRulesXmlParser().parse(input);
- }
- finally {
- IOUtils.closeQuietly(input);
- }
- }
-
- public List<Rule> parseReferential(String fileContent) {
- return new StandardRulesXmlParser().parse(fileContent);
- }
-
- public MAPPER getRulePriorityMapper() {
- return priorityMapper;
- }
-
- protected String getCheckResourcesBase() {
- String base = getRepositoryResourcesBase();
- base = base.startsWith("/") ? base : "/" + base;
- base = base.endsWith("/") ? base : base + "/";
- return base;
- }
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import org.sonar.api.profiles.RulesProfile;
-
-@Deprecated
-public interface ConfigurationExportable {
-
- String exportConfiguration(RulesProfile profile);
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import java.util.List;
-import org.sonar.api.rules.Rule;
-
-@Deprecated
-public interface ConfigurationImportable {
-
- List<ActiveRule> importConfiguration(String configuration, List<Rule> rules);
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import org.sonar.api.BatchExtension;
-import org.sonar.api.ServerExtension;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.resources.Language;
-
-import java.util.List;
-
-/**
- * @deprecated since 2.3
- */
-@Deprecated
-public interface RulesRepository<LANG extends Language> extends BatchExtension, ServerExtension {
-
- /**
- * @return the language the repository is associated
- */
- LANG getLanguage();
-
- /**
- * @return the list of rules of the repository
- */
- List<Rule> getInitialReferential();
-
- /**
- * The method to parse the base referential of rules and return a list of rules
- *
- * @param fileContent the initial referential
- * @return a list of rules
- */
- List<Rule> parseReferential(String fileContent);
-
- /**
- * @return a list of profiles that are provided with the referential
- */
- List<RulesProfile> getProvidedProfiles();
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import com.thoughtworks.xstream.XStream;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.xml.Profile;
-import org.sonar.api.rules.xml.Property;
-import org.sonar.api.utils.SonarException;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@Deprecated
-public class StandardProfileXmlParser {
-
- private final List<Rule> rules;
-
- public StandardProfileXmlParser() {
- rules = new ArrayList<Rule>();
- }
-
- public StandardProfileXmlParser(List<Rule> rules) {
- this.rules = rules;
- }
-
- /**
- * see the XML format into the unit test src/test/java/.../StandardProfileXmlParserTest
- */
- public Profile parse(String xml) {
- return (Profile) getXStream().fromXML(xml);
- }
-
- private XStream getXStream() {
- XStream xstream = new XStream();
- xstream.processAnnotations(Profile.class);
- xstream.processAnnotations(Rule.class);
- xstream.processAnnotations(Property.class);
- return xstream;
- }
-
- public RulesProfile importConfiguration(String configuration) {
- RulesProfile rulesProfile = new RulesProfile();
- List<ActiveRule> activeRules = new ArrayList<ActiveRule>();
- Profile profile = buildProfileFromXml(configuration);
-
- rulesProfile.setName(profile.getName());
- rulesProfile.setLanguage(profile.getLanguage());
-
- if (StringUtils.isBlank(rulesProfile.getName())) {
- throw new SonarException("Profile name can't be null or empty");
- }
-
- buildActiveRulesFromProfile(profile, activeRules);
- rulesProfile.setActiveRules(activeRules);
- return rulesProfile;
- }
-
- protected Profile buildProfileFromXml(String configuration) {
- StandardProfileXmlParser xstream = new StandardProfileXmlParser();
- return xstream.parse(configuration);
- }
-
- protected void buildActiveRulesFromProfile(Profile profile, List<ActiveRule> activeRules) {
- if (profile.getRules() != null && !profile.getRules().isEmpty()) {
- for (org.sonar.api.rules.xml.Rule module : profile.getRules()) {
- String ref = module.getKey();
- for (Rule rule : rules) {
- if (rule.getConfigKey().equals(ref)) {
- RulePriority rulePriority = getRulePriority(module);
- ActiveRule activeRule = new ActiveRule(null, rule, rulePriority);
- activeRule.setActiveRuleParams(getActiveRuleParams(module, rule, activeRule));
- activeRules.add(activeRule);
- break;
- }
- }
- }
- }
- }
-
- private RulePriority getRulePriority(org.sonar.api.rules.xml.Rule module) {
- return StringUtils.isBlank(module.getPriority()) ? null : RulePriority.valueOfString(module.getPriority());
- }
-
- private List<ActiveRuleParam> getActiveRuleParams(org.sonar.api.rules.xml.Rule module, Rule rule, ActiveRule activeRule) {
- List<ActiveRuleParam> activeRuleParams = new ArrayList<ActiveRuleParam>();
- if (module.getProperties() != null) {
- for (Property property : module.getProperties()) {
- if (rule.getParams() != null) {
- for (RuleParam ruleParam : rule.getParams()) {
- if (ruleParam.getKey().equals(property.getName())) {
- activeRuleParams.add(new ActiveRuleParam(activeRule, ruleParam, property.getValue()));
- }
- }
- }
- }
- }
- return activeRuleParams;
- }
-
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import com.thoughtworks.xstream.XStream;
-import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
-import com.thoughtworks.xstream.core.util.QuickWriter;
-import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
-import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
-import com.thoughtworks.xstream.io.xml.XppDriver;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.CharEncoding;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.utils.SonarException;
-
-import java.io.*;
-import java.lang.ref.WeakReference;
-import java.util.*;
-
-@Deprecated
-public class StandardRulesXmlParser {
-
- /**
- * see the XML format into the unit test src/test/java/.../StandardRulesXmlParserTest
- */
- public List<Rule> parse(String xml) {
- InputStream inputStream = null;
- try {
- inputStream = IOUtils.toInputStream(xml, CharEncoding.UTF_8);
- return setDefaultRuleSeverities((List<Rule>) getXStream().fromXML(inputStream));
-
- } catch (IOException e) {
- throw new SonarException("Can't parse xml file", e);
-
- } finally {
- IOUtils.closeQuietly(inputStream);
- }
- }
-
- public List<Rule> parse(Reader reader) {
- return setDefaultRuleSeverities((List<Rule>) getXStream().fromXML(reader));
- }
-
- public List<Rule> parse(InputStream input) {
- try {
- return setDefaultRuleSeverities((List<Rule>) getXStream().fromXML(new InputStreamReader(input, CharEncoding.UTF_8)));
-
- } catch (UnsupportedEncodingException e) {
- throw new SonarException("Can't parse xml file", e);
- }
- }
-
- private List<Rule> setDefaultRuleSeverities(List<Rule> rules) {
- for (Rule rule : rules) {
- if (rule.getSeverity() == null) {
- rule.setSeverity(RulePriority.MAJOR);
- }
- }
- return rules;
- }
-
- public String toXml(List<Rule> rules) {
- return getXStream().toXML(rules);
- }
-
- private static class CDataXppDriver extends XppDriver {
- @Override
- public HierarchicalStreamWriter createWriter(Writer out) {
- return new XDataPrintWriter(out);
- }
- }
-
- private static class XDataPrintWriter extends PrettyPrintWriter {
- public XDataPrintWriter(Writer writer) {
- super(writer);
- }
-
- @Override
- protected void writeText(QuickWriter writer, String text) {
- writer.write("<![CDATA[");
- writer.write(text);
- writer.write("]]>");
- }
- }
-
- private XStream getXStream() {
- XStream xstream = new XStream(new CDataXppDriver());
- xstream.registerConverter(new TrimStringConverter());
- xstream.alias("rules", ArrayList.class);
-
- xstream.omitField(Rule.class, "category");
-
- xstream.alias("rule", Rule.class);
- xstream.useAttributeFor(Rule.class, "key");
- xstream.useAttributeFor("priority", RulePriority.class);
-
- xstream.addImplicitCollection(Rule.class, "params");
-
- xstream.alias("param", RuleParam.class);
- xstream.useAttributeFor(RuleParam.class, "key");
- xstream.useAttributeFor(RuleParam.class, "type");
-
- // only for backward compatibility with sonar 1.4.
- xstream.omitField(RuleParam.class, "defaultValue");
- return xstream;
- }
-
- /**
- * See http://svn.codehaus.org/xstream/trunk/xstream/src/java/com/thoughtworks/xstream/converters/basic/StringConverter.java
- */
- public static class TrimStringConverter extends AbstractSingleValueConverter {
-
- private final Map cache;
-
- public TrimStringConverter(final Map map) {
- cache = map;
- }
-
- public TrimStringConverter() {
- this(Collections.synchronizedMap(new WeakHashMap()));
- }
-
- public boolean canConvert(final Class type) {
- return type.equals(String.class);
- }
-
- public Object fromString(final String str) {
- String trim = StringUtils.trim(str);
- final WeakReference ref = (WeakReference) cache.get(trim);
- String s = (String) (ref == null ? null : ref.get());
-
- if (s == null) {
- // fill cache
- cache.put(str, new WeakReference(trim));
- s = trim;
- }
-
- return s;
- }
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.sonar.api.checks.samples.*;
-import org.sonar.check.IsoCategory;
-
-import java.util.Iterator;
-import java.util.Locale;
-
-import static junit.framework.Assert.assertNotNull;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.*;
-
-public class AnnotationCheckTemplateFactoryTest {
-
- private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
- private static final Locale ALTERNATIVE_LOCALE = Locale.FRENCH;
- private static final Locale UNKNOWN_LOCALE = Locale.CHINESE;
-
- private static final Locale JVM_LOCALE = Locale.getDefault();
-
- @BeforeClass
- public static void beforeAll() {
- Locale.setDefault(Locale.ENGLISH);
- }
-
- @AfterClass
- public static void afterAll() {
- Locale.setDefault(JVM_LOCALE);
- }
-
- @Test
- public void checkWithDefaultValues() {
- BundleCheckTemplate check = new AnnotationCheckTemplateFactory(null).create(SimpleAnnotatedCheck.class);
- assertNotNull(check);
-
- assertThat(check.getKey(), is("org.sonar.api.checks.samples.SimpleAnnotatedCheck"));
-
- assertThat(check.getTitle(DEFAULT_LOCALE), is("org.sonar.api.checks.samples.SimpleAnnotatedCheck"));
- assertThat(check.getTitle(ALTERNATIVE_LOCALE), is("org.sonar.api.checks.samples.SimpleAnnotatedCheck"));
- assertThat(check.getTitle(UNKNOWN_LOCALE), is("org.sonar.api.checks.samples.SimpleAnnotatedCheck"));
-
- assertThat(check.getDescription(DEFAULT_LOCALE), is(""));
- assertThat(check.getDescription(ALTERNATIVE_LOCALE), is(""));
- assertThat(check.getDescription(UNKNOWN_LOCALE), is(""));
-
- assertEquals(IsoCategory.Efficiency, check.getIsoCategory());
-
- assertThat(check.getProperties().size(), is(2));
- Iterator<CheckTemplateProperty> it = check.getProperties().iterator();
-
- CheckTemplateProperty maxTemplateProperty = it.next();
- assertThat(maxTemplateProperty.getKey(), is("max"));
-
- assertThat(maxTemplateProperty.getDescription(DEFAULT_LOCALE), is(""));
- assertThat(maxTemplateProperty.getDescription(ALTERNATIVE_LOCALE), is(""));
- assertThat(maxTemplateProperty.getDescription(UNKNOWN_LOCALE), is(""));
-
- CheckTemplateProperty minTemplateProperty = it.next();
- assertThat(minTemplateProperty.getKey(), is("min"));
- }
-
- @Test
- public void failOnNonCheckClass() {
- assertNull(new AnnotationCheckTemplateFactory(null).create(String.class));
- }
-
- @Test
- public void checkWithDetailedMessages() {
- BundleCheckTemplate check = new AnnotationCheckTemplateFactory(null).create(DetailedAnnotatedCheck.class);
- assertNotNull(check);
-
- assertThat(check.getKey(), is("org.sonar.api.checks.samples.DetailedAnnotatedCheck"));
-
- assertThat(check.getTitle(DEFAULT_LOCALE), is("Detailed Check"));
- assertThat(check.getTitle(ALTERNATIVE_LOCALE), is("Detailed Check"));
- assertThat(check.getTitle(UNKNOWN_LOCALE), is("Detailed Check"));
-
- assertThat(check.getDescription(DEFAULT_LOCALE), is("Detailed description"));
- assertThat(check.getDescription(ALTERNATIVE_LOCALE), is("Detailed description"));
- assertThat(check.getDescription(UNKNOWN_LOCALE), is("Detailed description"));
-
- assertThat(check.getIsoCategory(), is(IsoCategory.Reliability));
-
- assertThat(check.getProperties().size(), is(2));
- Iterator<CheckTemplateProperty> it = check.getProperties().iterator();
-
- CheckTemplateProperty maxTemplateProperty = it.next();
- assertThat(maxTemplateProperty.getKey(), is("max"));
-
- assertThat(maxTemplateProperty.getDescription(DEFAULT_LOCALE), is("Maximum value"));
- assertThat(maxTemplateProperty.getDescription(ALTERNATIVE_LOCALE), is("Maximum value"));
- assertThat(maxTemplateProperty.getDescription(UNKNOWN_LOCALE), is("Maximum value"));
- }
-
- @Test
- public void checkWithInternationalizedMessages() {
- BundleCheckTemplate check = new AnnotationCheckTemplateFactory(null).create(AnnotatedCheckWithBundles.class);
- assertNotNull(check);
-
- assertThat(check.getKey(), is("org.sonar.api.checks.samples.AnnotatedCheckWithBundles"));
- assertThat(check.getTitle(DEFAULT_LOCALE), is("I18n Check"));
- assertThat(check.getTitle(ALTERNATIVE_LOCALE), is("Règle d'internationalisation"));
- assertThat(check.getTitle(UNKNOWN_LOCALE), is("I18n Check"));
-
- assertThat(check.getDescription(DEFAULT_LOCALE), is("Description in english"));
- assertThat(check.getDescription(ALTERNATIVE_LOCALE), is("Description en Français"));
- assertThat(check.getDescription(UNKNOWN_LOCALE), is("Description in english"));
-
- assertThat(check.getProperties().size(), is(2));
- Iterator<CheckTemplateProperty> it = check.getProperties().iterator();
-
- CheckTemplateProperty maxTemplateProperty = it.next();
- assertThat(maxTemplateProperty.getKey(), is("max"));
-
- assertThat(maxTemplateProperty.getDescription(DEFAULT_LOCALE), is("Description in english of the maximum value"));
- assertThat(maxTemplateProperty.getDescription(ALTERNATIVE_LOCALE), is("Description en Français de la valeur maximale"));
- assertThat(maxTemplateProperty.getDescription(UNKNOWN_LOCALE), is("Description in english of the maximum value"));
- }
-
- @Test
- public void loadBundlesFromAlternativePath() {
- BundleCheckTemplate check = new AnnotationCheckTemplateFactory(null).create(I18nCheckWithAlternativeBundle.class);
- assertNotNull(check);
-
- assertThat(check.getKey(), is("new_key"));
- assertThat(check.getTitle(DEFAULT_LOCALE), is("Alternative Path to Bundle"));
- }
-
- @Test
- public void loadFromAnnotationIfNoDefaultLocale() {
- BundleCheckTemplate check = new AnnotationCheckTemplateFactory(null).create(I18nCheckWithoutDefaultLocale.class);
- assertNotNull(check);
-
- assertThat(check.getTitle(DEFAULT_LOCALE), is("Title from annotation"));
- assertThat(check.getTitle(ALTERNATIVE_LOCALE), is("Titre depuis le bundle"));
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.sonar.api.checks.samples.AnnotatedCheckWithBundles;
-import org.sonar.api.checks.samples.SimpleAnnotatedCheck;
-
-import java.util.Locale;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-public class BundleCheckTemplateTest {
-
- private static final Locale DEFAULT_LOCALE = Locale.getDefault();
-
- @BeforeClass
- public static void beforeAll() {
- Locale.setDefault(Locale.ENGLISH);
- }
-
- @AfterClass
- public static void afterAll() {
- Locale.setDefault(DEFAULT_LOCALE);
- }
-
- @Test
- public void loadBundlesFromClass() {
- BundleCheckTemplate check = new BundleCheckTemplate("key", AnnotatedCheckWithBundles.class);
-
- assertNotNull(check.getBundle(Locale.ENGLISH));
- assertNotNull(check.getBundle(Locale.FRENCH));
- assertNotNull(check.getBundle(Locale.CHINESE)); // use the english bundle
-
- assertThat(check.getBundle(Locale.ENGLISH).getString("title"), is("I18n Check"));
- assertThat(check.getBundle(Locale.CHINESE).getString("title"), is("I18n Check"));
- assertThat(check.getBundle(Locale.FRENCH).getString("title"), is("Règle d'internationalisation"));
- }
-
- @Test
- public void useDefaultValuesWhenNoBundles() {
- BundleCheckTemplate check = new BundleCheckTemplate("key", SimpleAnnotatedCheck.class);
- check.setDefaultTitle("default title");
- check.setDefaultDescription("default desc");
-
- assertThat(check.getTitle(null), is("default title"));
- assertThat(check.getTitle(Locale.ENGLISH), is("default title"));
- assertThat(check.getTitle(Locale.CHINESE), is("default title"));
-
- assertThat(check.getDescription(Locale.ENGLISH), is("default desc"));
- assertThat(check.getDescription(Locale.CHINESE), is("default desc"));
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.junit.Test;
-import org.sonar.api.checks.templates.CheckTemplateRepositories;
-import org.sonar.api.checks.templates.CheckTemplateRepository;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNull;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class CheckTemplateRepositoriesTest {
-
- @Test
- public void noRepositories() {
- CheckTemplateRepositories templateRepositories = new CheckTemplateRepositories();
- assertNull(templateRepositories.getRepository("foo"));
- assertThat(templateRepositories.getRepositories().size(), is(0));
- }
-
- @Test
- public void getRepositoryByKey() {
- CheckTemplateRepository repo1 = mock(CheckTemplateRepository.class);
- when(repo1.getKey()).thenReturn("one");
-
- CheckTemplateRepository repo2 = mock(CheckTemplateRepository.class);
- when(repo2.getKey()).thenReturn("two");
-
- CheckTemplateRepositories templateRepositories = new CheckTemplateRepositories(new CheckTemplateRepository[]{repo1, repo2});
-
- assertThat(templateRepositories.getRepositories().size(), is(2));
- assertEquals(repo1, templateRepositories.getRepository("one"));
- assertEquals(repo2, templateRepositories.getRepository("two"));
- assertNull(templateRepositories.getRepository("foo"));
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.checks.templates;
-
-import org.junit.Test;
-
-import java.util.Locale;
-
-import static org.junit.Assert.assertEquals;
-
-public class DefaultCheckTemplateTest {
-
- @Test
- public void isNotInternationalized() {
- DefaultCheckTemplate check = new DefaultCheckTemplate("key1");
- check.setTitle("title");
- check.setDescription("desc");
-
- assertEquals("title", check.getTitle(Locale.ENGLISH));
- assertEquals(check.getTitle(Locale.ENGLISH), check.getTitle(Locale.FRENCH));
-
- assertEquals("desc", check.getDescription(Locale.ENGLISH));
- assertEquals(check.getDescription(Locale.ENGLISH), check.getDescription(Locale.FRENCH));
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import org.apache.commons.io.IOUtils;
-import org.hamcrest.CoreMatchers;
-import org.junit.Assert;
-import org.junit.Test;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.xml.Profile;
-import org.sonar.api.rules.xml.Property;
-import org.sonar.api.utils.SonarException;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-public class StandardProfileXmlParserTest {
-
- @Test
- public void checkAllFields() {
- StandardProfileXmlParser parser = new StandardProfileXmlParser();
- String xml = "<profile name='Sonar way' language='java'><rule key=\"2006\" priority=\"warning\" /><rule key=\"2007\" priority=\"error\"><property name=\"toto\" value=\"titi\" /></rule></profile>";
- Profile profile = parser.parse(xml);
-
- assertEquals(2, profile.getRules().size());
- assertEquals("Sonar way", profile.getName());
-
- org.sonar.api.rules.xml.Rule rule1 = profile.getRules().get(0);
- assertEquals("2006", rule1.getKey());
- assertEquals("warning", rule1.getPriority());
- assertNull(rule1.getProperties());
-
- org.sonar.api.rules.xml.Rule rule2 = profile.getRules().get(1);
- assertEquals("2007", rule2.getKey());
- assertEquals("error", rule2.getPriority());
- assertEquals(rule2.getProperties().size(), 1);
-
- Property property = rule2.getProperties().get(0);
- assertEquals("toto", property.getName());
- assertEquals("titi", property.getValue());
- }
-
- @Test(expected = SonarException.class)
- public void shouldProfileNameBeNotNull() throws IOException {
- InputStream input = getClass().getResourceAsStream("/org/sonar/api/rules/test_profile_name_null.xml");
- StandardProfileXmlParser standardProfileXmlParser = new StandardProfileXmlParser();
- standardProfileXmlParser.importConfiguration(IOUtils.toString(input));
- }
-
- @Test
- public void shouldBuildProfileFromXml() throws IOException {
- StandardProfileXmlParser standardProfileXmlParser = new StandardProfileXmlParser();
- InputStream input = getClass().getResourceAsStream("/org/sonar/api/rules/test_profile.xml");
- Profile profile = standardProfileXmlParser.buildProfileFromXml(IOUtils.toString(input));
-
- assertThat("Sonar way", is(profile.getName()));
- assertThat(profile.getRules().size(), is(3));
-
- org.sonar.api.rules.xml.Rule rule1 = profile.getRules().get(0);
- assertThat(rule1.getKey(), is("2006"));
- assertThat(rule1.getPriority(), is("warning"));
- assertNull(rule1.getProperties());
-
- org.sonar.api.rules.xml.Rule rule2 = profile.getRules().get(1);
- assertThat(rule2.getKey(), is("2007"));
- assertThat(rule2.getPriority(), is("error"));
- assertThat(rule2.getProperties().size(), is(1));
-
- org.sonar.api.rules.xml.Rule rule3 = profile.getRules().get(2);
- assertThat(rule3.getKey(), is("2008"));
- assertThat(rule3.getPriority(), is("critical"));
- assertNull(rule3.getProperties());
-
- Property rule2Property = rule2.getProperties().get(0);
- assertThat(rule2Property.getName(), is("toto"));
- assertThat(rule2Property.getValue(), is("titi"));
- }
-
- @Test
- public void shouldImportConfiguration() throws IOException {
- final List<Rule> inputRules = buildRulesFixture();
- List<ActiveRule> activeRulesExpected = buildActiveRulesFixture(inputRules);
-
- StandardProfileXmlParser standardProfileXmlParser = new StandardProfileXmlParser(inputRules);
-
- InputStream input = getClass().getResourceAsStream("/org/sonar/api/rules/test_profile.xml");
- RulesProfile profile = standardProfileXmlParser.importConfiguration(IOUtils.toString(input));
- List<ActiveRule> results = profile.getActiveRules();
-
- assertThat("Sonar way", CoreMatchers.is(profile.getName()));
- assertThat(results.size(), is(activeRulesExpected.size()));
- assertActiveRulesAreEquals(results, activeRulesExpected);
- }
-
- private List<Rule> buildRulesFixture() {
- List<Rule> rules = new ArrayList<Rule>();
-
- Rule rule1 = new Rule("One rule", "2006",
- "2006", null, "MYPLUGIN", null);
-
- Rule rule2 = new Rule("Another rule", "2007",
- "2007", null, "MYPLUGIN", null);
- RuleParam ruleParam2 = new RuleParam(rule2, "toto", null, "s");
- rule2.setParams(Arrays.asList(ruleParam2));
-
- Rule rule3 = new Rule("Third rule", "2008",
- "2008", null, "MYPLUGIN", null);
-
- rules.add(rule1);
- rules.add(rule2);
- rules.add(rule3);
-
- return rules;
- }
-
- private List<ActiveRule> buildActiveRulesFixture(List<Rule> rules) {
- List<ActiveRule> activeRules = new ArrayList<ActiveRule>();
-
- ActiveRule activeRule1 = new ActiveRule(null, rules.get(0), RulePriority.INFO);
- activeRules.add(activeRule1);
-
- ActiveRule activeRule2 = new ActiveRule(null, rules.get(1), RulePriority.MAJOR);
- activeRule2.setActiveRuleParams(Arrays.asList(new ActiveRuleParam(activeRule2, rules.get(1).getParams().get(0), "titi")));
- activeRules.add(activeRule2);
-
- ActiveRule activeRule3 = new ActiveRule(null, rules.get(2), RulePriority.CRITICAL);
- activeRules.add(activeRule3);
-
- return activeRules;
- }
-
- private void assertActiveRulesAreEquals(List<ActiveRule> activeRules1, List<ActiveRule> activeRules2) {
- for (int i = 0; i < activeRules1.size(); i++) {
- ActiveRule activeRule1 = activeRules1.get(i);
- ActiveRule activeRule2 = activeRules2.get(i);
- assertTrue(activeRule1.getRule().equals(activeRule2.getRule()) && activeRule1.getSeverity().equals(activeRule2.getSeverity()));
-
- Assert.assertEquals(activeRule1.getActiveRuleParams().size(), (activeRule2.getActiveRuleParams().size()));
- for (int j = 0; j < activeRule1.getActiveRuleParams().size(); j++) {
- ActiveRuleParam activeRuleParam1 = activeRule1.getActiveRuleParams().get(j);
- ActiveRuleParam activeRuleParam2 = activeRule2.getActiveRuleParams().get(j);
- assertTrue(activeRuleParam1.getRuleParam().equals(activeRuleParam2.getRuleParam())
- && activeRuleParam1.getValue().equals(activeRuleParam2.getValue()));
- }
- }
- }
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.api.rules;
-
-import org.apache.commons.io.IOUtils;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.util.List;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-public class StandardRulesXmlParserTest {
- @Test
- public void checkAllFields() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1'><name>my name</name><configKey>my_config_key</configKey><description>my description</description><param key='param1'><type>s</type><description>param description</description></param><param key='param2'><type>integer</type><description>param description 2</description></param></rule></rules>";
- List<Rule> rules = parser.parse(xml);
- assertEquals(1, rules.size());
-
- Rule rule = rules.get(0);
- Assert.assertEquals("key1", rule.getKey());
- Assert.assertEquals("my name", rule.getName());
- Assert.assertEquals("my_config_key", rule.getConfigKey());
- Assert.assertEquals("my description", rule.getDescription());
- Assert.assertEquals(2, rule.getParams().size());
- Assert.assertEquals("param1", rule.getParams().get(0).getKey());
- Assert.assertEquals("s", rule.getParams().get(0).getType());
- Assert.assertEquals("param description", rule.getParams().get(0).getDescription());
- }
-
- @Test
- public void ruleCanHaveALevel() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='1' priority='CRITICAL'><category name='cat1'/></rule></rules>";
- List<Rule> rules = parser.parse(xml);
- Assert.assertEquals(RulePriority.CRITICAL, rules.get(0).getSeverity());
- }
-
- @Test
- public void ruleShouldHaveADefaultLevel() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='1'><category name='cat1'/></rule></rules>";
- List<Rule> rules = parser.parse(xml);
- Assert.assertEquals(RulePriority.MAJOR, rules.get(0).getSeverity());
- }
-
- @Test
- public void shouldDefineManyRules() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1' /><rule key='key2' category='cat1' /></rules>";
- List<Rule> rules = parser.parse(xml);
- assertEquals(2, rules.size());
- Assert.assertEquals("key1", rules.get(0).getKey());
- Assert.assertEquals("key2", rules.get(1).getKey());
- }
-
- @Test
- public void someFielsShouldBeNull() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1' /></rules>";
- List<Rule> rules = parser.parse(xml);
- assertNull(rules.get(0).getDescription());
- assertNull(rules.get(0).getName());
- assertNull(rules.get(0).getConfigKey());
- }
-
- @Test
- public void shouldContainCDataDescription() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1'><description> <![CDATA[<xml> </nodes> and accents ��� ]]> </description></rule></rules>";
- List<Rule> rules = parser.parse(xml);
- assertEquals(1, rules.size());
- Assert.assertEquals("<xml> </nodes> and accents ���", rules.get(0).getDescription());
- }
-
- @Test
- public void shouldBeBackwardCompatibleWithDefaultVersionProperty() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1'><name>my name</name><configKey>my_config_key</configKey><param key='param1'><type>s</type><description>param description</description><defaultValue>xxx</defaultValue></param></rule></rules>";
- List<Rule> rules = parser.parse(xml);
- assertEquals(1, rules.size());
-
- Rule rule = rules.get(0);
- Assert.assertEquals("key1", rule.getKey());
- Assert.assertEquals(1, rule.getParams().size());
- Assert.assertEquals("param1", rule.getParams().get(0).getKey());
- }
-
- @Test
- public void shouldParseStringInUt8() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1' ><description>\\u00E9</description></rule></rules>";
- List<Rule> rules = parser.parse(xml);
- assertThat(rules.get(0).getDescription(), is("\\u00E9"));
- }
-
- @Test
- public void shouldParseInputStreamInUt8() {
- StandardRulesXmlParser parser = new StandardRulesXmlParser();
- String xml = "<rules><rule key='key1' category='cat1' ><description>\\u00E9</description></rule></rules>";
- List<Rule> rules = parser.parse(IOUtils.toInputStream(xml));
- assertThat(rules.get(0).getDescription(), is("\\u00E9"));
- }
-}
+++ /dev/null
-<profile name="Sonar way" language='java'>\r
- <rule key="2006" priority="warning"/>\r
- <rule key="2007" priority="error">\r
- <property name="toto" value="titi"/>\r
- </rule>\r
- <rule key="2008" priority="critical"/>\r
-</profile>
\ No newline at end of file
+++ /dev/null
-<profile name="" language='java'>\r
- <rule key="2006" priority="warning"/>\r
- <rule key="2007" priority="error">\r
- <property name="toto" value="titi"/>\r
- </rule>\r
-</profile>
\ No newline at end of file
public Plugin getPlugin(String key) {
return pluginProvider.getPlugin(key);
}
-
- /**
- * Returns a plugin based on its extension
- */
- public Plugin getPluginByExtension(Extension extension) {
- return pluginProvider.getPluginForExtension(extension);
- }
-
/**
* Returns the list of properties of a plugin
*/
--- /dev/null
+/*
+ * Sonar, open source software quality management tool.
+ * Copyright (C) 2008-2011 SonarSource
+ * mailto:contact AT sonarsource DOT com
+ *
+ * Sonar is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * Sonar is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with Sonar; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
+ */
+package org.sonar.api.batch;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Define instanciation strategy of batch extensions. If an extension is not annotated, then default value
+ * is {@link org.sonar.api.batch.InstanciationStrategy#PER_PROJECT}.
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.TYPE)
+public @interface InstanciationStrategy {
+
+ /**
+ * Shared extension. Lifecycle is the full analysis.
+ */
+ public static final String PER_BATCH = "PER_BATCH";
+
+ /**
+ * Created and initialized for each project and sub-project (a project is a module in Maven terminology).
+ */
+ public static final String PER_PROJECT = "PER_PROJECT";
+
+ String value();
+}
Plugin getPlugin(String key);
- /**
- * @deprecated since 2.3
- */
- @Deprecated
- Plugin getPluginForExtension(Object extension);
-
Property[] getProperties(Plugin plugin);
}
servicesContainer.as(Characteristics.CACHE).addComponent(XMLRuleParser.class);
servicesContainer.as(Characteristics.CACHE).addComponent(DefaultRuleFinder.class);
servicesContainer.as(Characteristics.CACHE).addComponent(DefaultMetricFinder.class);
- servicesContainer.as(Characteristics.CACHE).addComponent(DeprecatedRuleRepositories.class);
- servicesContainer.as(Characteristics.CACHE).addComponent(DeprecatedProfiles.class);
- servicesContainer.as(Characteristics.CACHE).addComponent(DeprecatedProfileExporters.class);
- servicesContainer.as(Characteristics.CACHE).addComponent(DeprecatedProfileImporters.class);
servicesContainer.as(Characteristics.CACHE).addComponent(ProfilesConsole.class);
servicesContainer.as(Characteristics.CACHE).addComponent(RulesConsole.class);
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.server.rules;
-
-import org.sonar.api.Plugin;
-import org.sonar.api.Plugins;
-import org.sonar.api.ServerComponent;
-import org.sonar.api.profiles.ProfileExporter;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.ConfigurationExportable;
-import org.sonar.api.rules.RulesRepository;
-import org.sonar.api.utils.SonarException;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.List;
-
-public final class DeprecatedProfileExporters implements ServerComponent {
-
- private Plugins plugins;
- private RulesRepository[] deprecatedRepositories;
-
- public DeprecatedProfileExporters(Plugins plugins, RulesRepository[] deprecatedRepositories) {
- this.deprecatedRepositories = deprecatedRepositories;
- this.plugins = plugins;
- }
-
- public DeprecatedProfileExporters(Plugins plugins) {
- this.deprecatedRepositories = new RulesRepository[0];
- this.plugins = plugins;
- }
-
- public List<ProfileExporter> create() {
- List<ProfileExporter> result = new ArrayList<ProfileExporter>();
- for (RulesRepository repo : deprecatedRepositories) {
- if (repo instanceof ConfigurationExportable) {
- result.add(new DeprecatedProfileExporter(getPlugin(repo), repo));
- }
- }
- return result;
- }
-
- private Plugin getPlugin(RulesRepository repository) {
- return plugins.getPluginByExtension(repository);
- }
-}
-
-class DeprecatedProfileExporter extends ProfileExporter {
- private RulesRepository exportableRepository;
-
- protected DeprecatedProfileExporter(Plugin plugin, RulesRepository exportableRepository) {
- super(plugin.getKey(), plugin.getName());
- this.exportableRepository = exportableRepository;
- setSupportedLanguages(exportableRepository.getLanguage().getKey());
- setMimeType("application/xml");
- }
-
-
- @Override
- public void exportProfile(RulesProfile profile, Writer writer) {
- String xml = ((ConfigurationExportable)exportableRepository).exportConfiguration(profile);
- if (xml != null) {
- try {
- writer.append(xml);
- } catch (IOException e) {
- throw new SonarException("Can not export profile", e);
- }
- }
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.server.rules;
-
-import org.apache.commons.io.IOUtils;
-import org.sonar.api.Plugin;
-import org.sonar.api.Plugins;
-import org.sonar.api.profiles.ProfileImporter;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.*;
-import org.sonar.api.utils.SonarException;
-import org.sonar.api.utils.ValidationMessages;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.List;
-
-public class DeprecatedProfileImporters {
-
- private Plugins plugins;
- private RuleFinder ruleFinder;
- private RulesRepository[] deprecatedRepositories;
-
- public DeprecatedProfileImporters(Plugins plugins, RuleFinder ruleFinder, RulesRepository[] deprecatedRepositories) {
- this.deprecatedRepositories = deprecatedRepositories;
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- }
-
- public DeprecatedProfileImporters(Plugins plugins, RuleFinder ruleFinder) {
- this.deprecatedRepositories = new RulesRepository[0];
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- }
-
- public List<ProfileImporter> create() {
- List<ProfileImporter> result = new ArrayList<ProfileImporter>();
- for (RulesRepository repo : deprecatedRepositories) {
- if (repo instanceof ConfigurationImportable) {
- result.add(new DeprecatedProfileImporter(getPlugin(repo), ruleFinder, repo));
- }
- }
- return result;
- }
-
- private Plugin getPlugin(RulesRepository repository) {
- return plugins.getPluginByExtension(repository);
- }
-}
-
-class DeprecatedProfileImporter extends ProfileImporter {
- private RulesRepository importableRepository;
- private RuleFinder ruleFinder;
-
- protected DeprecatedProfileImporter(Plugin plugin, RuleFinder ruleFinder, RulesRepository importableRepository) {
- super(plugin.getKey(), plugin.getName());
- this.importableRepository = importableRepository;
- this.ruleFinder = ruleFinder;
- setSupportedLanguages(importableRepository.getLanguage().getKey());
- }
-
- @Override
- public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
- List<Rule> rules = new ArrayList<Rule>(ruleFinder.findAll(RuleQuery.create().withRepositoryKey(getKey())));
- try {
- RulesProfile profile = RulesProfile.create(getKey(), getName());
- List<ActiveRule> activeRules = ((ConfigurationImportable) importableRepository).importConfiguration(IOUtils.toString(reader), rules);
- profile.setActiveRules(activeRules);
- return profile;
-
- } catch (IOException e) {
- throw new SonarException("Fail to load the profile definition", e);
- }
- }
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.server.rules;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.Plugins;
-import org.sonar.api.checks.profiles.Check;
-import org.sonar.api.checks.profiles.CheckProfile;
-import org.sonar.api.checks.profiles.CheckProfileProvider;
-import org.sonar.api.profiles.ProfileDefinition;
-import org.sonar.api.profiles.RulesProfile;
-import org.sonar.api.rules.*;
-import org.sonar.api.utils.ValidationMessages;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-public final class DeprecatedProfiles {
-
- private RulesRepository[] deprecatedRepositories;
- private Plugins plugins;
- private RuleFinder ruleFinder;
- private CheckProfile[] deprecatedCheckProfiles;
- private CheckProfileProvider[] deprecatedCheckProfileProviders;
-
- public DeprecatedProfiles(Plugins plugins, RuleFinder ruleFinder, RulesRepository[] r, CheckProfile[] deprecatedCheckProfiles, CheckProfileProvider[] deprecatedCheckProfileProviders) {
- this.deprecatedRepositories = (RulesRepository[])ArrayUtils.clone(r);
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- this.deprecatedCheckProfiles = (CheckProfile[])ArrayUtils.clone(deprecatedCheckProfiles);
- this.deprecatedCheckProfileProviders = (CheckProfileProvider[])ArrayUtils.clone(deprecatedCheckProfileProviders);
- }
-
- public DeprecatedProfiles(Plugins plugins, RuleFinder ruleFinder, RulesRepository[] r, CheckProfile[] deprecatedCheckProfiles) {
- this.deprecatedRepositories = (RulesRepository[])ArrayUtils.clone(r);
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- this.deprecatedCheckProfiles = (CheckProfile[])ArrayUtils.clone(deprecatedCheckProfiles);
- this.deprecatedCheckProfileProviders = new CheckProfileProvider[0];
- }
-
- public DeprecatedProfiles(Plugins plugins, RuleFinder ruleFinder, RulesRepository[] r, CheckProfileProvider[] deprecatedCheckProfileProviders) {
- this.deprecatedRepositories = (RulesRepository[])ArrayUtils.clone(r);
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- this.deprecatedCheckProfiles = new CheckProfile[0];
- this.deprecatedCheckProfileProviders = deprecatedCheckProfileProviders;
- }
-
- public DeprecatedProfiles(Plugins plugins, RuleFinder ruleFinder, RulesRepository[] r) {
- this.deprecatedRepositories = (RulesRepository[])ArrayUtils.clone(r);
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- this.deprecatedCheckProfiles = new CheckProfile[0];
- this.deprecatedCheckProfileProviders = new CheckProfileProvider[0];
- }
-
- public DeprecatedProfiles(Plugins plugins, RuleFinder ruleFinder) {
- this.deprecatedRepositories = new RulesRepository[0];
- this.plugins = plugins;
- this.ruleFinder = ruleFinder;
- this.deprecatedCheckProfiles = new CheckProfile[0];
- this.deprecatedCheckProfileProviders = new CheckProfileProvider[0];
- }
-
- public List<ProfileDefinition> getProfiles() {
- List<ProfileDefinition> profiles = new ArrayList<ProfileDefinition>();
- for (RulesRepository repository : deprecatedRepositories) {
- profiles.addAll(loadFromDeprecatedRepository(repository));
- }
- for (CheckProfile deprecatedCheckProfile : deprecatedCheckProfiles) {
- profiles.add(loadFromDeprecatedCheckProfile(deprecatedCheckProfile));
- }
- for (CheckProfileProvider provider : deprecatedCheckProfileProviders) {
- for (CheckProfile deprecatedCheckProfile : provider.provide()) {
- profiles.add(loadFromDeprecatedCheckProfile(deprecatedCheckProfile));
- }
- }
- return profiles;
- }
-
- private List<ProfileDefinition> loadFromDeprecatedRepository(RulesRepository repository) {
- List<ProfileDefinition> result = new ArrayList<ProfileDefinition>();
-
- for (int index = 0; index < repository.getProvidedProfiles().size(); index++) {
- RulesProfile deprecated = (RulesProfile) repository.getProvidedProfiles().get(index);
- DefaultProfileDefinition providedProfile = DefaultProfileDefinition.create(deprecated.getName(), repository.getLanguage().getKey());
- for (ActiveRule deprecatedActiveRule : deprecated.getActiveRules(true)) {
- String repositoryKey = deprecatedActiveRule.getRepositoryKey();
- if (StringUtils.isBlank(repositoryKey)) {
- repositoryKey = getPluginKey(repository);
- }
- Rule rule = ruleFinder.findByKey(repositoryKey, deprecatedActiveRule.getRuleKey());
- if (rule != null) {
- ActiveRule activeRule = providedProfile.activateRule(rule, deprecatedActiveRule.getSeverity());
- for (ActiveRuleParam arp : deprecatedActiveRule.getActiveRuleParams()) {
- activeRule.setParameter(arp.getKey(), arp.getValue());
- }
- }
- }
- result.add(providedProfile);
- }
- return result;
- }
-
- private ProfileDefinition loadFromDeprecatedCheckProfile(CheckProfile cp) {
- DefaultProfileDefinition definition = DefaultProfileDefinition.create(cp.getName(), cp.getLanguage());
- for (Check check : cp.getChecks()) {
- RulePriority priority = null;
- if (check.getPriority() != null) {
- priority = RulePriority.fromCheckPriority(check.getPriority());
- }
- Rule rule = ruleFinder.findByKey(check.getRepositoryKey(), check.getTemplateKey());
- if (rule != null) {
- ActiveRule activeRule = definition.activateRule(rule, priority);
- for (Map.Entry<String, String> entry : check.getProperties().entrySet()) {
- activeRule.setParameter(entry.getKey(), entry.getValue());
- }
- }
- }
- return definition;
- }
-
- private String getPluginKey(RulesRepository repository) {
- return plugins.getPluginByExtension(repository).getKey();
- }
-
- public static class DefaultProfileDefinition extends ProfileDefinition {
-
- private RulesProfile profile;
-
- DefaultProfileDefinition(String name, String language) {
- this.profile = RulesProfile.create(name, language);
- }
-
- public static DefaultProfileDefinition create(String name, String language) {
- return new DefaultProfileDefinition(name, language);
- }
-
- @Override
- public RulesProfile createProfile(ValidationMessages validation) {
- return profile;
- }
-
- public List<ActiveRule> getRules() {
- return profile.getActiveRules(true);
- }
-
- public List<ActiveRule> getRulesByRepositoryKey(String repositoryKey) {
- return profile.getActiveRulesByRepository(repositoryKey);
- }
-
- public ActiveRule activateRule(Rule rule, RulePriority nullablePriority) {
- return profile.activateRule(rule, nullablePriority);
- }
- }
-
-}
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.server.rules;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.CharEncoding;
-import org.sonar.api.Plugin;
-import org.sonar.api.Plugins;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleParam;
-import org.sonar.api.rules.RuleRepository;
-import org.sonar.api.rules.RulesRepository;
-import org.sonar.api.utils.SonarException;
-import org.sonar.server.platform.DefaultServerFileSystem;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-public final class DeprecatedRuleRepositories {
-
- private RulesRepository<?>[] repositories;
- private DefaultServerFileSystem fileSystem;
- private Plugins plugins;
-
- public DeprecatedRuleRepositories(DefaultServerFileSystem fileSystem, Plugins plugins) {
- this.fileSystem = fileSystem;
- this.plugins = plugins;
- this.repositories = new RulesRepository[0];
- }
-
- public DeprecatedRuleRepositories(DefaultServerFileSystem fileSystem, Plugins plugins, RulesRepository[] repositories) {
- this.fileSystem = fileSystem;
- this.plugins = plugins;
- this.repositories = repositories;
- }
-
- public List<DeprecatedRuleRepository> create() {
- List<DeprecatedRuleRepository> repositories = new ArrayList<DeprecatedRuleRepository>();
- for (RulesRepository repository : this.repositories) {
- Plugin plugin = getPlugin(repository);
- repositories.add(new DeprecatedRuleRepository(plugin.getKey(), plugin.getName(), repository, fileSystem));
- }
- return repositories;
- }
-
- private Plugin getPlugin(RulesRepository repository) {
- return plugins.getPluginByExtension(repository);
- }
-}
-
-class DeprecatedRuleRepository extends RuleRepository {
-
- private RulesRepository deprecatedRepository;
- private DefaultServerFileSystem fileSystem;
-
- public DeprecatedRuleRepository(String repositoryKey, String repositoryName, RulesRepository deprecatedRepository, DefaultServerFileSystem fileSystem) {
- super(repositoryKey, deprecatedRepository.getLanguage().getKey());
- this.deprecatedRepository = deprecatedRepository;
- this.fileSystem = fileSystem;
- setName(repositoryName);
- }
-
- @Override
- public List<Rule> createRules() {
- List<Rule> rules = new ArrayList<Rule>();
- registerRules(rules);
- registerRuleExtensions(rules);
- return rules;
- }
-
- private void registerRules(List<Rule> rules) {
- List<Rule> deprecatedRules = deprecatedRepository.getInitialReferential();
- if (deprecatedRules != null) {
- for (Rule deprecatedRule : deprecatedRules) {
- rules.add(cloneRule(deprecatedRule));
- }
- }
- }
-
- private void registerRuleExtensions(List<Rule> rules) {
- for (File file : fileSystem.getPluginExtensionXml(getKey())) {
- try {
- String fileContent = FileUtils.readFileToString(file, CharEncoding.UTF_8);
- List<Rule> deprecatedRules = deprecatedRepository.parseReferential(fileContent);
- if (deprecatedRules != null) {
- for (Rule deprecatedRule : deprecatedRules) {
- rules.add(cloneRule(deprecatedRule));
- }
- }
- } catch (IOException e) {
- throw new SonarException("Can not read the file: " + file.getPath(), e);
- }
- }
- }
-
- private Rule cloneRule(Rule deprecatedRule) {
- Rule rule = Rule.create(getKey(), deprecatedRule.getKey(), deprecatedRule.getName());
- rule.setConfigKey(deprecatedRule.getConfigKey());
- rule.setSeverity(deprecatedRule.getSeverity());
- rule.setDescription(deprecatedRule.getDescription());
- rule.setEnabled(true);
- if (deprecatedRule.getParams() != null) {
- for (RuleParam deprecatedParam : deprecatedRule.getParams()) {
- rule.createParameter(deprecatedParam.getKey())
- .setDescription(deprecatedParam.getDescription())
- .setType(deprecatedParam.getType());
- }
- }
- return rule;
- }
-}
private List<ProfileImporter> importers = new ArrayList<ProfileImporter>();
public ProfilesConsole(DatabaseSessionFactory sessionFactory, XMLProfileParser xmlProfileParser, XMLProfileSerializer xmlProfileSerializer,
- ProfileExporter[] exporters, DeprecatedProfileExporters deprecatedExporters,
- ProfileImporter[] importers, DeprecatedProfileImporters deprecatedImporters) {
+ ProfileExporter[] exporters,
+ ProfileImporter[] importers) {
this.xmlProfileParser = xmlProfileParser;
this.xmlProfileSerializer = xmlProfileSerializer;
this.sessionFactory = sessionFactory;
- initProfileExporters(exporters, deprecatedExporters);
- initProfileImporters(importers, deprecatedImporters);
- }
-
- private void initProfileExporters(ProfileExporter[] exporters, DeprecatedProfileExporters deprecatedExporters) {
this.exporters.addAll(Arrays.asList(exporters));
- for (ProfileExporter exporter : deprecatedExporters.create()) {
- this.exporters.add(exporter);
- }
- }
-
- private void initProfileImporters(ProfileImporter[] importers, DeprecatedProfileImporters deprecatedImporters) {
this.importers.addAll(Arrays.asList(importers));
- for (ProfileImporter importer : deprecatedImporters.create()) {
- this.importers.add(importer);
- }
}
public String backupProfile(int profileId) {
private SetMultimap<String, RuleRepository> repositoriesByLanguage = HashMultimap.create();
- public RulesConsole(RuleRepository[] repositories, DeprecatedRuleRepositories deprecatedRuleRepositories) {
- initRepositories(repositories, deprecatedRuleRepositories);
+ public RulesConsole(RuleRepository[] repositories) {
+ initRepositories(repositories);
}
- private void initRepositories(RuleRepository[] repositories, DeprecatedRuleRepositories deprecatedBridge) {
+ private void initRepositories(RuleRepository[] repositories) {
this.repositories.addAll(Arrays.asList(repositories));
- if (deprecatedBridge != null) {
- this.repositories.addAll(deprecatedBridge.create());
- }
for (RuleRepository repository : this.repositories) {
if (!repositoryByKey.containsKey(repository.getKey())) {
repositoriesByLanguage.put(repository.getLanguage(), repository);
import org.sonar.api.utils.TimeProfiler;
import org.sonar.api.utils.ValidationMessages;
import org.sonar.jpa.session.DatabaseSessionFactory;
-import org.sonar.server.rules.DeprecatedProfiles;
import java.util.ArrayList;
import java.util.Arrays;
private DatabaseSessionFactory sessionFactory;
private List<ProfileDefinition> definitions = Lists.newArrayList();
- private DeprecatedProfiles deprecatedProfiles = null;
private RuleFinder ruleFinder;
public RegisterProvidedProfiles(RuleFinder ruleFinder, DatabaseSessionFactory sessionFactory,
- DeprecatedProfiles deprecatedBridge, RegisterRules registerRulesBefore,// NOSONAR the parameter registerRulesBefore is unused must be declared for execution order of tasks
+ RegisterRules registerRulesBefore,// NOSONAR the parameter registerRulesBefore is unused must be declared for execution order of tasks
ProfileDefinition[] definitions) {
this.ruleFinder = ruleFinder;
this.sessionFactory = sessionFactory;
this.definitions.addAll(Arrays.asList(definitions));
- this.deprecatedProfiles = deprecatedBridge;
}
public RegisterProvidedProfiles(RuleFinder ruleFinder, DatabaseSessionFactory sessionFactory,
- DeprecatedProfiles deprecatedBridge, RegisterRules registerRulesBefore) {// NOSONAR the parameter registerRulesBefore is unused must be declared for execution order of tasks
+ RegisterRules registerRulesBefore) {// NOSONAR the parameter registerRulesBefore is unused must be declared for execution order of tasks
this.ruleFinder = ruleFinder;
this.sessionFactory = sessionFactory;
- this.deprecatedProfiles = deprecatedBridge;
}
public void start() {
List<RulesProfile> createProfiles() {
List<RulesProfile> result = Lists.newArrayList();
-
- // this must not be moved in the constructor, because rules are still not saved
- definitions.addAll(deprecatedProfiles.getProfiles());
-
for (ProfileDefinition definition : definitions) {
ValidationMessages validation = ValidationMessages.create();
RulesProfile profile = definition.createProfile(validation);
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.rules.*;
+import org.sonar.api.rules.ActiveRuleParam;
+import org.sonar.api.rules.Rule;
+import org.sonar.api.rules.RuleParam;
+import org.sonar.api.rules.RuleRepository;
import org.sonar.api.utils.Logs;
import org.sonar.api.utils.TimeProfiler;
import org.sonar.jpa.session.DatabaseSessionFactory;
-import org.sonar.server.rules.DeprecatedRuleRepositories;
import java.util.*;
private DatabaseSessionFactory sessionFactory;
private List<RuleRepository> repositories = new ArrayList<RuleRepository>();
- public RegisterRules(DatabaseSessionFactory sessionFactory, DeprecatedRuleRepositories repositories, RuleRepository[] repos) {
+ public RegisterRules(DatabaseSessionFactory sessionFactory, RuleRepository[] repos) {
this.sessionFactory = sessionFactory;
this.repositories.addAll(Arrays.asList(repos));
- if (repositories != null) {
- this.repositories.addAll(repositories.create());
- }
}
- public RegisterRules(DatabaseSessionFactory sessionFactory, DeprecatedRuleRepositories repositories) {
- this(sessionFactory, repositories, new RuleRepository[0]);
+ public RegisterRules(DatabaseSessionFactory sessionFactory) {
+ this(sessionFactory, new RuleRepository[0]);
}
public void start() {
private void deleteDeprecatedParameters(Rule persistedRule, Rule rule, DatabaseSession session) {
if (persistedRule.getParams() != null && persistedRule.getParams().size() > 0) {
- for (Iterator<RuleParam> it = persistedRule.getParams().iterator(); it.hasNext();) {
+ for (Iterator<RuleParam> it = persistedRule.getParams().iterator(); it.hasNext(); ) {
RuleParam persistedParam = it.next();
if (rule.getParam(persistedParam.getKey()) == null) {
it.remove();
+++ /dev/null
-/*
- * Sonar, open source software quality management tool.
- * Copyright (C) 2008-2011 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * Sonar is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * Sonar is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with Sonar; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
- */
-package org.sonar.server.rules;
-
-import org.junit.Test;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.utils.ValidationMessages;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-
-public class DeprecatedProfilesTest {
- @Test
- public void shouldCreateProfile() {
- DeprecatedProfiles.DefaultProfileDefinition def = DeprecatedProfiles.DefaultProfileDefinition.create("sonar way", "java");
- assertThat(def.createProfile(ValidationMessages.create()).getName(), is("sonar way"));
- assertThat(def.createProfile(ValidationMessages.create()).getLanguage(), is("java"));
- }
-
- @Test
- public void testActivateRule() {
- DeprecatedProfiles.DefaultProfileDefinition def = DeprecatedProfiles.DefaultProfileDefinition.create("sonar way", "java");
- def.activateRule(Rule.create("checkstyle", "IllegalRegexp", "Illegal Regexp"), RulePriority.BLOCKER);
- def.activateRule(Rule.create("pmd", "NullPointer", "Null Pointer"), RulePriority.INFO);
-
- assertThat(def.getRules().size(), is(2));
- assertThat(def.getRulesByRepositoryKey("checkstyle").size(), is(1));
- assertThat(def.getRulesByRepositoryKey("checkstyle").get(0).getSeverity(), is(RulePriority.BLOCKER));
- }
-
- @Test
- public void priorityIsOptional() {
- DeprecatedProfiles.DefaultProfileDefinition def = DeprecatedProfiles.DefaultProfileDefinition.create("sonar way", "java");
- def.activateRule(Rule.create("checkstyle", "IllegalRegexp", "Illegal regexp").setSeverity(RulePriority.BLOCKER), null);
- assertThat(def.getRules().get(0).getSeverity(), is(RulePriority.BLOCKER));
- }
-}
new FakeRepository("findbugs", "java"),
new FakeRepository("findbugs", "java"), // for example fb-contrib
};
- RulesConsole console = new RulesConsole(repositories, null);
+ RulesConsole console = new RulesConsole(repositories);
assertThat(console.getRepository("findbugs"), not(Matchers.nullValue()));
assertThat(console.getRepositoriesByLanguage("java").size(), is(1));
@Test
public void saveNewRepositories() {
setupData("shared");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
List<Rule> result = getSession().getResults(Rule.class, "pluginName", "fake");
@Test
public void disableDeprecatedRepositories() {
setupData("shared");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
List<Rule> rules = (List<Rule>) getSession()
@Test
public void disableDeprecatedActiveRules() {
setupData("disableDeprecatedActiveRules");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
List<Rule> result = getSession().getResults(Rule.class, "pluginName", "fake");
@Test
public void disableDeprecatedActiveRuleParameters() {
setupData("disableDeprecatedActiveRuleParameters");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
ActiveRule arule = getSession().getSingleResult(ActiveRule.class, "id", 1);
@Test
public void disableDeprecatedRules() {
setupData("disableDeprecatedRules");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
Rule rule = getSession().getSingleResult(Rule.class, "id", 1);
@Test
public void updateRuleFields() {
setupData("updadeRuleFields");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
// fields have been updated with new values
@Test
public void updateRuleParameters() {
setupData("updateRuleParameters");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
Rule rule = getSession().getSingleResult(Rule.class, "id", 1);
@Test
public void doNotDisableUserRulesIfParentIsEnabled() {
setupData("doNotDisableUserRulesIfParentIsEnabled");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
Rule rule = getSession().getSingleResult(Rule.class, "id", 2);
@Test
public void disableUserRulesIfParentIsDisabled() {
setupData("disableUserRulesIfParentIsDisabled");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new FakeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new FakeRepository() });
task.start();
Rule rule = getSession().getSingleResult(Rule.class, "id", 2);
@Test
public void volumeTesting() {
setupData("shared");
- RegisterRules task = new RegisterRules(getSessionFactory(), null, new RuleRepository[] { new VolumeRepository() });
+ RegisterRules task = new RegisterRules(getSessionFactory(), new RuleRepository[] { new VolumeRepository() });
task.start();
List<Rule> result = getSession().getResults(Rule.class, "enabled", true);