protected Resource createResource(File file, List<File> sourceDirs, boolean unitTest) { org.sonar.api.resources.File resource = org.sonar.api.resources.File.fromIOFile(file, sourceDirs); if (resource != null) { resource.setLanguage(language); if (unitTest) { resource.setQualifier(Qualifiers.UNIT_TEST_FILE); } } return resource; }
@Override public String getSource(Resource reference) { Resource resource = getResource(reference); if (resource instanceof File) { File file = (File) resource; Project module = currentProject; ProjectDefinition def = projectTree.getProjectDefinition(module); try { return FileUtils.readFileToString(new java.io.File(def.getBaseDir(), file.getPath())); } catch (IOException e) { throw new IllegalStateException("Unable to read file content " + reference, e); } } return null; }
/** * Create violation from Aftermath Sin * * <p>Note can return null */ protected Violation createViolation(RealmNode realm, SoulNode soul, SinNode sin) { String ruleKey = sin.getTruth(); // get the rule from the repository Rule rule = this.ruleFinder.findByKey(AftermathRuleRepository.REPOSITORY_KEY, ruleKey); if (null == rule) { AftermathResultAnalysis.LOG.info("- Rule [" + ruleKey + "] not found in Repository"); return null; } // Get resource org.sonar.api.resources.File resource = org.sonar.api.resources.File.fromIOFile( new File(realm.getName(), soul.getName()), this.project); if (null == this.context.getResource(resource)) { AftermathResultAnalysis.LOG.warn( "Cannot get resource for realm [" + realm.getName() + "] soul [" + soul.getName() + "]"); return null; } // Create violation Violation violation = Violation.create(rule, resource); violation.setLineId(sin.getYear()); violation.setMessage(sin.getMessage()); violation.setSeverity(AftermathSeverityMap.getSeverity(sin.getSeverity())); // AftermathResultAnalysis.LOG.info("- Violation created: " + violation.toString()); return violation; }
@Test public void shouldIndexTreeOfResources() { Directory directory = new Directory("org/foo"); File file = new File("org/foo/Bar.java"); file.setLanguage(Java.INSTANCE); assertThat(index.index(directory), is(true)); assertThat(index.index(file, directory), is(true)); File fileRef = new File("org/foo/Bar.java"); assertThat(index.getResource(fileRef).getKey(), is("org/foo/Bar.java")); assertThat(index.getResource(fileRef).getLanguage(), is((Language) Java.INSTANCE)); assertThat(index.isIndexed(fileRef, true), is(true)); assertThat(index.isExcluded(fileRef), is(false)); assertThat(index.getChildren(fileRef).size(), is(0)); assertThat(index.getParent(fileRef), is(Directory.class)); }
private Bucket getBucket(@Nullable Resource reference) { if (reference == null) { return null; } if (StringUtils.isNotBlank(reference.getKey())) { return buckets.get(reference); } String relativePathFromSourceDir = null; boolean isTest = false; boolean isDir = false; if (reference instanceof File) { File referenceFile = (File) reference; isTest = Qualifiers.UNIT_TEST_FILE.equals(referenceFile.getQualifier()); relativePathFromSourceDir = referenceFile.relativePathFromSourceDir(); } else if (reference instanceof Directory) { isDir = true; Directory referenceDir = (Directory) reference; relativePathFromSourceDir = referenceDir.relativePathFromSourceDir(); if (Directory.ROOT.equals(relativePathFromSourceDir)) { relativePathFromSourceDir = ""; } } if (relativePathFromSourceDir != null) { // Resolve using deprecated key List<String> dirs; ProjectDefinition projectDef = projectTree.getProjectDefinition(getProject()); if (isTest) { dirs = projectDef.getTestDirs(); } else { dirs = projectDef.getSourceDirs(); } for (String src : dirs) { java.io.File dirOrFile = pathResolver.relativeFile(projectDef.getBaseDir(), src); java.io.File abs = new java.io.File(dirOrFile, relativePathFromSourceDir); Bucket b = getBucket( isDir ? Directory.fromIOFile(abs, getProject()) : File.fromIOFile(abs, getProject())); if (b != null) { return b; } } } return null; }
public class DuplicationPersisterTest extends AbstractDaoTestCase { @org.junit.Rule public ExpectedException thrown = ExpectedException.none(); public static final int FILE_SNAPSHOT_ID = 3003; DuplicationPersister duplicationPersister; RuleFinder ruleFinder = mock(RuleFinder.class); File aFile = File.create("org/foo/Bar.java"); Snapshot fileSnapshot = snapshot(FILE_SNAPSHOT_ID); private DuplicationCache duplicationCache; @Before public void mockResourcePersister() { duplicationCache = mock(DuplicationCache.class); ResourceCache resourceCache = mock(ResourceCache.class); BatchResource batchResource = mock(BatchResource.class); when(batchResource.resource()).thenReturn(aFile); when(batchResource.snapshotId()).thenReturn(FILE_SNAPSHOT_ID); when(resourceCache.get("foo:org/foo/Bar.java")).thenReturn(batchResource); MetricFinder metricFinder = mock(MetricFinder.class); when(metricFinder.findByKey(CoreMetrics.DUPLICATIONS_DATA_KEY)) .thenReturn(CoreMetrics.DUPLICATIONS_DATA.setId(2)); duplicationPersister = new DuplicationPersister( getMyBatis(), ruleFinder, resourceCache, duplicationCache, metricFinder); } @Test public void should_insert_duplications() { setupData("empty"); Duplication.Block originBlock = new Duplication.Block("foo:org/foo/Bar.java", 1, 4); DefaultDuplication group = new DefaultDuplication().setOriginBlock(originBlock); group.duplicates().add(new Duplication.Block("foo:org/foo/Foo.java", 5, 9)); when(duplicationCache.componentKeys()).thenReturn(Arrays.asList("foo:org/foo/Bar.java")); when(duplicationCache.byComponent("foo:org/foo/Bar.java")).thenReturn(Arrays.asList(group)); duplicationPersister.persist(); checkTables("shouldInsertDuplication", "project_measures"); } private static Snapshot snapshot(int id) { Snapshot snapshot = mock(Snapshot.class); when(snapshot.getId()).thenReturn(id); return snapshot; } }
@Override public <P extends Perspective> P as(Class<P> perspectiveClass, InputPath inputPath) { Resource r; if (inputPath instanceof InputDir) { r = Directory.create(((InputDir) inputPath).relativePath()); } else if (inputPath instanceof InputFile) { r = File.create(((InputFile) inputPath).relativePath()); } else { throw new IllegalArgumentException("Unknow input path type: " + inputPath); } return as(perspectiveClass, r); }
private void save(Collection<SourceCode> squidSourceFiles) { for (SourceCode squidSourceFile : squidSourceFiles) { SourceFile squidFile = (SourceFile) squidSourceFile; File sonarFile = File.fromIOFile(new java.io.File(squidFile.getKey()), project); saveMeasures(sonarFile, squidFile); saveFunctionsComplexityDistribution(sonarFile, squidFile); saveFilesComplexityDistribution(sonarFile, squidFile); saveViolations(sonarFile, squidFile); } }
private void createViolation(SMInputCursor violationsCursor, Rule currentRule) throws XMLStreamException { org.sonar.api.resources.File sonarFile = org.sonar.api.resources.File.fromIOFile( new File(violationsCursor.getAttrValue("Source")), project); if (context.isIndexed(sonarFile, false)) { Violation violation = Violation.create(currentRule, sonarFile); String lineNumber = violationsCursor.getAttrValue("LineNumber"); if (lineNumber != null) { violation.setLineId(Integer.parseInt(lineNumber)); } violation.setMessage(violationsCursor.collectDescendantText().trim()); violation.setSeverity(currentRule.getSeverity()); context.saveViolation(violation); } else { LOG.debug("Violation could not be saved, associated resource not indexed " + sonarFile); } }
@Test public void test_measure_coder() throws Exception { Resource file1 = File.create("foo/bar/File1.txt").setEffectiveKey("struts:foo/bar/File1.txt"); Measure measure = new Measure(CoreMetrics.NCLOC, 3.14); measure.setData("data"); measure.setAlertStatus(Level.ERROR); measure.setAlertText("alert"); measure.setDate(new Date()); measure.setDescription("description"); measure.setPersistenceMode(null); measure.setPersonId(3); measure.setUrl("http://foo"); measure.setVariation1(11.0); measure.setVariation2(12.0); measure.setVariation3(13.0); measure.setVariation4(14.0); measure.setVariation5(15.0); measureCache.put(file1, measure); Measure savedMeasure = measureCache.byResource(file1).iterator().next(); assertThat(EqualsBuilder.reflectionEquals(measure, savedMeasure)).isTrue(); }
public void saveMeasures(final Map<String, List<Measure>> measures) { if (measures == null) { return; } for (Map.Entry<String, List<Measure>> entry : measures.entrySet()) { final org.sonar.api.resources.File objcfile = org.sonar.api.resources.File.fromIOFile( new File(project.getFileSystem().getBasedir(), entry.getKey()), project); if (fileExists(sensorContext, objcfile)) { for (Measure measure : entry.getValue()) { try { LoggerFactory.getLogger(getClass()) .debug("Save measure {} for file {}", measure.getMetric().getName(), objcfile); sensorContext.saveMeasure(objcfile, measure); } catch (Exception e) { LoggerFactory.getLogger(getClass()) .error(" Exception -> {} -> {}", entry.getKey(), measure.getMetric().getName()); } } } } }