Example usage for org.apache.commons.io FileUtils toFile

List of usage examples for org.apache.commons.io FileUtils toFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils toFile.

Prototype

public static File toFile(URL url) 

Source Link

Document

Convert from a URL to a File.

Usage

From source file:org.sonar.plugins.groovy.codenarc.CodeNarcSensorTest.java

@Test
public void should_parse_but_not_add_issue_if_issuable_not_found() {
    when(ruleFinder.find(any(RuleQuery.class))).thenReturn(Rule.create());

    FileSystem fileSystem = mock(FileSystem.class);
    when(fileSystem.predicates()).thenReturn(mock(FilePredicates.class));
    when(fileSystem.inputFile(any(FilePredicate.class))).thenReturn(mock(InputFile.class));

    File report = FileUtils.toFile(getClass().getResource("parsing/sample.xml"));
    when(settings.getString(GroovyPlugin.CODENARC_REPORT_PATH)).thenReturn(report.getAbsolutePath());

    when(perspectives.as(any(Class.class), any(InputFile.class))).thenReturn(null);

    sensor = new CodeNarcSensor(settings, perspectives, moduleFileSystem, fileSystem, profile, ruleFinder);
    sensor.analyse(project, context);//from  ww w.  j a va  2  s . co  m

    verify(issuable, never()).addIssue(any(Issue.class));
}

From source file:org.sonar.plugins.groovy.codenarc.CodeNarcXMLParserTest.java

@Test
public void testCodeNarcReportParser() {
    File fileToParse = FileUtils.toFile(getClass().getResource("CodeNarcXMLParserTest/sample.xml"));

    CodeNarcXMLParser parser = new CodeNarcXMLParser(null);
    parser = spy(parser);//  www  .  j a va 2  s  .c om
    doNothing().when(parser).log((SensorContext) anyObject(), anyString(), anyString(), anyInt(), anyString());

    SensorContext context = mock(SensorContext.class);
    parser.parseAndLogCodeNarcResults(fileToParse, context);

    verify(parser).log(eq(context), eq("EmptyIfStatement"), eq("org/codenarc/sample/domain/SampleDomain"),
            eq(21), eq(""));
    verify(parser).log(eq(context), eq("EmptyWhileStatement"), eq("org/codenarc/sample/service/NewService"),
            eq(18), eq(""));
    verify(parser, times(2)).log(eq(context), anyString(), eq("org/codenarc/sample/service/NewService"),
            anyInt(), anyString());
    verify(parser, times(16)).log(eq(context), anyString(), anyString(), anyInt(), anyString());
}

From source file:org.sonar.plugins.groovy.codenarc.CodeNarcXMLParserTest.java

/**
 * See http://jira.codehaus.org/browse/SONARPLUGINS-620
 *//*  w ww  .j a  va 2 s  . co m*/
@Test
public void shouldNotFailWhenLineNumberNotSpecified() {
    File fileToParse = FileUtils
            .toFile(getClass().getResource("CodeNarcXMLParserTest/line-number-not-specified.xml"));

    CodeNarcXMLParser parser = new CodeNarcXMLParser(null);
    parser = spy(parser);
    doNothing().when(parser).log((SensorContext) anyObject(), anyString(), anyString(), anyInt(), anyString());

    SensorContext context = mock(SensorContext.class);
    parser.parseAndLogCodeNarcResults(fileToParse, context);

    verify(parser).log(eq(context), eq("CyclomaticComplexity"), eq("org/example/Example"), (Integer) eq(null),
            eq("The cyclomatic complexity for class [org.example.Example] is [27.0]"));
}

From source file:org.sonar.plugins.groovy.gmetrics.GMetricsXMLParserTest.java

@Test
public void testGMetricsReportParser() {
    SensorContext context = mock(SensorContext.class);

    File fileToParse = FileUtils
            .toFile(getClass().getResource("/org/sonar/plugins/groovy/gmetrics/sample.xml"));
    new GMetricsXMLParser().parseAndProcessGMetricsResults(fileToParse, context);

    GroovyFile file = new GroovyFile("org.gmetrics.analyzer.FilesystemSourceAnalyzer");
    verify(context).saveMeasure(eq(file), eq(CoreMetrics.FUNCTIONS), eq(7.0));
    verify(context).saveMeasure(eq(file), eq(CoreMetrics.COMPLEXITY), eq(13.0));
    verify(context).saveMeasure(eq(file), argThat(
            new IsMeasure(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION, "1=4;2=2;4=1;6=0;8=0;10=0;12=0")));
    verify(context).saveMeasure(eq(file), argThat(
            new IsMeasure(CoreMetrics.CLASS_COMPLEXITY_DISTRIBUTION, "0=0;5=0;10=1;20=0;30=0;60=0;90=0")));
}

From source file:org.sonar.plugins.groovy.TestUtils.java

/**
 * Search for a test resource in the classpath. For example getResource("org/sonar/MyClass/foo.txt");
 *
 * @param path the starting slash is optional
 * @return the resource. Null if resource not found
 *//* www . j av  a2 s . c o m*/
public static File getResource(String path) {
    String resourcePath = path;
    if (!resourcePath.startsWith("/")) {
        resourcePath = "/" + resourcePath;
    }
    URL url = TestUtils.class.getResource(resourcePath);
    if (url != null) {
        return FileUtils.toFile(url);
    }
    return null;
}

From source file:org.sonar.plugins.l10n.L10nHackyPropertiesUpdater.java

