Java Code Examples for com.google.common.io.Files#write()

The following examples show how to use com.google.common.io.Files#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: TestBootstrap.java    From cdep with Apache License 2.0 6 votes vote down vote up
public void testLocalFile() throws Exception {
    File localCDep = new File("./local-test-files/cdep-alpha-0.0.29.jar").getAbsoluteFile();
    File localSnake = new File("./local-test-files/snakeyaml-1.17.jar").getAbsoluteFile();
    if (!localCDep.exists()) {
         localCDep = new File("../../bootstrap/local-test-files/cdep-alpha-0.0.29.jar")
                 .getAbsoluteFile().getCanonicalFile();
         localSnake = new File("../../bootstrap/local-test-files/snakeyaml-1.17.jar")
                 .getAbsoluteFile().getCanonicalFile();
    }
    assertThat(localCDep.exists()).isTrue();
    assertThat(localSnake.exists()).isTrue();
    getDownloadFolder().mkdirs();
    File manifest = new File(getDownloadFolder().getParentFile().getParentFile(),
            "bootstrap.yml").getAbsoluteFile();
    StringBuilder sb = new StringBuilder();
    sb.append("entry: com.jomofisher.cdep.CDep\n");
    sb.append("dependencies:\n");
    sb.append(String.format("- %s\n", localCDep.toString()));
    sb.append(String.format("- %s\n", localSnake.toString()));
    Files.write(sb.toString(), manifest, StandardCharsets.UTF_8);
    String result = main(manifest.getAbsolutePath(), "--version");
    System.out.printf(result);
}
 
Example 2
Source File: TestSpoolingFileLineReader.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@Test
// Test the case where we read finish reading and fully commit a file, then
//  the directory is empty.
public void testEmptyDirectoryAfterCommittingFile() throws IOException {
  File f1 = new File(tmpDir.getAbsolutePath() + "/file1");

  Files.write("file1line1\nfile1line2\n", f1, Charsets.UTF_8);

  ReliableSpoolingFileEventReader parser = getParser();

  List<String> allLines = bodiesAsStrings(parser.readEvents(2));
  assertEquals(2, allLines.size());
  parser.commit();

  List<String> empty = bodiesAsStrings(parser.readEvents(10));
  assertEquals(0, empty.size());
}
 
Example 3
Source File: KeyManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void copyToWorkspace(Workspace ws) {
    try {
        if (!isKeyExist()) generateKey();

        Key key = getKey();

        Files.write(key.getPublicKey(), getPublicKeyFile(ws), defaultCharset());
        Files.write(key.getPrivateKey(), getPrivateKeyFile(ws), defaultCharset());
        Files.write(format("coding.net %s\n", CODING_PUB_KEY), getKnownHostsFile(ws), defaultCharset());
        
        //ignore on windows.
        if (!IS_OS_WINDOWS) {
            //using PosixFilePermission to set file permissions 600
            setPosixFilePermissions(getPrivateKeyFile(ws).toPath(), newHashSet(OWNER_READ, OWNER_WRITE));
        }
    } catch (IOException e) {
        log.error("copy key to workspace failed", e);
    }
}
 
Example 4
Source File: TestSFTPRemoteConnector.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testStrictHostChecking() throws Exception {
  File knownHostsFile = testFolder.newFile("hosts");
  Files.write(getHostsFileEntry(), knownHostsFile);

  SFTPRemoteConnectorForTest connector = new SFTPRemoteConnectorForTest(getBean(
      "sftp://localhost:" + port + "/",
      true,
      false,
      TESTUSER,
      TESTPASS,
      null,
      null,
      knownHostsFile.toString(),
      false,
      null
  ));

  List<Stage.ConfigIssue> issues = initWithNoIssues(connector);
  Assert.assertEquals(0, issues.size());
  verifyConnection(connector);

  connector.close();
}
 
Example 5
Source File: TestCDep.java    From cdep with Apache License 2.0 6 votes vote down vote up
@Test
public void unfindableLocalFile() throws Exception {
  CDepYml config = new CDepYml();
  System.out.printf(new Yaml().dump(config));
  File yaml = new File(".test-files/unfindableLocalFile/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\ndependencies:\n- compile: ../not-a-file/cdep-manifest.yml\n",
      yaml, StandardCharsets.UTF_8);

  try {
    main("-wf", yaml.getParent());
    fail("Expected failure");
  } catch (CDepRuntimeException e) {
    assertThat(e).hasMessage("Could not resolve '../not-a-file/cdep-manifest.yml'. It doesn't exist.");
    assertThat(e.errorInfo.file).endsWith("cdep.yml");
    assertThat(e.errorInfo.code).isEqualTo("c35a5b0");
  }
}
 
