Java Code Examples for org.apache.commons.io.FileUtils#readFileToString()

The following examples show how to use org.apache.commons.io.FileUtils#readFileToString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CountBasesSparkIntegrationTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider = "countBases", groups = "spark")
public void countBases(final String fileName, final String referenceFileName, final long expectedCount) throws Exception {
    final File unsortedBam = new File(getTestDataDir(), fileName);
    final File outputTxt = createTempFile("count_bases", ".txt");
    ArgumentsBuilder args = new ArgumentsBuilder();
    args.addInput(unsortedBam);
    args.addOutput(outputTxt);
    if (null != referenceFileName) {
        final File ref = new File(getTestDataDir(), referenceFileName);
        args.addReference(ref);
    }
    this.runCommandLine(args.getArgsArray());

    final String readIn = FileUtils.readFileToString(outputTxt.getAbsoluteFile(), StandardCharsets.UTF_8);
    Assert.assertEquals((int) Integer.valueOf(readIn), expectedCount);
}
 
Example 2
Source File: XMLConfigurationProviderTest.java    From walkmod-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testAddConfigurationParameterWithChainFilter() throws Exception {
   AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, null,
         null, null, false);

   File aux = new File("src/test/resources/xmlparams");
   aux.mkdirs();
   File xml = new File(aux, "walkmod.xml");
   XMLConfigurationProvider prov = new XMLConfigurationProvider(xml.getPath(), false);
   try {
      prov.createConfig();

      TransformationConfig transfCfg = command.buildTransformationCfg();
      prov.addTransformationConfig("mychain", null, transfCfg, false, null, null);
      prov.setWriter("mychain", "eclipse-writer", null, false, null);
      prov.addConfigurationParameter("testParam", "hello", "eclipse-writer", null, null, "mychain", false);

      String output = FileUtils.readFileToString(xml);
      System.out.println(output);

      Assert.assertTrue(output.contains("testParam") && output.contains("hello"));
   } finally {
      FileUtils.deleteDirectory(aux);
   }
}
 
Example 3
Source File: DownloadTest.java    From gradle-download-task with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if multiple files can be downloaded to a directory
 * @throws Exception if anything goes wrong
 */
@Test
public void downloadMultipleFiles() throws Exception {
    Download t = makeProjectAndTask();
    t.src(Arrays.asList(wireMockRule.url(TEST_FILE_NAME),
            wireMockRule.url(TEST_FILE_NAME2)));

    File dst = folder.newFolder();
    t.dest(dst);
    t.execute();

    String dstContents = FileUtils.readFileToString(
            new File(dst, TEST_FILE_NAME));
    assertEquals(CONTENTS, dstContents);
    String dstContents2 = FileUtils.readFileToString(
            new File(dst, TEST_FILE_NAME2));
    assertEquals(CONTENTS2, dstContents2);
}
 
Example 4
Source File: NpmLockfileExtractor.java    From hub-detect with Apache License 2.0 6 votes vote down vote up
public Extraction extract(final File directory, final File lockfile, final Optional<File> packageJson) {
    try {
        final boolean includeDev = detectConfiguration.getBooleanProperty(DetectProperty.DETECT_NPM_INCLUDE_DEV_DEPENDENCIES, PropertyAuthority.None);

        String lockText = FileUtils.readFileToString(lockfile, StandardCharsets.UTF_8);
        Optional<String> packageText = Optional.empty();
        if (packageJson.isPresent()) {
            packageText = Optional.of(FileUtils.readFileToString(packageJson.get(), StandardCharsets.UTF_8));
        }

        final NpmParseResult result = npmLockfileParser.parse(directory.getCanonicalPath(), packageText, lockText, includeDev);

        return new Extraction.Builder().success(result.codeLocation).projectName(result.projectName).projectVersion(result.projectVersion).build();

    } catch (final IOException e) {
        return new Extraction.Builder().exception(e).build();
    }
}
 
Example 5
Source File: WalkmodDispatcherTest.java    From walkmod-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testScript() throws Exception {
    File tmp = new File("src/test/resources/add-script").getAbsoluteFile();
    tmp.mkdirs();
    File walkmodCfg = new File(tmp, "walkmod.xml");
    walkmodCfg.delete();
    String scriptPath = new File("src/test/resources/scripts/myscript.groovy").getAbsolutePath();
    String code = "public class Foo { public String bar; }";
    File srcDir = new File(tmp, "src/main/java");
    srcDir.mkdirs();
    File srcFile = new File(srcDir, "Foo.java").getAbsoluteFile();
    FileUtils.write(srcFile, code);

    String userDir = new File(System.getProperty("user.dir")).getCanonicalPath();
    System.setProperty("user.dir", tmp.getAbsolutePath());

    try {
        run(new String[] { "add", "--name=private-fields", "-Dlocation=" + scriptPath, "script" });
        run(new String[] { "apply" });
        String newContent = FileUtils.readFileToString(srcFile);
        Assert.assertTrue(newContent.contains("private String"));
    } finally {
        System.setProperty("user.dir", userDir);
    }

}
 