public static void main(String[] args) throws ConfigurationException, IOException {
    URL l10nRoot = FrenchPackPlugin.class.getResource(BundleSynchronizedMatcher.L10N_PATH);

    Collection<File> bundles = FileUtils.listFiles(FileUtils.toFile(l10nRoot), new String[] { "properties" },
            false);//www  .  jav a 2  s. c o  m

    for (File localizedBundle : bundles) {
        String originalVersion = localizedBundle.getName().replaceFirst("_fr\\.", ".");
        System.out.println("Processing " + localizedBundle + " looking for " + originalVersion);
        URL originalBundle = FrenchPackPlugin.class
                .getResource(BundleSynchronizedMatcher.L10N_PATH + originalVersion);
        if (originalBundle == null) {
            System.out.println("\tOriginal bundle not found");
        } else {
            System.out.println("\tOriginal bundle found, let's try to update the localized version");
            Properties localizedProps = new Properties();
            localizedProps.load(new FileInputStream(localizedBundle));

            PropertiesConfiguration config = new PropertiesConfiguration();
            PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
            layout.load(new InputStreamReader(FrenchPackPlugin.class
                    .getResourceAsStream(BundleSynchronizedMatcher.L10N_PATH + originalVersion)));

            for (@SuppressWarnings("unchecked")
            Iterator<String> it = config.getKeys(); it.hasNext();) {
                String key = it.next();
                Object localizedValue = localizedProps.get(key);
                if (localizedValue != null) {
                    config.setProperty(key, localizedValue);
                } else {
                    System.out.println("Nothing found for " + key);
                    String currentValue = config.getString(key);
                    config.setProperty(key, currentValue + " <== TODO");
                }
            }

            layout.save(new FileWriter(localizedBundle));

            System.out.println("\tFixing spaces");
            fixSpacesAroundEqualsAndScrewUpEncoding(localizedBundle);
            System.out.println("OK: file " + localizedBundle + " contains ready-to-translate updated file.");
        }
    }

}

From source file:org.sonar.plugins.php.codesniffer.PhpCodeSnifferViolationsXmlParserTest.java

@Test
public void shouldReturnViolationsFromExistingFile() throws URISyntaxException, XMLStreamException {
    PhpCodeSnifferViolationsXmlParser parser = new PhpCodeSnifferViolationsXmlParser();
    String reportFile = "/org/sonar/plugins/php/codesniffer/violations/parser/codesniffer-simple-result.xml";
    File xmlFile = FileUtils.toFile(getClass().getResource(reportFile));
    List<PhpCodeSnifferViolation> violations = parser.getViolations(xmlFile);
    assertTrue(violations != null && !violations.isEmpty());
    assertEquals(violations.size(), 2);/*from www .j a v a  2 s  .c  o m*/
}

From source file:org.sonar.plugins.php.codesniffer.PhpCodeSnifferViolationsXmlParserTest.java

@Test(expected = SonarException.class)
public void shouldThrowExceptionOnNonExistingFile() throws URISyntaxException, XMLStreamException {
    PhpCodeSnifferViolationsXmlParser parser = new PhpCodeSnifferViolationsXmlParser();
    String reportFile = "BLABLALBLALBA.XML";
    File xmlFile = FileUtils.toFile(getClass().getResource(reportFile));
    parser.getViolations(xmlFile);//from  w  w  w .  j a v a  2 s  . co m
}

From source file:org.sonar.plugins.php.cpd.PhpCpdResultParserTest.java

@Test
public void shouldParse() throws URISyntaxException, XMLStreamException {
    SensorContext context = mock(SensorContext.class);
    Project project = getMockProject("C:/php/math-php-test/source/src/");
    PhpCpdResultParser parser = new PhpCpdResultParser(project, context);
    String reportFile = "/org/sonar/plugins/php/cpd/php-cpd.xml";
    File xmlFile = FileUtils.toFile(getClass().getResource(reportFile));
    parser.parse(xmlFile);/* w  ww  . ja  va2 s .  c  om*/

    PhpFile mathPhp = new PhpFile("Math.php");
    verify(context).saveMeasure(mathPhp, DUPLICATED_FILES, 1.0);
    verify(context).saveMeasure(mathPhp, DUPLICATED_LINES, 0.0);
    verify(context).saveMeasure(mathPhp, DUPLICATED_BLOCKS, 0.0);

}

From source file:org.sonar.plugins.pmd.PmdExecutorTest.java

@Test
public void executeOnManySourceDirs() throws URISyntaxException, IOException, PMDException {
    Project project = new Project("two-source-dirs");

    ProjectFileSystem fs = mock(ProjectFileSystem.class);
    File root = new File(
            getClass().getResource("/org/sonar/plugins/pmd/PmdExecutorTest/executeOnManySourceDirs/").toURI());
    when(fs.getSourceFiles(Java.INSTANCE)).thenReturn(
            Arrays.asList(new File(root, "src1/FirstClass.java"), new File(root, "src2/SecondClass.java")));
    when(fs.getSourceCharset()).thenReturn(Charset.forName("UTF-8"));
    when(fs.getSonarWorkingDirectory()).thenReturn(new File("target"));
    project.setFileSystem(fs);//from w w w. j  ava  2  s .co m

    PmdConfiguration conf = mock(PmdConfiguration.class);
    File file = FileUtils.toFile(
            getClass().getResource("/org/sonar/plugins/pmd/PmdExecutorTest/executeOnManySourceDirs/pmd.xml")
                    .toURI().toURL());
    when(conf.getRulesets()).thenReturn(Arrays.asList(file.getAbsolutePath()));

    PmdExecutor executor = new PmdExecutor(project, conf);
    File xmlReport = executor.execute();
    assertThat(xmlReport.exists(), is(true));

    String xml = FileUtils.readFileToString(xmlReport);

    // errors on the two source files
    assertThat(StringUtils.countMatches(xml, "<file"), is(2));
    assertThat(StringUtils.countMatches(xml, "<violation"), greaterThan(2));
}