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

The following examples show how to use org.apache.commons.io.FileUtils#write() . 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: Rgaa3Extractor.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void extractLevelFromCriterionAndWrite(Document doc) throws IOException {
    StringBuilder crit = new StringBuilder();
    for (Element el : doc.select(CRITERION_SELECTOR)) {
        if (StringUtils.isNotBlank(el.id())) {
            crit.append(el.id().replace("crit", "Rgaa30"));
            crit.append("=");
            String content = el.html();
            content = content.substring(content.indexOf("] ") + 1);
            content = extractRuleContent(content);
            crit.append(content);
            crit.append("\n");
            String level = el.text().substring(el.text().indexOf("[")+1, el.text().indexOf("]"));
            levelFromCrit.put(el.id().replaceAll("crit-", ""), level);
        }
    }
    if (writeCritInFile) {
        FileUtils.write(new File(CRITERION_I18N_FILE_PATH), crit.toString());
    }
}
 
Example 2
Source File: BuildWorkTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
void shouldReportUploadMessageWhenUpload() throws Exception {
    String destFolder = "dest\\test\\sub-folder";
    final String url = String.format("%s/remoting/files/%s/%s/%s/%s/%s/%s?attempt=1&buildId=0", SERVER_URL, PIPELINE_NAME, PIPELINE_LABEL, STAGE_NAME, STAGE_COUNTER, JOB_PLAN_NAME,
            destFolder.replaceAll("\\\\", "/"));

    String artifactFile = "example.txt";
    File basedir = new File("pipelines/pipeline1");

    FileUtils.write(new File(basedir, artifactFile), "foo", StandardCharsets.UTF_8);

    buildWork = (BuildWork) getWork(willUploadToDest(artifactFile, destFolder), PIPELINE_NAME);
    com.thoughtworks.go.remote.work.HttpServiceStub httpService = new com.thoughtworks.go.remote.work.HttpServiceStub(HttpServletResponse.SC_OK);
    artifactManipulator = new GoArtifactsManipulatorStub(httpService);

    buildWork.doWork(environmentVariableContext, new AgentWorkContext(agentIdentifier, buildRepository, artifactManipulator, new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie"), packageRepositoryExtension, scmExtension, taskExtension, null, pluginRequestProcessorRegistry));

    String actual = artifactManipulator.consoleOut();

    assertThat(actual.toLowerCase()).contains(("Uploading artifacts from " + new File(basedir, artifactFile).getCanonicalPath()).toLowerCase());

    Map<String, File> uploadedFiles = httpService.getUploadedFiles();

    assertThat(uploadedFiles.size()).isEqualTo(1);
    assertThat(uploadedFiles.get(url).getAbsolutePath()).contains(artifactFile + ".zip");
}
 
Example 3
Source File: SharedFolderWithWritePermissionUpdateTest.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Test
public void testSynchronizeAddSubfileFromBUpdateAtA() throws NoSessionException, NoPeerConnectionException, IOException,
		IllegalArgumentException, IllegalArgumentException, GetFailedException {
	File fileFromBAtB = FileTestUtil.createFileRandomContent("subfile1FromB", new Random().nextInt(MAX_NUM_CHUNKS) + 1,
			subFolderB);
	logger.info("Upload a new file '{}' from B.", fileFromBAtB.toString());
	UseCaseTestUtil.uploadNewFile(network.get(1), fileFromBAtB);

	logger.info("Wait till new file '{}' gets synchronized with A.", fileFromBAtB.toString());
	File fileFromBAtA = new File(subFolderA, fileFromBAtB.getName());
	waitTillSynchronized(fileFromBAtA, true);

	logger.info("Update file '{}' at A.", fileFromBAtB.toString());
	long lastUpdated = fileFromBAtA.lastModified();
	FileUtils.write(fileFromBAtA, randomString(), false);
	byte[] newHash = HashUtil.hash(fileFromBAtA);
	UseCaseTestUtil.uploadNewVersion(network.get(0), fileFromBAtA);

	logger.info("Wait till update of file '{}' gets synchronized with B.", fileFromBAtB.toString());
	waitTillSynchronizedUpdating(fileFromBAtB, lastUpdated);
	compareFiles(fileFromBAtA, fileFromBAtB);
	checkFileIndex(fileFromBAtA, fileFromBAtB, newHash);
}
 
Example 4
Source File: SharedFolderWithWritePermissionUpdateTest.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Test
public void testSynchronizeAddFileFromAUpdateAtB() throws NoSessionException, NoPeerConnectionException, IOException,
		IllegalArgumentException, IllegalArgumentException, GetFailedException {
	File fileFromAAtA = FileTestUtil.createFileRandomContent("file2FromA", new Random().nextInt(MAX_NUM_CHUNKS) + 1,
			sharedFolderA);
	logger.info("Upload a new file '{}' from A.", fileFromAAtA.toString());
	UseCaseTestUtil.uploadNewFile(network.get(0), fileFromAAtA);

	logger.info("Wait till new file '{}' gets synchronized with B.", fileFromAAtA.toString());
	File fileFromAAtB = new File(sharedFolderB, fileFromAAtA.getName());
	waitTillSynchronized(fileFromAAtB, true);

	logger.info("Update file '{}' at B.", fileFromAAtA.toString());
	long lastUpdated = fileFromAAtB.lastModified();
	FileUtils.write(fileFromAAtB, randomString(), false);
	byte[] newHash = HashUtil.hash(fileFromAAtB);
	UseCaseTestUtil.uploadNewVersion(network.get(1), fileFromAAtB);

	logger.info("Wait till update of file '{}' gets synchronized with A.", fileFromAAtA.toString());
	waitTillSynchronizedUpdating(fileFromAAtA, lastUpdated);
	compareFiles(fileFromAAtA, fileFromAAtB);
	checkFileIndex(fileFromAAtA, fileFromAAtB, newHash);
}
 
Example 5
Source File: TestPropertiesFileGenerator.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("This test is to generate the test.properties for new developers.")
public void generatePropertiesFile() throws IOException {
    String propertiesFileName = ResourceLoader.RESOURCE_DIR + "/" + ResourceLoader.DEFAULT_PROPERTIES_FILE_LOCATION;
    System.out.println("Generating file: " + propertiesFileName + "..");

    File testPropertiesFile = new File(propertiesFileName);
    if (!testPropertiesFile.exists()) {
        boolean successfullyCreated = testPropertiesFile.createNewFile();
        if (!successfullyCreated) {
            System.out.println("There was a problem creating the file '" + propertiesFileName + "'.");
            return;
        }

        StringBuilder dataBuilder = new StringBuilder();
        for (TestPropertyKey propertyKey : TestPropertyKey.values()) {
            dataBuilder.append(propertyKey.getPropertyKey());
            dataBuilder.append('=');
            dataBuilder.append(System.lineSeparator());
        }
        FileUtils.write(testPropertiesFile, dataBuilder.toString(), Charset.defaultCharset(), false);
    } else {
        System.out.println("The file '" + propertiesFileName + "' already exists, please rename or back it up.");
    }
}
 
Example 6
Source File: FileVersionSelectorTest.java    From PeerWasp with MIT License 6 votes vote down vote up
private static void uploadVersions() throws  Exception {
	content = new ArrayList<String>();

	// add an intial file to the network
	file = new File(root, fileName);
	String fileContent = RandomStringUtils.randomAscii(FILE_SIZE);
	content.add(fileContent);
	logger.info("Initial content: {}...", fileContent.substring(0, 10));
	FileUtils.write(file, fileContent);
	client.getFileManager().createAddProcess(file).execute();

	// update and upload
	for(int i = 0; i < NUM_VERSIONS; ++i) {
		Thread.sleep(2000); // sleep such that each file has different timestamp
		fileContent = RandomStringUtils.randomAscii(FILE_SIZE);
		content.add(fileContent);
		logger.info("File version {} content: {}...", i, fileContent.substring(0, 10));
		FileUtils.write(file, fileContent);
		client.getFileManager().createUpdateProcess(file).execute();
	}
}
 
Example 7
Source File: InterpreterModeActionsIT.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startUp() {
  try {
    System.setProperty(ZeppelinConfiguration.ConfVars.ZEPPELIN_HOME.getVarName(), new File("../").getAbsolutePath());
    ZeppelinConfiguration conf = ZeppelinConfiguration.create();
    shiroPath = conf.getRelativeDir(String.format("%s/shiro.ini", conf.getConfDir()));
    interpreterOptionPath = conf.getRelativeDir(String.format("%s/interpreter.json", conf.getConfDir()));
    File shiroFile = new File(shiroPath);
    if (shiroFile.exists()) {
      originalShiro = StringUtils.join(FileUtils.readLines(shiroFile, "UTF-8"), "\n");
    }
    FileUtils.write(shiroFile, authShiro, "UTF-8");

    File interpreterOptionFile = new File(interpreterOptionPath);
    if (interpreterOptionFile.exists()) {
      originalInterpreterOption = StringUtils.join(FileUtils.readLines(interpreterOptionFile, "UTF-8"), "\n");
    }
  } catch (IOException e) {
    LOG.error("Error in InterpreterModeActionsIT startUp::", e);
  }
  ZeppelinITUtils.restartZeppelin();
  driver = WebDriverManager.getWebDriver();
}
 
Example 8
Source File: ConfigConverterUtil.java    From vertx-maven-plugin with Apache License 2.0 5 votes vote down vote up
public static void convertYamlToJson(File yamlFile, File jsonFilePath) throws IOException {
    FileUtils.deleteQuietly(jsonFilePath);
    String content = FileUtils.readFileToString(yamlFile, "UTF-8");
    Yaml yaml = new Yaml();
    Map<Object, Object> map = yaml.load(content);
    JSONObject jsonObject = new JSONObject(map);
    FileUtils.write(jsonFilePath, jsonObject.toString(), "UTF-8");
}
 
Example 9
Source File: SSHClientTest.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testScp() throws Exception {
    if (isRemote == false)
        return;

    SSHClient ssh = new SSHClient(this.hostname, this.port, this.username, this.password);
    File tmpFile = File.createTempFile("test_scp", "", new File("/tmp"));
    tmpFile.deleteOnExit();
    FileUtils.write(tmpFile, "test_scp", Charset.defaultCharset());
    ssh.scpFileToRemote(tmpFile.getAbsolutePath(), "/tmp");
}
 
Example 10
Source File: MappingUtil.java    From hugegraph-loader with Apache License 2.0 5 votes vote down vote up
public static void write(LoadMapping mapping, String path) {
    File file = FileUtils.getFile(path);
    String json = JsonUtil.toJson(mapping);
    try {
        FileUtils.write(file, json, Constants.CHARSET);
    } catch (IOException e) {
        throw new LoadException("Failed to write mapping %s to file '%s'",
                                e, mapping, file);
    }
}
 
Example 11
Source File: S3DataManagerTest.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testZipSourceOneDirEmpty() throws Exception {
    String buildSpecName = "Buildspec.yml";
    File buildSpec = new File("/tmp/source/" + buildSpecName);
    String buildSpecContents = "yo\n";
    FileUtils.write(buildSpec, buildSpecContents);
    File sourceDir = new File("/tmp/source/src");
    sourceDir.mkdir();

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream("/tmp/source.zip"));
    ZipSourceCallable.zipSource(testZipSourceWorkspace, "/tmp/source/", out, "/tmp/source/");
    out.close();

    File zip = new File("/tmp/source.zip");
    assertTrue(zip.exists());

    File unzipFolder = new File("/tmp/folder/");
    unzipFolder.mkdir();
    ZipFile z = new ZipFile(zip.getPath());
    z.extractAll(unzipFolder.getPath());
    assertEquals(2, unzipFolder.list().length);
    assertTrue(Arrays.asList(unzipFolder.list()).contains(buildSpecName));
    assertTrue(Arrays.asList(unzipFolder.list()).contains("src"));
    File extractedBuildSpec = new File(unzipFolder.getPath() + "/" + buildSpecName);
    assertEquals(buildSpecContents, FileUtils.readFileToString(extractedBuildSpec));
    File srcDir = new File(unzipFolder.getPath() + "/src");
    assertTrue(srcDir.isDirectory());
    assertEquals(0, srcDir.list().length);
}
 
Example 12
Source File: Issue294Test.java    From jtwig-core with Apache License 2.0 5 votes vote down vote up
@Test
public void jtwigSupportsAbsolutePaths() throws Exception {
    File baseDir = new File(new File(FileUtils.getTempDirectory(), "jtwig"), "test");
    baseDir.mkdirs();
    File child = new File(baseDir, "child.twig");
    FileUtils.write(child, "{{ var }}");

    File parent = File.createTempFile("jtwig", "test");
    FileUtils.write(parent, "{% extends '"+ escapeJtwig(baseDir.getAbsolutePath() + File.separator)+ "child.twig' %}");

    String result = JtwigTemplate.fileTemplate(parent).render(JtwigModel.newModel()
            .with("var", "Hi"));

    assertThat(result, is("Hi"));
}
 
Example 13
Source File: IngraphDriver.java    From trainbenchmark with Eclipse Public License 1.0 5 votes vote down vote up
public void maybeMeasureMemory() throws IOException {
	final String memPath = bc.getMemoryMeasurementPath();
	if (memPath != null) {
		final MemoryMeter meter = new MemoryMeter();
		final long memoryB = meter.measureDeep(adapter.engine());
		final double memoryMB = memoryB / Math.pow(10, 6);
		final String line = String.join(",",
				Arrays.asList(bc.getToolName(), bc.getQueryVariant(), bc.getFileName(), String.format("%.02f", memoryMB))) + "\n";

		FileUtils.write(new File(memPath), line, Charset.defaultCharset(), true);
	}
}
 
Example 14
Source File: YAMLConfigurationProviderTest.java    From walkmod-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testAddConfigurationParameterWithCategory() throws Exception {
   AddTransformationCommand command = new AddTransformationCommand("imports-cleaner", null, false, null, null, null,
         null, false);

   File file = new File("src/test/resources/yaml/rmchains.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 transformationCfg = command.buildTransformationCfg();
      provider.addTransformationConfig(null, null, transformationCfg, false, null, null);
      provider.addConfigurationParameter("testParam", "hello", "imports-cleaner", "transformation", null, null,
            false);

      String output = FileUtils.readFileToString(file);
      System.out.println(output);
      Assert.assertTrue(output.contains("params") && output.contains("testParam") && output.contains("hello"));
   } finally {
      if (file.exists()) {
         file.delete();
      }
   }
}
 
Example 15
Source File: TaskRunPnpmInstallTest.java    From flow with Apache License 2.0 5 votes vote down vote up
@Test
public void runPnpmInstall_overlayVersionIsPinnedViaPlatform_installedOverlayVersionIsSpecifiedByPlatform()
        throws IOException, ExecutionFailedException {
    File packageJson = new File(getNodeUpdater().npmFolder, PACKAGE_JSON);
    packageJson.createNewFile();

    // Write package json file: dialog doesn't pin its Overlay version which
    // is transitive dependency.
    FileUtils.write(packageJson,
            "{\"dependencies\": {"
                    + "\"@vaadin/vaadin-dialog\": \"2.2.1\"}}",
            StandardCharsets.UTF_8);

    // Platform defines a pinned version
    TaskRunNpmInstall task = createTask(
            "{ \"@vaadin/vaadin-overlay\":\"" + PINNED_VERSION + "\"}");
    task.execute();

    File overlayPackageJson = new File(getNodeUpdater().nodeModulesFolder,
            "@vaadin/vaadin-overlay/package.json");

    // The resulting version should be the one specified via platform
    // versions file
    JsonObject overlayPackage = Json.parse(FileUtils
            .readFileToString(overlayPackageJson, StandardCharsets.UTF_8));
    Assert.assertEquals(PINNED_VERSION,
            overlayPackage.getString("version"));
}
 
Example 16
Source File: FileReaderTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"[object ArrayBuffer]", "8"})
public void readAsArrayBuffer() throws Exception {
    final String html
        = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "    function test() {\n"
        + "      var files = document.testForm.fileupload.files;\n"
        + "      var reader = new FileReader();\n"
        + "      reader.onload = function() {\n"
        + "        alert(reader.result);\n"
        + "        alert(reader.result.byteLength);\n"
        + "      };\n"
        + "      reader.readAsArrayBuffer(files[0]);\n"
        + "    }\n"
        + "  </script>\n"
        + "<head>\n"
        + "<body>\n"
        + "  <form name='testForm'>\n"
        + "    <input type='file' id='fileupload' name='fileupload'>\n"
        + "  </form>\n"
        + "  <button id='testBtn' onclick='test()'>Tester</button>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);

    final File tstFile = File.createTempFile("HtmlUnitReadAsArrayBufferTest", ".txt");
    try {
        FileUtils.write(tstFile, "HtmlUnit", StandardCharsets.UTF_8);

        final String path = tstFile.getCanonicalPath();
        driver.findElement(By.name("fileupload")).sendKeys(path);

        driver.findElement(By.id("testBtn")).click();

        verifyAlerts(driver, getExpectedAlerts());
    }
    finally {
        FileUtils.deleteQuietly(tstFile);
    }
}
 