Example 6
Source File: HTMLBoilerplateRemoval.java    From dkpro-c4corpus with Apache License 2.0 6 votes vote down vote up
public static void processHtmlFile(File input, File outFile, boolean keepMinimalHtml)
        throws IOException
{
    // read the html file
    String html = FileUtils.readFileToString(input, "utf-8");

    // boilerplate removal
    String cleanText;
    if (keepMinimalHtml) {
        cleanText = boilerPlateRemoval.getMinimalHtml(html, null);
    }
    else {
        cleanText = boilerPlateRemoval.getPlainText(html, null);
    }

    // write to the output file
    PrintWriter writer = new PrintWriter(outFile, "utf-8");
    writer.write(cleanText);

    writer.close();
}
 
Example 7
Source File: AutomaticFileCWWorker.java    From wpcleaner with Apache License 2.0 6 votes vote down vote up
/** 
 * Compute the value to be returned by the <code>get</code> method. 
 * 
 * @return Object returned by the <code>get</code> method.
 * @see org.wikipediacleaner.gui.swing.basic.BasicWorker#construct()
 */
@Override
public Object construct() {
  try {
    File file = new File(path);
    String fileContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    Page page = DataManager.getPage(getWikipedia(), file.getName(), null, null, null);
    page.setContents(fileContent);
    PageAnalysis analysis = page.getAnalysis(fileContent, true);
    for (PageElementInternalLink link : analysis.getInternalLinks()) {
      if (!shouldContinue()) {
        return null;
      }
      Page tmpPage = DataManager.getPage(getWikipedia(), link.getLink(), null, null, null);
      analyzePage(tmpPage, selectedAlgorithms, null);
    }
  } catch (APIException | IOException e) {
    return e;
  }
  return null;
}
 
Example 8
Source File: FinalStepJsonProtoHaskellCabalLibrariesTest.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@Test
public void testStep() throws IntegrationException, IOException {
    File jsonProtoFile = new File("src/test/resources/detectables/functional/bazel/jsonProtoForHaskellCabalLibraries.txt");
    String jsonProtoHaskellCabalLibrary = FileUtils.readFileToString(jsonProtoFile, StandardCharsets.UTF_8);
    FinalStepJsonProtoHaskellCabalLibraries step = new FinalStepJsonProtoHaskellCabalLibraries(
        new HaskellCabalLibraryJsonProtoParser(new Gson()),
        new ExternalIdFactory());
    List<String> input = new ArrayList<>(1);
    input.add(jsonProtoHaskellCabalLibrary);

    MutableDependencyGraph graph = step.finish(input);

    Forge hackageForge = new Forge("/", "hackage");
    GraphAssert graphAssert = new GraphAssert(hackageForge, graph);
    graphAssert.hasRootSize(1);
    ExternalId expectedExternalId = new ExternalIdFactory().createNameVersionExternalId(hackageForge, "colour", "2.3.5");
    graphAssert.hasRootDependency(expectedExternalId);
}
 
Example 9
Source File: ETagTest.java    From gradle-download-task with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if the plugin doesn't download a file if the etag equals
 * the cached one
 * @throws Exception if anything goes wrong
 */
@Test
public void dontDownloadIfEqual() throws Exception {
    String etag = "\"foobar\"";

    wireMockRule.stubFor(get(urlEqualTo("/" + TEST_FILE_NAME))
            .withHeader("If-None-Match", equalTo(etag))
            .willReturn(aResponse()
                    .withStatus(304)));

    Download t = makeProjectAndTask();
    t.src(wireMockRule.url(TEST_FILE_NAME));
    File dst = folder.newFile();
    FileUtils.writeStringToFile(dst, "Hello");
    t.dest(dst);
    t.onlyIfModified(true);
    t.useETag(true);

    prepareCachedETagsFile(t.getCachedETagsFile(), etag);

    t.compress(false);
    t.execute();

    String dstContents = FileUtils.readFileToString(dst);
    assertEquals("Hello", dstContents);
    assertNotEquals(CONTENTS, dstContents);
}
 
Example 10
Source File: YAMLConfigurationProviderTest.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddIncludesToReaderAndWriter() throws Exception {
   AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, null,
         null, null, false);
   File file = new File("src/test/resources/yaml/addIncludes.yml");
   if (file.exists()) {
      file.delete();
   }
   file.createNewFile();
   FileUtils.write(file, "");

   YAMLConfigurationProvider prov = new YAMLConfigurationProvider(file.getPath());
   try {
      prov.createConfig();

      TransformationConfig transfCfg = command.buildTransformationCfg();
      prov.addTransformationConfig("mychain", null, transfCfg, false, null, null);
      prov.setWriter("mychain", "eclipse-writer", null, false, null);
      prov.addIncludesToChain("mychain", Arrays.asList("foo"), false, true, true);

      String output = FileUtils.readFileToString(file);
      System.out.println(output);

      Assert.assertTrue(output.contains("foo"));
   } finally {
      if (file.exists()) {
         file.delete();
      }
   }
}
 
