Java Code Examples for java.nio.file.Files#newOutputStream()

The following examples show how to use java.nio.file.Files#newOutputStream() . These examples are extracted from open source projects. 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 Project: Alpine   File: KeyManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Saves a key pair.
 *
 * @param keyPair the key pair to save
 * @throws IOException if the files cannot be written
 * @since 1.0.0
 */
public void save(final KeyPair keyPair) throws IOException {
    LOGGER.info("Saving key pair");
    final PrivateKey privateKey = keyPair.getPrivate();
    final PublicKey publicKey = keyPair.getPublic();

    // Store Public Key
    final File publicKeyFile = getKeyPath(publicKey);
    publicKeyFile.getParentFile().mkdirs(); // make directories if they do not exist
    final X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    try (OutputStream fos = Files.newOutputStream(publicKeyFile.toPath())) {
        fos.write(x509EncodedKeySpec.getEncoded());
    }

    // Store Private Key.
    final File privateKeyFile = getKeyPath(privateKey);
    privateKeyFile.getParentFile().mkdirs(); // make directories if they do not exist
    final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    try (OutputStream fos = Files.newOutputStream(privateKeyFile.toPath())) {
        fos.write(pkcs8EncodedKeySpec.getEncoded());
    }
}
 
Example 2
static void test8069211() throws Exception {
    // create a new filesystem, copy this file into it
    Map<String, Object> env = new HashMap<String, Object>();
    env.put("create", "true");
    Path fsPath = getTempPath();
    try (FileSystem fs = newZipFileSystem(fsPath, env);) {
        OutputStream out = Files.newOutputStream(fs.getPath("/foo"));
        out.write("hello".getBytes());
        out.close();
        out.close();
    }
    try (FileSystem fs = newZipFileSystem(fsPath, new HashMap<String, Object>())) {
        if (!Arrays.equals(Files.readAllBytes(fs.getPath("/foo")),
                           "hello".getBytes())) {
            throw new RuntimeException("entry close() failed");
        }
    } catch (Exception x) {
        throw new RuntimeException("entry close() failed", x);
    } finally {
        Files.delete(fsPath);
    }
}
 
Example 3
Source Project: Jaffree   File: FFmpegTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPipeOutput() throws IOException {
    Path tempDir = Files.createTempDirectory("jaffree");
    Path outputPath = tempDir.resolve(VIDEO_MP4.getFileName());

    FFmpegResult result;
    try (OutputStream outputStream = Files.newOutputStream(outputPath, CREATE)) {
        result = FFmpeg.atPath(BIN)
                .addInput(UrlInput.fromPath(VIDEO_MP4))
                .addOutput(PipeOutput.pumpTo(outputStream).setFormat("flv"))
                .setOverwriteOutput(true)
                .execute();
    }

    Assert.assertNotNull(result);
    Assert.assertNotNull(result.getVideoSize());

    Assert.assertTrue(getExactDuration(outputPath) > 10.);
}
 
Example 4
Source Project: tessera   File: LegacyCliAdapter.java    License: Apache License 2.0 6 votes vote down vote up
static CliResult writeToOutputFile(Config config, Path outputPath) throws IOException {
    SystemAdapter systemAdapter = SystemAdapter.INSTANCE;
    systemAdapter.out().printf("Saving config to %s", outputPath);
    systemAdapter.out().println();
    JaxbUtil.marshalWithNoValidation(config, systemAdapter.out());
    systemAdapter.out().println();

    try (OutputStream outputStream = Files.newOutputStream(outputPath)) {
        JaxbUtil.marshal(config, outputStream);
        systemAdapter.out().printf("Saved config to  %s", outputPath);
        systemAdapter.out().println();
        return new CliResult(0, false, config);
    } catch (ConstraintViolationException validationException) {
        validationException.getConstraintViolations().stream()
                .map(cv -> "Warning: " + cv.getMessage() + " on property " + cv.getPropertyPath())
                .forEach(systemAdapter.err()::println);

        Files.write(outputPath, JaxbUtil.marshalToStringNoValidation(config).getBytes());
        systemAdapter.out().printf("Saved config to  %s", outputPath);
        systemAdapter.out().println();
        return new CliResult(2, false, config);
    }
}
 