Example 17
Source File: GatewayAdminTopologyFuncTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test( timeout = TestUtils.LONG_TIMEOUT )
public void testDescriptorCollection() throws Exception {
  LOG_ENTER();

  final String username = "admin";
  final String password = "admin-password";
  final String serviceUrl = clusterUrl + "/api/v1/descriptors";

  final File descriptorsDir = new File(config.getGatewayConfDir(), "descriptors");
  final List<String> clusterNames        = Arrays.asList("clusterOne", "clusterTwo");
  final List<String> descriptorNames     = Arrays.asList("test-descriptor-one", "test-descriptor-two");
  final List<String> descriptorFileNames = Arrays.asList(descriptorNames.get(0) + ".json",
                                                         descriptorNames.get(1) + ".json");

  // Request a listing of all the descriptors with an INCORRECT Accept header
  given()
      .auth().preemptive().basic(username, password)
      .header("Accept", MediaType.APPLICATION_XML)
      .then()
      .statusCode(HttpStatus.SC_NOT_ACCEPTABLE)
      .when().get(serviceUrl);

  // Request a listing of all the descriptors (with the CORRECT Accept header)
  ResponseBody responseBody = given()
                                .auth().preemptive().basic(username, password)
                                .header("Accept", MediaType.APPLICATION_JSON)
                                .then()
                                .statusCode(HttpStatus.SC_OK)
                                .contentType(MediaType.APPLICATION_JSON)
                                .when().get(serviceUrl).body();
  List<String> items = responseBody.path("items");
  assertTrue("Expected no items since the descriptors dir is empty.", items.isEmpty());

  // Manually write a file to the descriptors directory
  File descriptorOneFile = new File(descriptorsDir, descriptorFileNames.get(0));
  FileUtils.write(descriptorOneFile, createDescriptor(clusterNames.get(0)), StandardCharsets.UTF_8);

  // Request a listing of all the descriptors
  responseBody = given()
                  .auth().preemptive().basic(username, password)
                  .header("Accept", MediaType.APPLICATION_JSON)
                  .then()
                  .statusCode(HttpStatus.SC_OK)
                  .contentType(MediaType.APPLICATION_JSON)
                  .when().get(serviceUrl).body();
  items = responseBody.path("items");
  assertEquals("Expected items to include the new file in the shared-providers dir.", 1, items.size());
  assertEquals(descriptorFileNames.get(0), responseBody.path("items[0].name"));
  String href1 = responseBody.path("items[0].href");

  // Manually write another file to the descriptors directory
  File descriptorTwoFile = new File(descriptorsDir, descriptorFileNames.get(1));
  FileUtils.write(descriptorTwoFile, createDescriptor(clusterNames.get(1)), StandardCharsets.UTF_8);

  // Request a listing of all the descriptors
  responseBody = given()
                  .auth().preemptive().basic(username, password)
                  .header("Accept", MediaType.APPLICATION_JSON)
                  .then()
                  .statusCode(HttpStatus.SC_OK)
                  .contentType(MediaType.APPLICATION_JSON)
                  .when().get(serviceUrl).body();
  items = responseBody.path("items");
  assertEquals(2, items.size());
  String descOne = responseBody.path("items[0].name");
  String descTwo = responseBody.path("items[1].name");
  assertTrue(descriptorFileNames.contains(descOne));
  assertTrue(descriptorFileNames.contains(descTwo));

  // Request a specific descriptor with an INCORRECT Accept header
  given()
      .auth().preemptive().basic(username, password)
      .header("Accept", MediaType.APPLICATION_XML)
      .then()
      .statusCode(HttpStatus.SC_NOT_ACCEPTABLE)
      .when().get(href1).body();

  // Request a specific descriptor (with the CORRECT Accept header)
  responseBody = given()
                  .auth().preemptive().basic(username, password)
                  .header("Accept", MediaType.APPLICATION_JSON)
                  .then()
                  .statusCode(HttpStatus.SC_OK)
                  .contentType(MediaType.APPLICATION_JSON)
                  .when().get(href1).body();
  String cluster = responseBody.path("cluster");
  assertEquals(cluster, clusterNames.get(0));

  // Request a specific descriptor, which does NOT exist
  given()
    .auth().preemptive().basic(username, password)
    .header("Accept", MediaType.APPLICATION_JSON)
    .then()
    .statusCode(HttpStatus.SC_NOT_FOUND)
    .when().get(serviceUrl + "/not-a-real-descriptor").body();

  descriptorOneFile.delete();
  descriptorTwoFile.delete();

  LOG_EXIT();
}
 