Example 6
Source File: RestrictionConfiguratorTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_tooHigh() throws IOException {
    final String contents =
            "<hivemq>" +
                    "<restrictions>" +
                    "<max-connections>500</max-connections>" +
                    "<max-client-id-length>123456</max-client-id-length>" +
                    "<max-topic-length>123456</max-topic-length>" +
                    "<no-connect-idle-timeout>300</no-connect-idle-timeout>" +
                    "<incoming-bandwidth-throttling>200</incoming-bandwidth-throttling>" +
                    "</restrictions>" +
                    "</hivemq>";
    Files.write(contents.getBytes(UTF_8), xmlFile);

    reader.applyConfig();

    assertEquals(500, restrictionsConfigurationService.maxConnections());
    assertEquals(MAX_CLIENT_ID_LENGTH_DEFAULT, restrictionsConfigurationService.maxClientIdLength());
    assertEquals(MAX_TOPIC_LENGTH_DEFAULT, restrictionsConfigurationService.maxTopicLength());
    assertEquals(300, restrictionsConfigurationService.noConnectIdleTimeout());
    assertEquals(200, restrictionsConfigurationService.incomingLimit());
}
 
Example 7
Source File: MavenImportUtils.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Force the pom file of a project to be "simple".
 *
 * @param projectDir the folder in which the pom file is located.
 * @param monitor the progress monitor.
 * @throws IOException if the pom file cannot be changed.
 */
static void forceSimplePom(File projectDir, IProgressMonitor monitor) throws IOException {
	final File pomFile = new File(projectDir, POM_FILE);
	if (pomFile.exists()) {
		final SubMonitor submon = SubMonitor.convert(monitor, 4);
		final File savedPomFile = new File(projectDir, POM_BACKUP_FILE);
		if (savedPomFile.exists()) {
			savedPomFile.delete();
		}
		submon.worked(1);
		Files.copy(pomFile, savedPomFile);
		submon.worked(1);
		final StringBuilder content = new StringBuilder();
		try (BufferedReader stream = new BufferedReader(new FileReader(pomFile))) {
			String line = stream.readLine();
			while (line != null) {
				line = line.replaceAll("<extensions>\\s*true\\s*</extensions>", ""); //$NON-NLS-1$ //$NON-NLS-2$
				content.append(line).append("\n"); //$NON-NLS-1$
				line = stream.readLine();
			}
		}
		submon.worked(1);
		Files.write(content.toString().getBytes(), pomFile);
		submon.worked(1);
	}
}
 
Example 8
Source File: TestCDep.java    From cdep with Apache License 2.0 6 votes vote down vote up
@Test
public void download() throws Exception {
  CDepYml config = new CDepYml();
  File yaml = new File(".test-files/download/cdep.yml");
  yaml.getParentFile().mkdirs();
  Files.write("builders: [cmake, cmakeExamples]\n" +
          "dependencies:\n" +
          "- compile: com.github.jomof:low-level-statistics:0.0.16\n", yaml,
      StandardCharsets.UTF_8);
  // Download first.
  main("-wf", yaml.getParent());
  // Redownload
  String result = main("download", "-wf", yaml.getParent());
  System.out.printf(result);
  assertThat(result).doesNotContain("Redownload");
  assertThat(result).contains("Generating");
}
 
Example 9
Source File: RestrictionConfiguratorTest.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@Test
public void test_restrictions_xml() throws Exception {

    final String contents =
            "<hivemq>" +
                    "<restrictions>" +
                    "<max-connections>500</max-connections>" +
                    "<max-client-id-length>400</max-client-id-length>" +
                    "<max-topic-length>400</max-topic-length>" +
                    "<no-connect-idle-timeout>300</no-connect-idle-timeout>" +
                    "<incoming-bandwidth-throttling>200</incoming-bandwidth-throttling>" +
                    "</restrictions>" +
                    "</hivemq>";
    Files.write(contents.getBytes(UTF_8), xmlFile);

    reader.applyConfig();

    assertEquals(500, restrictionsConfigurationService.maxConnections());
    assertEquals(400, restrictionsConfigurationService.maxClientIdLength());
    assertEquals(400, restrictionsConfigurationService.maxTopicLength());
    assertEquals(300, restrictionsConfigurationService.noConnectIdleTimeout());
    assertEquals(200, restrictionsConfigurationService.incomingLimit());

}
 
