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

The following examples show how to use org.apache.commons.io.FileUtils#writeStringToFile() . 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: GitHubPRCause.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@Override
public void onAddedTo(@Nonnull Run run) {
    if (run.getParent().getParent() instanceof SCMSourceOwner) {
        // skip multibranch
        return;
    }

    // move polling log from cause to action
    try {
        GitHubPRPollingLogAction action = new GitHubPRPollingLogAction(run);
        FileUtils.writeStringToFile(action.getPollingLogFile(), getPollingLog());
        run.replaceAction(action);
    } catch (IOException e) {
        LOGGER.warn("Failed to persist the polling log", e);
    }
    setPollingLog(null);
}
 
Example 2
Source File: PluginLoaderImplTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 5000)
public void test_load_single_plugin_load_and_instantiate_no_noarg_constructor() throws Throwable {

    final File pluginFolder1 = temporaryFolder.newFolder("extension", "plugin1");
    FileUtils.writeStringToFile(pluginFolder1.toPath().resolve("hivemq-extension.xml").toFile(),
            validPluginXML1,
            Charset.defaultCharset());
    final File file = new File(pluginFolder1, "extension.jar");
    final JavaArchive javaArchive = ShrinkWrap.create(JavaArchive.class).
            addAsServiceProviderAndClasses(ExtensionMain.class, TestExtensionMainConstructorParamImpl.class);
    javaArchive.as(ZipExporter.class).exportTo(file);

    final HiveMQExtension hiveMQExtension = realPluginLoader.loadSinglePlugin(
            pluginFolder1.toPath(),
            HiveMQPluginXMLReader.getPluginEntityFromXML(pluginFolder1.toPath(), true).get(),
            ExtensionMain.class);

    assertNull(hiveMQExtension);
}
 
Example 3
Source File: CommandHelper.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * Writes the content into a file using same format as source file
 *
 * @param content         content to be written
 * @param path            path to the file
 * @param sourceFileMatch
 * @throws CommandException
 */
public void writeFileContent(String content, Path path, FileMatch sourceFileMatch) throws CommandException {
    try {
        File outputFile = path.toFile();
        BOMInputStream inputStream = new BOMInputStream(FileUtils.openInputStream(sourceFileMatch.getPath().toFile()), false, boms);
        if (inputStream.hasBOM()) {
            FileUtils.writeByteArrayToFile(outputFile, inputStream.getBOM().getBytes());
            FileUtils.writeByteArrayToFile(outputFile, content.getBytes(inputStream.getBOMCharsetName()), true);
        } else {
            FileUtils.writeStringToFile(outputFile, content, StandardCharsets.UTF_8);
        }
    } catch (IOException e) {
        throw new CommandException("Cannot write file content in path: " + path.toString(), e);
    }
}
 
Example 4
Source File: GoConfigFileHelper.java    From gocd with Apache License 2.0 5 votes vote down vote up
private File addPasswordFile() throws IOException {
    passwordFile = TestFileUtil.createTempFile("password.properties");
    passwordFile.deleteOnExit();
    final String nonAdmin = "jez=ThmbShxAtJepX80c2JY1FzOEmUk=\n"; //in plain text: badger
    final String admin1 = "admin1=W6ph5Mm5Pz8GgiULbPgzG37mj9g=\n"; //in plain text: password
    FileUtils.writeStringToFile(passwordFile, nonAdmin + admin1, UTF_8);
    return passwordFile;
}
 
Example 5
Source File: ConcurrentConsumerCorrectTest.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
private void cleanDir() throws Exception {
    Thread.sleep(2000);
    File file = new File(System.getProperty("user.home") + File.separator + "logs/tracelog"
                         + File.separator + "append-manager.log");
    if (file.exists()) {
        FileUtils.writeStringToFile(file, "");
    }
    File f1 = new File(fileNameRoot + fileName1);
    if (f1.exists()) {
        FileUtils.writeStringToFile(f1, "");
    }
    File f2 = new File(fileNameRoot + fileName2);
    if (f2.exists()) {
        FileUtils.writeStringToFile(f2, "");
    }
    File f3 = new File(fileNameRoot + fileName3);
    if (f3.exists()) {
        FileUtils.writeStringToFile(f3, "");
    }
    File f4 = new File(fileNameRoot + fileName4);
    if (f4.exists()) {
        FileUtils.writeStringToFile(f4, "");
    }
    File f5 = new File(fileNameRoot + fileName5);
    if (f5.exists()) {
        FileUtils.writeStringToFile(f5, "");
    }
}
 