Example 18
Source File: FileReaderTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("Html \u00dcnit")
public void readAsTextUtf8() throws Exception {
    final String html
        = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "    function test() {\n"
        + "      var files = document.testForm.fileupload.files;\n"
        + "      var reader = new FileReader();\n"
        + "      reader.onload = function() {\n"
        + "        alert(reader.result);\n"
        + "      };\n"
        + "      reader.readAsText(files[0], 'utf-8');\n"
        + "    }\n"
        + "  </script>\n"
        + "<head>\n"
        + "<body>\n"
        + "  <form name='testForm'>\n"
        + "    <input type='file' id='fileupload' name='fileupload'>\n"
        + "  </form>\n"
        + "  <button id='testBtn' onclick='test()'>Tester</button>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);

    final File tstFile = File.createTempFile("HtmlUnitReadAsTextTest", ".txt");
    try {
        FileUtils.write(tstFile, "Html \u00dcnit", StandardCharsets.UTF_8);

        final String path = tstFile.getCanonicalPath();
        driver.findElement(By.name("fileupload")).sendKeys(path);

        driver.findElement(By.id("testBtn")).click();

        verifyAlerts(driver, getExpectedAlerts());
    }
    finally {
        FileUtils.deleteQuietly(tstFile);
    }
}
 