Example 10
Source File: CommandLineSteps.java    From datamill with ISC License 5 votes vote down vote up
public void doCreateFile(String file, String content) throws IOException {
    File temporaryDirectory = getOrCreateTemporaryDirectory();

    String resolvedFile = placeholderResolver.resolve(file);

    File fileWithinDirectory = new File(temporaryDirectory, resolvedFile);
    Files.write(content, fileWithinDirectory, Charset.defaultCharset());
}
 
Example 11
Source File: ATHJUnitRunner.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private void writeScreenShotCause(Throwable t, Object test, FrameworkMethod method) throws IOException {
    WebDriver driver = injector.getInstance(WebDriver.class);
    File file = new File("target/screenshots/"+ test.getClass().getName() + "_" + method.getName() + ".png");

    Throwable cause = t.getCause();
    boolean fromException = false;
    while(cause != null) {
        if(cause instanceof ScreenshotException) {
            ScreenshotException se = ((ScreenshotException) cause);

            byte[] screenshot =  Base64.getMimeDecoder().decode(se.getBase64EncodedScreenshot());

            Files.createParentDirs(file);
            Files.write(screenshot, file);
            logger.info("Wrote screenshot to " + file.getAbsolutePath());
            fromException = true;
            break;
        } else {
            cause = cause.getCause();
        }
    }

    if(!fromException) {
        File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, file);
        logger.info("Wrote screenshot to " + file.getAbsolutePath());
    }
}
 
Example 12
Source File: MiscClassesRebindTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Entity loadEntityMemento(String label, String entityId) throws Exception {
    String mementoResourceName = JavaClassNames.cleanSimpleClassName(this) + "-" + label + "-entity-" + entityId+".memento";
    String memento = Streams.readFullyString(getClass().getResourceAsStream(mementoResourceName));
    
    File persistedEntityFile = new File(mementoDir, Os.mergePaths("entities", entityId));
    Files.write(memento.getBytes(), persistedEntityFile);
    
    return newApp = rebind();
}
 
Example 13
Source File: FileScanWriter.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean writeScanCompleteFile(URI fileUri, byte[] contents)
        throws IOException {
    File file = new File(fileUri.toURL().getFile());
    if (file.exists()) {
        // Complete already marked; take no action
        return false;

    }
    Files.createParentDirs(file);
    Files.write(contents, file);
    return true;
}
 
Example 14
Source File: TestSFTPStreamFactory.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  File file = testFolder.newFile("file.txt");
  String text = "hello";
  Files.write(text.getBytes(Charset.forName("UTF-8")), file);
  Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));

  path = testFolder.getRoot().getAbsolutePath();
  setupSSHD(path);
  SSHClient sshClient = createSSHClient();

  SFTPClient sftpClient = sshClient.newSFTPClient();
  remoteFile = sftpClient.open(file.getName(), EnumSet.of(OpenMode.READ));
  remoteFile = Mockito.spy(remoteFile);
}
 
Example 15
Source File: IoUtil.java    From camunda-bpm-elasticsearch with Apache License 2.0 5 votes vote down vote up
public static void writeToFile(byte[] content, String fileName, boolean createFile) {
  File file = new File(fileName);
  try {
    if (createFile) {
      Files.createParentDirs(file);
      file.createNewFile();
    }

    Files.write(content, file);
  } catch (IOException e) {
    // nop
  }
}
 