Example 5
Source Project: turbine   File: ZipTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void malformedComment() throws Exception {
  Path path = temporaryFolder.newFile("test.jar").toPath();
  Files.delete(path);

  try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(path))) {
    createEntry(zos, "hello", "world".getBytes(UTF_8));
    zos.setComment("this is a comment");
  }
  Files.write(path, "trailing garbage".getBytes(UTF_8), StandardOpenOption.APPEND);

  try {
    actual(path);
    fail();
  } catch (ZipException e) {
    assertThat(e).hasMessageThat().isEqualTo("zip file comment length was 33, expected 17");
  }
}
 
Example 6
Source Project: flink   File: JobSubmitHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFailedJobSubmission() throws Exception {
	final String errorMessage = "test";
	DispatcherGateway mockGateway = new TestingDispatcherGateway.Builder()
		.setSubmitFunction(jobgraph -> FutureUtils.completedExceptionally(new Exception(errorMessage)))
		.build();

	JobSubmitHandler handler = new JobSubmitHandler(
		() -> CompletableFuture.completedFuture(mockGateway),
		RpcUtils.INF_TIMEOUT,
		Collections.emptyMap(),
		TestingUtils.defaultExecutor(),
		configuration);

	final Path jobGraphFile = TEMPORARY_FOLDER.newFile().toPath();

	JobGraph jobGraph = new JobGraph("testjob");
	try (ObjectOutputStream objectOut = new ObjectOutputStream(Files.newOutputStream(jobGraphFile))) {
		objectOut.writeObject(jobGraph);
	}
	JobSubmitRequestBody request = new JobSubmitRequestBody(jobGraphFile.getFileName().toString(), Collections.emptyList(), Collections.emptyList());

	try {
		handler.handleRequest(new HandlerRequest<>(
				request,
				EmptyMessageParameters.getInstance(),
				Collections.emptyMap(),
				Collections.emptyMap(),
				Collections.singletonList(jobGraphFile.toFile())), mockGateway)
			.get();
	} catch (Exception e) {
		Throwable t = ExceptionUtils.stripExecutionException(e);
		Assert.assertEquals(errorMessage, t.getMessage());
	}
}
 
Example 7
@Test
public void openNewOutputStream_theResultShouldBeNotNull() throws IOException {
  initRepository();
  writeToCache("/test_file.txt");
  commitToMaster();
  initGitFileSystem();

  try(OutputStream stream = Files.newOutputStream(gfs.getPath("/test_file.txt"))) {
    assertNotNull(stream);
  }
}
 
Example 8
Source Project: knox   File: GatewayDeployFuncTest.java    License: Apache License 2.0 5 votes vote down vote up
private File writeTestTopology( String name, XMLTag xml ) throws IOException {
  // Create the test topology.
  File tempFile = new File( config.getGatewayTopologyDir(), name + ".xml." + UUID.randomUUID() );
  try(OutputStream stream = Files.newOutputStream(tempFile.toPath())) {
    xml.toStream(stream);
  }
  File descriptor = new File( config.getGatewayTopologyDir(), name + ".xml" );
  tempFile.renameTo( descriptor );
  return descriptor;
}
 
Example 9
Source Project: tessera   File: PicoCliDelegate.java    License: Apache License 2.0 5 votes vote down vote up
private void createPidFile(Path pidFilePath) throws Exception {
    if (Files.exists(pidFilePath)) {
        LOGGER.info("File already exists {}", pidFilePath);
    } else {
        LOGGER.info("Created pid file {}", pidFilePath);
    }

    final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];

    try (OutputStream stream = Files.newOutputStream(pidFilePath, CREATE, TRUNCATE_EXISTING)) {
        stream.write(pid.getBytes(UTF_8));
    }
}
 