Example 6
Source File: Structure.java    From coming with MIT License 5 votes vote down vote up
public void save(String filePath) {
    try {
        StringJoiner stringJoiner = new StringJoiner(" ");
        for (double parameter : parameterArray) {
            stringJoiner.add(String.valueOf(parameter));
        }
        File vectorFile = new File(filePath);
        FileUtils.writeStringToFile(vectorFile, stringJoiner.toString(), Charset.defaultCharset(), false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: ArtifactsServiceTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldPurgeArtifactsExceptPluggableArtifactMetadataFolderForGivenStageAndMarkItCleaned() throws IOException {
    File artifactsRoot = temporaryFolder.newFolder();
    assumeArtifactsRoot(artifactsRoot);
    willCleanUp(artifactsRoot);
    File jobDir = new File(artifactsRoot, "pipelines/pipeline/10/stage/20/job");
    jobDir.mkdirs();
    File aFile = new File(jobDir, "foo");
    FileUtils.writeStringToFile(aFile, "hello world", UTF_8);
    File aDirectory = new File(jobDir, "bar");
    aDirectory.mkdir();
    File anotherFile = new File(aDirectory, "baz");
    FileUtils.writeStringToFile(anotherFile, "quux", UTF_8);

    File pluggableArtifactMetadataDir = new File(jobDir, "pluggable-artifact-metadata");
    pluggableArtifactMetadataDir.mkdir();
    File metadataJson = new File(pluggableArtifactMetadataDir, "cd.go.artifact.docker.json");
    FileUtils.writeStringToFile(metadataJson, "{\"image\": \"alpine:foo\", \"digest\": \"sha\"}", UTF_8);

    ArtifactsService artifactsService = new ArtifactsService(resolverService, stageService, artifactsDirHolder, zipUtil);
    artifactsService.initialize();
    Stage stage = StageMother.createPassedStage("pipeline", 10, "stage", 20, "job", new Date());
    artifactsService.purgeArtifactsForStage(stage);

    assertThat(jobDir.exists()).isTrue();
    assertThat(aFile.exists()).isFalse();
    assertThat(anotherFile.exists()).isFalse();
    assertThat(aDirectory.exists()).isFalse();

    assertThat(new File(artifactsRoot, "pipelines/pipeline/10/stage/20/job/pluggable-artifact-metadata/cd.go.artifact.docker.json").exists()).isTrue();

    verify(stageService).markArtifactsDeletedFor(stage);
}
 
Example 8
Source File: PomIOTest.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
@Test
public void testRewritePOMs()
                throws Exception
{
    URL resource = PomIOTest.class.getResource( filename );
    assertNotNull( resource );
    File pom = new File( resource.getFile() );
    assertTrue( pom.exists() );

    File targetFile = folder.newFile( "target.xml" );
    FileUtils.writeStringToFile( targetFile, FileUtils.readFileToString( pom, StandardCharsets.UTF_8 )
                                                      .replaceAll( "dospom", "newdospom" ), StandardCharsets.UTF_8 );
    FileUtils.copyFile( pom, targetFile );

    List<Project> projects = pomIO.parseProject( targetFile );
    Model model = projects.get( 0 ).getModel();
    model.setGroupId( "org.commonjava.maven.ext.versioning.test" );
    model.setArtifactId( "dospom" );
    model.setVersion( "1.0" );
    model.setPackaging( "pom" );
    model.setModelVersion( "4.0.0" );

    Project p = new Project( targetFile, model );
    HashSet<Project> changed = new HashSet<>();
    changed.add( p );
    pomIO.rewritePOMs( changed );

    assertTrue( FileUtils.contentEqualsIgnoreEOL( pom, targetFile, StandardCharsets.UTF_8.toString() ) );
    assertTrue( FileUtils.contentEquals( targetFile, pom ) );
}
 
Example 9
Source File: RSpecReportBuilder.java    From bootstraped-multi-test-results-report with MIT License 5 votes vote down vote up
private void writeTestCaseSummaryReport() throws IOException {
    Template template = new Helpers(new Handlebars()).registerHelpers().compile(TEST_SUMMARY_REPORT);
    for (TestSuiteModel ts : processedTestSuites) {
        String content = template.apply(ts);
        FileUtils.writeStringToFile(new File(TEST_SUMMARY_PATH + ts.getUniqueID() + ".html"),
            content);
    }
}
 
Example 10
Source File: TopicMsgFilterServiceImpl.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
private int appendFile(File file, StringBuilder strBuilder) throws IOException {
    if (file != null && strBuilder.length() > 0) {
        FileUtils.writeStringToFile(file, strBuilder.toString(), StandardCharsets.UTF_8, true);
        strBuilder.delete(0, strBuilder.length());
    }
    return 0;
}
 
Example 11
Source File: PushTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
@BeforeClass
public static void createBareRepository() throws Exception {
    /* Command line git commands fail unless certain default values are set */
    CliGitCommand gitCmd = new CliGitCommand(null);
    gitCmd.setDefaults();

    /* Randomly choose git implementation to create bare repository */
    final String[] gitImplementations = {"git", "jgit"};
    Random random = new Random();
    String gitImpl = gitImplementations[random.nextInt(gitImplementations.length)];

    /* Create the bare repository */
    bareRepo = staticTemporaryFolder.newFolder();
    bareURI = new URIish(bareRepo.getAbsolutePath());
    hudson.EnvVars env = new hudson.EnvVars();
    TaskListener listener = StreamTaskListener.fromStderr();
    bareGitClient = Git.with(listener, env).in(bareRepo).using(gitImpl).getClient();
    bareGitClient.init_().workspace(bareRepo.getAbsolutePath()).bare(true).execute();

    /* Clone the bare repository into a working copy */
    File cloneRepo = staticTemporaryFolder.newFolder();
    GitClient cloneGitClient = Git.with(listener, env).in(cloneRepo).using(gitImpl).getClient();
    cloneGitClient.clone_()
            .url(bareRepo.getAbsolutePath())
            .repositoryName("origin")
            .execute();

    for (String branchName : BRANCH_NAMES) {
        /* Add a file with random content to the current branch of working repo */
        File added = File.createTempFile("added-", ".txt", cloneRepo);
        String randomContent = java.util.UUID.randomUUID().toString();
        String addedContent = "Initial commit to branch " + branchName + " content '" + randomContent + "'";
        FileUtils.writeStringToFile(added, addedContent, "UTF-8");
        cloneGitClient.add(added.getName());
        cloneGitClient.commit("Initial commit to " + branchName + " file " + added.getName() + " with " + randomContent);
        // checkoutOldBranchAndCommitFile needs at least two commits to the branch
        FileUtils.writeStringToFile(added, "Another revision " + randomContent, "UTF-8");
        cloneGitClient.add(added.getName());
        cloneGitClient.commit("Second commit to " + branchName);

        /* Push HEAD of current branch to branchName on the bare repository */
        cloneGitClient.push().to(bareURI).ref("HEAD:" + branchName).execute();
    }

    /* Remember the SHA1 of the first commit */
    bareFirstCommit = bareGitClient.getHeadRev(bareRepo.getAbsolutePath(), "master");
}
 
Example 12
Source File: AgentBootstrapperFunctionalTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
private void createRandomFile(File agentJar) throws IOException {
    FileUtils.writeStringToFile(agentJar, RandomStringUtils.random((int) (Math.random() * 100)), UTF_8);
}
 
Example 13
Source File: WorkMgrServiceTest.java    From batfish with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetAnswerRowsAnalysis() throws Exception {
  initNetwork();
  initSnapshot();
  String analysis = "analysis1";
  String question = "question1";
  Question questionObj = new TestQuestion();
  String questionContent = BatfishObjectMapper.writeString(questionObj);
  String columnName = "col";
  AnswerRowsOptions answersRowsOptions =
      new AnswerRowsOptions(
          ImmutableSet.of(columnName),
          ImmutableList.of(new ColumnFilter(columnName, "")),
          Integer.MAX_VALUE,
          0,
          ImmutableList.of(new ColumnSortOption(columnName, false)),
          false);
  String answerRowsOptionsStr = BatfishObjectMapper.writePrettyString(answersRowsOptions);
  int value = 5;
  Answer testAnswer = new Answer();
  testAnswer.addAnswerElement(
      new TableAnswerElement(
              new TableMetadata(
                  ImmutableList.of(new ColumnMetadata(columnName, Schema.INTEGER, "foobar")),
                  new DisplayHints().getTextDesc()))
          .addRow(Row.of(columnName, value)));
  testAnswer.setStatus(AnswerStatus.SUCCESS);
  String answer = BatfishObjectMapper.writePrettyString(testAnswer);

  String analysisJsonString = String.format("{\"%s\":%s}", question, questionContent);
  File analysisFile = _networksFolder.newFile(analysis);
  FileUtils.writeStringToFile(analysisFile, analysisJsonString, StandardCharsets.UTF_8);

  _service.configureAnalysis(
      CoordConsts.DEFAULT_API_KEY,
      BatfishVersion.getVersionStatic(),
      _networkName,
      "new",
      analysis,
      new FileInputStream(analysisFile),
      "",
      null);
  AnalysisId analysisId = idm().getAnalysisId(analysis, _networkId).get();
  QuestionId questionId = idm().getQuestionId(question, _networkId, analysisId).get();
  AnswerId answerId =
      idm()
          .getBaseAnswerId(
              _networkId,
              _snapshotId,
              questionId,
              DEFAULT_QUESTION_SETTINGS_ID,
              DEFAULT_NETWORK_NODE_ROLES_ID,
              null,
              analysisId);

  Main.getWorkMgr().getStorage().storeAnswer(answer, answerId);
  Main.getWorkMgr()
      .getStorage()
      .storeAnswerMetadata(
          AnswerMetadataUtil.computeAnswerMetadata(testAnswer, Main.getLogger()), answerId);

  JSONArray answerOutput =
      _service.getAnswerRows(
          CoordConsts.DEFAULT_API_KEY,
          BatfishVersion.getVersionStatic(),
          _networkName,
          _snapshotName,
          null,
          question,
          analysis,
          answerRowsOptionsStr,
          null);

  assertThat(answerOutput.get(0), equalTo(CoordConsts.SVC_KEY_SUCCESS));

  JSONObject answerJsonObject = (JSONObject) answerOutput.get(1);
  String answersJsonString = answerJsonObject.getString(CoordConsts.SVC_KEY_ANSWER);
  Answer processedAnswer =
      BatfishObjectMapper.mapper().readValue(answersJsonString, new TypeReference<Answer>() {});

  TableAnswerElement processedTable =
      (TableAnswerElement) processedAnswer.getAnswerElements().get(0);

  assertThat(processedTable.getRowsList(), equalTo(ImmutableList.of(Row.of(columnName, value))));
}
 
Example 14
Source File: TestFileUploadPart.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void classSetup() throws IOException {
  file = File.createTempFile("upload", ".txt");
  file.deleteOnExit();
  FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8, false);
}
 
Example 15
Source File: StandaloneBroadcaster.java    From jvm-sandbox-repeater with Apache License 2.0 4 votes vote down vote up
private void broadcast(String body, String name, String folder) throws IOException {
    FileUtils.writeStringToFile(new File(assembleFileName(name, folder)), body, "UTF-8");
}
 
Example 16
Source File: ConverterObjectGenerator.java    From obridge with MIT License 4 votes vote down vote up
private static void generatePrimitiveTypeConverter(String packageName, String outputDir) throws IOException {
    Pojo pojo = new Pojo();
    pojo.setPackageName(packageName);
    String javaSource = MustacheRunner.build("PrimitiveTypeConverter.java.mustache", pojo);
    FileUtils.writeStringToFile(new File(outputDir + "PrimitiveTypeConverter.java"), CodeFormatter.format(javaSource), "utf-8");
}
 
Example 17
Source File: ValidationUtilTests.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
@Test
    public void testINDArrayTextValidation() throws Exception {
        File f = testDir.newFolder();

        //Test not existent file:
        File fNonExistent = new File("doesntExist.txt");
        ValidationResult vr0 = Nd4jValidator.validateINDArrayTextFile(fNonExistent);
        assertFalse(vr0.isValid());
        assertEquals("INDArray Text File", vr0.getFormatType());
        assertTrue(vr0.getIssues().get(0), vr0.getIssues().get(0).contains("exist"));
//        System.out.println(vr0.toString());

        //Test empty file:
        File fEmpty = new File(f, "empty.txt");
        fEmpty.createNewFile();
        assertTrue(fEmpty.exists());
        ValidationResult vr1 = Nd4jValidator.validateINDArrayTextFile(fEmpty);
        assertEquals("INDArray Text File", vr1.getFormatType());
        assertFalse(vr1.isValid());
        assertTrue(vr1.getIssues().get(0), vr1.getIssues().get(0).contains("empty"));
//        System.out.println(vr1.toString());

        //Test directory (not zip file)
        File directory = new File(f, "dir");
        boolean created = directory.mkdir();
        assertTrue(created);
        ValidationResult vr2 = Nd4jValidator.validateINDArrayTextFile(directory);
        assertEquals("INDArray Text File", vr2.getFormatType());
        assertFalse(vr2.isValid());
        assertTrue(vr2.getIssues().get(0), vr2.getIssues().get(0).contains("directory"));
//        System.out.println(vr2.toString());

        //Test non-INDArray format:
        File fText = new File(f, "text.txt");
        FileUtils.writeStringToFile(fText, "Not a INDArray .text file", StandardCharsets.UTF_8);
        ValidationResult vr3 = Nd4jValidator.validateINDArrayTextFile(fText);
        assertEquals("INDArray Text File", vr3.getFormatType());
        assertFalse(vr3.isValid());
        String s = vr3.getIssues().get(0);
        assertTrue(s, s.contains("text") && s.contains("INDArray") && s.contains("corrupt"));
//        System.out.println(vr3.toString());

        //Test corrupted txt format:
        File fValid = new File(f, "valid.txt");
        INDArray arr = Nd4j.arange(12).castTo(DataType.FLOAT).reshape(3,4);
        Nd4j.writeTxt(arr, fValid.getPath());
        byte[] indarrayTxtBytes = FileUtils.readFileToByteArray(fValid);
        for( int i=0; i<30; i++ ){
            indarrayTxtBytes[i] = (byte)('a' + i);
        }
        File fCorrupt = new File(f, "corrupt.txt");
        FileUtils.writeByteArrayToFile(fCorrupt, indarrayTxtBytes);

        ValidationResult vr4 = Nd4jValidator.validateINDArrayTextFile(fCorrupt);
        assertEquals("INDArray Text File", vr4.getFormatType());
        assertFalse(vr4.isValid());
        s = vr4.getIssues().get(0);
        assertTrue(s, s.contains("text") && s.contains("INDArray") && s.contains("corrupt"));
//        System.out.println(vr4.toString());


        //Test valid npz format:
        ValidationResult vr5 = Nd4jValidator.validateINDArrayTextFile(fValid);
        assertEquals("INDArray Text File", vr5.getFormatType());
        assertTrue(vr5.isValid());
        assertNull(vr5.getIssues());
        assertNull(vr5.getException());
//        System.out.println(vr4.toString());
    }
 
Example 18
Source File: FileUtilTest.java    From gocd with Apache License 2.0 4 votes vote down vote up
@Test
void shouldCalculateSha1Digest() throws IOException {
    File tempFile = temporaryFolder.newFile();
    FileUtils.writeStringToFile(tempFile, "12345", UTF_8);
    assertThat(FileUtil.sha1Digest(tempFile)).isEqualTo("jLIjfQZ5yojbZGTqxg2pY0VROWQ=");
}
 
Example 19
Source File: AdminConfigurationUtil.java    From jumbune with GNU Lesser General Public License v3.0 3 votes vote down vote up
/************************************* Ticket **************************************/


public static void saveTicketConfiguration(String clusterName, TicketConfiguration conf) throws IOException {
	String path = confPath + clusterName + File.separator + ConfigurationConstants.TICKET_CONFIGURATION_FILE;
	FileUtils.writeStringToFile(new File(path), gson.toJson(conf));
}
 
Example 20
Source File: FileSystem.java    From functional-tests-core with Apache License 2.0 2 votes vote down vote up
/**
 * Write content of String to file.
 *
 * @param filePath File path as String.
 * @param text     Content to be written in file.
 * @throws IOException When fail to write in file.
 */
public static void writeFile(String filePath, String text) throws IOException {
    FileUtils.writeStringToFile(new File(filePath), text);
}