Example 16
Source File: TestRemoteUploadTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileExistsToError() throws Exception {
  FileRefTestUtil.writePredefinedTextToFile(testFolder.getRoot());
  Record record = createRecord();

  final String OTHER_TEXT = "some other text";
  File targetFile = testFolder.newFile("target.txt");
  Files.write(OTHER_TEXT.getBytes(Charset.forName("UTF-8")), targetFile);
  Assert.assertEquals(OTHER_TEXT, Files.readFirstLine(targetFile, Charset.forName("UTF-8")));

  path = testFolder.getRoot().getAbsolutePath();
  setupServer(path, true);

  RemoteUploadTarget target = new RemoteUploadTarget(getBean(
      scheme.name() + "://localhost:" + port + "/",
      true,
      DataFormat.WHOLE_FILE,
      targetFile.getName(),
      WholeFileExistsAction.TO_ERROR
  ));
  TargetRunner runner = new TargetRunner.Builder(RemoteUploadDTarget.class, target).build();
  runner.runInit();
  runner.runWrite(Collections.singletonList(record));

  List<Record> errorRecords = runner.getErrorRecords();
  Assert.assertEquals(1, errorRecords.size());
  Assert.assertEquals(Errors.REMOTE_UPLOAD_02.getCode(), errorRecords.get(0).getHeader().getErrorCode());
  Assert.assertEquals(record.get().getValueAsMap(), errorRecords.get(0).get().getValueAsMap());

  Assert.assertEquals(0, runner.getEventRecords().size());

  String line = Files.readFirstLine(targetFile, Charset.forName("UTF-8"));
  Assert.assertEquals(OTHER_TEXT, line);

  destroyAndValidate(runner);
}
 
Example 17
Source File: TestJmsTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  baseDir = Files.createTempDir();
  tmpDir = new File(baseDir, "tmp");
  dataDir = new File(baseDir, "data");
  Assert.assertTrue(tmpDir.mkdir());
  passwordFile = new File(baseDir, "password");
  Files.write(PASSWORD.getBytes(StandardCharsets.UTF_8), passwordFile);

  broker = new BrokerService();

  broker.addConnector(BROKER_BIND_URL);
  broker.setTmpDataDirectory(tmpDir);
  broker.setDataDirectoryFile(dataDir);
  List<AuthenticationUser> users = Lists.newArrayList();
  users.add(new AuthenticationUser(USERNAME, PASSWORD, ""));
  SimpleAuthenticationPlugin authentication = new SimpleAuthenticationPlugin(users);
  broker.setPlugins(new BrokerPlugin[]{authentication});
  broker.start();

  credentialsConfig = new CredentialsConfig();
  jmsTargetConfig = new JmsTargetConfig();
  credentialsConfig.useCredentials = true;
  credentialsConfig.username = () -> USERNAME;
  credentialsConfig.password = () -> PASSWORD;
  jmsTargetConfig.destinationName = JNDI_PREFIX + DESTINATION_NAME;
  jmsTargetConfig.initialContextFactory = INITIAL_CONTEXT_FACTORY;
  jmsTargetConfig.connectionFactory = CONNECTION_FACTORY;
  jmsTargetConfig.providerURL = BROKER_BIND_URL;
  // Create a connection and start
  ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME,
      PASSWORD, BROKER_BIND_URL);
  connection = factory.createConnection();
  connection.start();
}
 
Example 18
Source File: UploadCertificate.java    From certificate-transparency-java with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
    throws IOException, CertificateException, InvalidKeySpecException, NoSuchAlgorithmException,
        InvalidKeyException, SignatureException {
  if (args.length < 1) {
    System.out.println(
        String.format(
            "Usage: %s <certificates chain> [output file]",
            UploadCertificate.class.getSimpleName()));
    return;
  }

  String pemFile = args[0];

  List<Certificate> certs = CryptoDataLoader.certificatesFromFile(new File(pemFile));
  System.out.println(String.format("Total number of certificates in chain: %d", certs.size()));

  HttpLogClient client = new HttpLogClient("http://ct.googleapis.com/pilot/ct/v1/");

  Ct.SignedCertificateTimestamp resp = client.addCertificate(certs);

  System.out.println(resp);
  if (args.length >= 2) {
    String outputFile = args[1];
    //TODO(eranm): Binary encoding compatible with the C++ code.
    Files.write(resp.toByteArray(), new File(outputFile));
  }
}
 
Example 19
Source File: ItemLister.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private void copyFromItemListerClasspathBaseStaticsToOutputDir(ResourceUtils resourceUtils, String item, String dest) throws IOException {
    String js = resourceUtils.getResourceAsString(Urls.mergePaths(BASE_STATICS, item));
    Files.write(js, new File(Os.mergePaths(outputFolder, dest)), Charsets.UTF_8);
}
 
Example 20
Source File: TempFiles.java    From appinventor-extensions with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a temporary file for the given data.
 *
 * @param data  data to write into the temporary file
 * @return  file descriptor for temporary file
 * @throws IOException
 */
public static File createTempFile(byte[] data) throws IOException {
  File tmpFile = File.createTempFile("ode", null, tempRoot);
  Files.write(data, tmpFile);
  return tmpFile;
}