Example 10
private static void createModule() {
    final String jbossHome = WildFlySecurityManager.getPropertyPrivileged("jboss.home", ".");
    final Path modulesDir = Paths.get(jbossHome, "modules");
    Assert.assertTrue("Could not find modules directory: " + modulesDir, Files.exists(modulesDir));
    // Create an archive for the module
    final JavaArchive jar = ShrinkWrap.create(JavaArchive.class, "logging-test.jar")
            .addClasses(TestFilter.class);

    final Path testModule = Paths.get(modulesDir.toString(), "org", "jboss", "as", "logging", "test", "main");
    try {
        Files.createDirectories(testModule);
        try (
                BufferedInputStream in = new BufferedInputStream(AbstractLoggingTestCase.class.getResourceAsStream("module.xml"));
                BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(testModule.resolve("module.xml")))
        ) {
            final byte[] buffer = new byte[512];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        }

        // Copy the JAR
        try (OutputStream out = Files.newOutputStream(testModule.resolve("logging-test.jar"), StandardOpenOption.CREATE_NEW)) {
            jar.as(ZipExporter.class).exportTo(out);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 11
Source Project: jeka   File: IvyPublisherForMaven.java    License: Apache License 2.0 5 votes vote down vote up
private void push(JkMavenMetadata metadata, String path) {
    final Path file = JkUtilsPath.createTempFile("metadata-", ".xml");

    try (OutputStream outputStream = Files.newOutputStream(file)) {
        metadata.output(outputStream);
        outputStream.flush();
    } catch (final IOException e) {
        throw new UncheckedIOException(e);
    }
    putInRepo(file, path, true);
}
 
Example 12
private void persist(final Properties props, final File dest) {
  try (OutputStream out = Files.newOutputStream(dest.toPath())) {
    props.store(out, PERSISTED_FILE_COMMENT);
    out.flush();
  } catch (Exception e) {
    log.failedToPersistClusterMonitorData(getMonitorType(), dest.getAbsolutePath(), e);
  }
}
 
Example 13
Source Project: turbine   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes a jdeps proto that indiciates to Blaze that the transitive classpath compilation failed,
 * and it should fall back to the transitive classpath. Used only when {@link
 * ReducedClasspathMode#BAZEL_REDUCED}.
 */
public static void writeJdepsForFallback(TurbineOptions options) throws IOException {
  try (OutputStream os =
      new BufferedOutputStream(Files.newOutputStream(Paths.get(options.outputDeps().get())))) {
    DepsProto.Dependencies.newBuilder()
        .setRuleLabel(options.targetLabel().get())
        .setRequiresReducedClasspathFallback(true)
        .build()
        .writeTo(os);
  }
}
 
Example 14
public void writeToXml(Path path, List<Book> books) throws IOException, XMLStreamException {
    try (OutputStream os = Files.newOutputStream(path)) {
        XMLOutputFactory outputFactory = XMLOutputFactory.newFactory();
        XMLStreamWriter writer = null;
        try {
            writer = outputFactory.createXMLStreamWriter(os, "utf-8");
            writeBooksElem(writer, books);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
 
Example 15
Source Project: takes   File: FkHitRefresh.java    License: MIT License 5 votes vote down vote up
/**
 * Touch the temporary file.
 * @throws IOException If fails
 */
public void touch() throws IOException {
    try (OutputStream out = Files.newOutputStream(
        this.touchedFile().toPath()
    )) {
        out.write('+');
    }
}
 
Example 16
@Test
public void retainsShouldRequirePlusOneReleasesToDeleteTheFile() throws IOException {
	final File newFile = new File(temporaryFolder.getRoot(), ".tmp_" + UUID.randomUUID());
	final OutputStream out = Files.newOutputStream(newFile.toPath(), StandardOpenOption.CREATE_NEW);

	// the reference counter always starts with 1 (not 0). This is why we need +1 releases
	RefCountedFile fileUnderTest = RefCountedFile.newFile(newFile, out);
	verifyTheFileIsStillThere();

	fileUnderTest.retain();
	fileUnderTest.retain();

	Assert.assertEquals(3, fileUnderTest.getReferenceCounter());

	fileUnderTest.release();
	Assert.assertEquals(2, fileUnderTest.getReferenceCounter());
	verifyTheFileIsStillThere();

	fileUnderTest.release();
	Assert.assertEquals(1, fileUnderTest.getReferenceCounter());
	verifyTheFileIsStillThere();

	fileUnderTest.release();
	// the file is deleted now
	try (Stream<Path> files = Files.list(temporaryFolder.getRoot().toPath())) {
		Assert.assertEquals(0L, files.count());
	}
}
 
Example 17
/**
 * The ODS file that is written here is the file content
 */

@Override
public void writeOnDiskFile(final Path odpFile) throws IOException {
	try(OutputStream os = Files.newOutputStream(odpFile)) {
		os.write(getFileData());
	}
	Files.setLastModifiedTime(odpFile, FileTime.from(Instant.ofEpochMilli(getDocLastModified().getTime())));
}
 
Example 18
@Test
public void testNonZeroOpensInOpen(Path base) throws Exception {
    Path m1 = base.resolve("m1x");
    tb.writeJavaFiles(m1,
                      "module m1x { opens api; }",
                      "package api; public class Api {}");
    Path classes = base.resolve("classes");
    Path m1Classes = classes.resolve("m1x");
    tb.createDirectories(m1Classes);

    new JavacTask(tb)
        .options("-XDrawDiagnostics")
        .outdir(m1Classes)
        .files(findJavaFiles(m1))
        .run(Expect.SUCCESS)
        .writeAll();

    Path miClass = m1Classes.resolve("module-info.class");
    ClassFile cf = ClassFile.read(miClass);
    Module_attribute module = (Module_attribute) cf.attributes.map.get(Attribute.Module);
    Module_attribute newModule = new Module_attribute(module.attribute_name_index,
                                                      module.module_name,
                                                      module.module_flags | Module_attribute.ACC_OPEN,
                                                      module.module_version_index,
                                                      module.requires,
                                                      module.exports,
                                                      module.opens,
                                                      module.uses_index,
                                                      module.provides);
    Map<String, Attribute> attrs = new HashMap<>(cf.attributes.map);

    attrs.put(Attribute.Module, newModule);

    Attributes newAttributes = new Attributes(attrs);
    ClassFile newClassFile = new ClassFile(cf.magic,
                                           cf.minor_version,
                                           cf.major_version,
                                           cf.constant_pool,
                                           cf.access_flags,
                                           cf.this_class,
                                           cf.super_class,
                                           cf.interfaces,
                                           cf.fields,
                                           cf.methods,
                                           newAttributes);

    try (OutputStream out = Files.newOutputStream(miClass)) {
        new ClassWriter().write(newClassFile, out);
    }

    Path test = base.resolve("test");
    tb.writeJavaFiles(test,
                      "package impl; public class Impl extends api.Api {}");
    Path testClasses = base.resolve("test-classes");
    tb.createDirectories(testClasses);

    List<String> log = new JavacTask(tb)
            .options("-XDrawDiagnostics",
                     "--module-path", classes.toString(),
                     "--add-modules", "m1x")
            .outdir(testClasses)
            .files(findJavaFiles(test))
            .run(Expect.FAIL)
            .writeAll()
            .getOutputLines(Task.OutputKind.DIRECT);

    List<String> expected = Arrays.asList(
            "- compiler.err.cant.access: m1x.module-info, "
                    + "(compiler.misc.bad.class.file.header: module-info.class, "
                    + "(compiler.misc.module.non.zero.opens: m1x))",
                                          "1 error");

    if (!expected.equals(log))
        throw new Exception("expected output not found: " + log);
}
 
Example 19
@Override
public OutputStream openOutputStream() throws IOException {
    fileManager.flushCache(this);
    ensureParentDirectoriesExist();
    return Files.newOutputStream(path);
}
 
Example 20
protected boolean buildToolIfRequired(@Nonnull String name, @Nonnull ProgressLogger progress) throws Exception {
    final ToolchainSettings toolchain = getToolchain();
    final Path goBinary = toolchain.getGoBinary();
    final Path binDirectory = goBinary.getParent();
    final Path toolBinary = binDirectory.resolve(name + toolchain.getExecutableSuffix());
    final Path toolBinaryInfo = binDirectory.resolve(name + ".info");
    final String info = name + ":" + Version.GROUP + ":" + Version.VERSION;
    if (exists(toolBinary) && exists(toolBinaryInfo)) {
        final String foundInfo = new String(readAllBytes(toolBinaryInfo), "UTF-8");
        if (foundInfo.equals(info)) {
            return false;
        }
    }

    progress.progress("Building tool " + name + "...");
    LOGGER.info("Going to build tool {}...", name);
    final Path sourceTempFile = createTempFile(name, ".go");
    try {
        final InputStream is = getClass().getClassLoader().getResourceAsStream("org/echocat/gradle/plugins/golang/utils/" + name + ".go");
        if (is == null) {
            throw new FileNotFoundException("Could not find source code for tool " + name + " in classpath.");
        }
        try {
            try (final OutputStream os = Files.newOutputStream(sourceTempFile)) {
                IOUtils.copy(is, os);
            }
        } finally {
            //noinspection ThrowFromFinallyBlock
            is.close();
        }

        createDirectoriesIfRequired(binDirectory);

        executor(goBinary)
            .arguments("build", "-o", toolBinary, sourceTempFile)
            .removeEnv("GOPATH")
            .env("GOROOT", toolchain.getGoroot())
            .env("GOROOT_BOOTSTRAP", toolchain.getBootstrapGoroot())
            .execute();
    } finally {
        deleteQuietly(sourceTempFile);
    }

    write(toolBinaryInfo, info.getBytes("UTF-8"));
    //noinspection UseOfSystemOutOrSystemErr
    System.out.println("Tool " + name + " build.");
    return true;
}