Example 11
Source File: SeedFileUtil.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
public static String readOrCreateSeedsFile(File file) {
	try {
		if (file.exists()) {
			return FileUtils.readFileToString(file);
		} else {
			String ip = InetAddress.getLocalHost().getHostAddress();
			FileUtils.writeStringToFile(file, ip);
			return ip;
		}
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 12
Source File: EnvReplacer.java    From oodt with Apache License 2.0 5 votes vote down vote up
public void doEnvReplace() throws IOException {
    if (this.filepath != null && this.filepath.exists()
            && this.filepath.canWrite()) {

        String existingFileStr = FileUtils.readFileToString(this.filepath);
        String envReplacedFileStr = PathUtils
                .replaceEnvVariables(existingFileStr);
        FileUtils.writeStringToFile(this.filepath, envReplacedFileStr);

    }

}
 
Example 13
Source File: YAMLConfigurationProviderTest.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddModulesToConfig() throws Exception {
   List<String> list = new LinkedList<String>();
   list.add("module1");

   File file = new File("src/test/resources/yaml/addmodules.yml");
   if (file.exists()) {
      file.delete();
   }
   file.createNewFile();
   FileUtils.write(file, "");

   try {
      YAMLConfigurationProvider provider = new YAMLConfigurationProvider(file.getPath());
      Configuration conf = new ConfigurationImpl();
      provider.init(conf);

      provider.addModules(list);

      String output = FileUtils.readFileToString(file);

      String desiredOutput = "modules:\n";
      desiredOutput += "- \"module1\"";

      Assert.assertEquals(desiredOutput, output);
   } finally {
      if (file.exists()) {
         file.delete();
      }
   }
}
 
Example 14
Source File: InjectScript.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private void loadSampleScript() {
    try {
        File file = new File("Configuration" + File.separator + "SampleScript.java");
        if (file.exists()) {
            sampleCode = FileUtils.readFileToString(file, Charset.defaultCharset());
        } else {
            sampleCode = "";
        }
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
}
 
Example 15
Source File: YAMLConfigurationProviderTest.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddTransformationToPath() throws Exception {
   AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", "mychain", false, null, "src",
         null, null, false);
   File file = new File("src/test/resources/yaml/addtransformation.yml");
   if (file.exists()) {
      file.delete();
   }
   file.createNewFile();
   FileUtils.write(file, "");
   try {
      YAMLConfigurationProvider provider = new YAMLConfigurationProvider(file.getPath());
      Configuration conf = new ConfigurationImpl();
      provider.init(conf);

      TransformationConfig transCfg = command.buildTransformationCfg();

      provider.addTransformationConfig("mychain", "src", transCfg, false, null, null);
      String output = FileUtils.readFileToString(file);

      Assert.assertTrue(output.contains("src"));
   } finally {
      if (file.exists()) {
         file.delete();
      }
   }
}
 
Example 16
Source File: GoFileConfigDataSourceIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotCorruptTheCruiseConfigXml() throws Exception {
    File file = dataSource.fileLocation();
    String originalCopy = FileUtils.readFileToString(file, UTF_8);

    try {
        dataSource.write("abc", false);
        fail("Should not allow us to write an invalid config");
    } catch (Exception e) {
        assertThat(e.getMessage(), containsString("Content is not allowed in prolog"));
    }

    assertThat(readFileToString(file, UTF_8), is(originalCopy));
}
 
Example 17
Source File: AnalyzeJSPFileRuleProvider.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
private Iterable<ClassReference> getClassReferences(TypeReferenceService service, JspSourceFileModel sourceFile) throws IOException
{
    String source = FileUtils.readFileToString(sourceFile.asFile());

    List<ClassReference> results = new ArrayList<>();
    results.addAll(findImports(source));
    results.addAll(findTaglib(source));
    return results;
}
 
Example 18
Source File: IterateJsonPathTest.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
@BeforeClass(alwaysRun = true)
public void uploadSynapseConfig() throws Exception {
    super.init();
    input = FileUtils.readFileToString(new File(getESBResourceLocation() + "/json/inputESBIterateJson.json"));
    loadESBConfigurationFromClasspath("/artifacts/ESB/mediatorconfig/iterate/iterate_jsonpath.xml");
}
 
Example 19
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 4 votes vote down vote up
String contentOf(String path) throws IOException {
    return FileUtils.readFileToString(file(path), "UTF-8");
}
 
Example 20
Source File: AbstractFileEventTest.java    From archiva with Apache License 2.0 4 votes vote down vote up
protected String readFile( Path file )
    throws IOException
{
    return FileUtils.readFileToString( file.toFile(), Charset.forName( "UTF-8" ) );
}