Example 19
Source File: FileReaderTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("Html \u00dcnit")
public void readAsTextIso88591() throws Exception {
    final String html
        = HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html>\n"
        + "<head>\n"
        + "  <script>\n"
        + "    function test() {\n"
        + "      var files = document.testForm.fileupload.files;\n"
        + "      var reader = new FileReader();\n"
        + "      reader.onload = function() {\n"
        + "        alert(reader.result);\n"
        + "      };\n"
        + "      reader.readAsText(files[0], 'iso-8859-1');\n"
        + "    }\n"
        + "  </script>\n"
        + "<head>\n"
        + "<body>\n"
        + "  <form name='testForm'>\n"
        + "    <input type='file' id='fileupload' name='fileupload'>\n"
        + "  </form>\n"
        + "  <button id='testBtn' onclick='test()'>Tester</button>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPage2(html);

    final File tstFile = File.createTempFile("HtmlUnitReadAsTextTest", ".txt");
    try {
        FileUtils.write(tstFile, "Html \u00dcnit", Charset.forName("ISO-8859-1"));

        final String path = tstFile.getCanonicalPath();
        driver.findElement(By.name("fileupload")).sendKeys(path);

        driver.findElement(By.id("testBtn")).click();

        verifyAlerts(driver, getExpectedAlerts());
    }
    finally {
        FileUtils.deleteQuietly(tstFile);
    }
}
 
Example 20
Source File: PageSourceSaver.java    From webtester2-core with Apache License 2.0 3 votes vote down vote up
private File doSavePageSource(File targetFolder, String fileNameWithoutSuffix) throws IOException {

        String fileName = fileNameWithoutSuffix + ".html";
        File pageSource = new File(targetFolder, fileName);

        FileUtils.write(pageSource, get(), StandardCharsets.UTF_8);

        log.debug("saved page source to file: {}", pageSource);
        fireEventIfEnabled(pageSource);
        return pageSource;

    }