List of usage examples for java.nio.file Files copy
public static long copy(Path source, OutputStream out) throws IOException
From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java
/** * Tests the reloading of SSLContext when a PEM key and certificate are used. *//* w ww . ja v a 2s . c o m*/ public void testPEMKeyConfigReloading() throws Exception { Path tempDir = createTempDir(); Path keyPath = tempDir.resolve("testnode.pem"); Path updatedKeyPath = tempDir.resolve("testnode_updated.pem"); Path certPath = tempDir.resolve("testnode.crt"); Path updatedCertPath = tempDir.resolve("testnode_updated.crt"); final Path clientTruststorePath = tempDir.resolve("testnode.jks"); Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.pem"), keyPath); Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.pem"), updatedKeyPath); Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"), updatedCertPath); Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt"), certPath); Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"), clientTruststorePath); MockSecureSettings secureSettings = new MockSecureSettings(); secureSettings.setString("xpack.ssl.secure_key_passphrase", "testnode"); final Settings settings = Settings.builder().put("path.home", createTempDir()).put("xpack.ssl.key", keyPath) .put("xpack.ssl.certificate", certPath).setSecureSettings(secureSettings).build(); final Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build()); // Load HTTPClient once. Client uses a keystore containing testnode key/cert as a truststore try (CloseableHttpClient client = getSSLClient(clientTruststorePath, "testnode")) { final Consumer<SSLContext> keyMaterialPreChecks = (context) -> { try (MockWebServer server = new MockWebServer(context, false)) { server.enqueue(new MockResponse().setResponseCode(200).setBody("body")); server.start(); privilegedConnect( () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close()); } catch (Exception e) { throw new RuntimeException("Exception starting or connecting to the mock server", e); } }; final Runnable modifier = () -> { try { atomicMoveIfPossible(updatedKeyPath, keyPath); atomicMoveIfPossible(updatedCertPath, certPath); } catch (Exception e) { throw new RuntimeException("failed to modify file", e); } }; // The new server certificate is not in the client's truststore so SSLHandshake should fail final Consumer<SSLContext> keyMaterialPostChecks = (updatedContext) -> { try (MockWebServer server = new MockWebServer(updatedContext, false)) { server.enqueue(new MockResponse().setResponseCode(200).setBody("body")); server.start(); SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class, () -> privilegedConnect(() -> client .execute(new HttpGet("https://localhost:" + server.getPort())).close())); assertThat(sslException.getCause().getMessage(), containsString("PKIX path validation failed")); } catch (Exception e) { throw new RuntimeException("Exception starting or connecting to the mock server", e); } }; validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier, keyMaterialPostChecks); } }
From source file:com.asakusafw.testdriver.DirectIoUtil.java
private static <T> DataModelSourceFactory load0(DataModelDefinition<T> definition, HadoopFileFormat<? super T> format, URL source) throws IOException, InterruptedException { List<String> segments = Arrays.stream(source.getPath().split("/")) //$NON-NLS-1$ .map(String::trim).filter(s -> s.isEmpty() == false).collect(Collectors.toList()); String name;// w w w . j a va 2 s .c o m if (segments.isEmpty()) { name = "testing.file"; //$NON-NLS-1$ } else { name = segments.get(segments.size() - 1); } Path tmpdir = Files.createTempDirectory("asakusa-"); //$NON-NLS-1$ try (InputStream in = source.openStream()) { Path target = tmpdir.resolve(name); Files.copy(in, target); return load0(definition, format, target.toFile()); } finally { File dir = tmpdir.toFile(); if (FileUtils.deleteQuietly(dir) == false && dir.exists()) { LOG.warn(MessageFormat.format("failed to delete a temporary file: {0}", tmpdir)); } } }
From source file:com.machinepublishers.jbrowserdriver.JBrowserDriver.java
private static void initClasspath() { List<String> classpathSimpleTmp = new ArrayList<String>(); List<String> classpathUnpackedTmp = new ArrayList<String>(); try {/*from w w w . j a va2 s . c om*/ List<File> classpathElements = new FastClasspathScanner().getUniqueClasspathElements(); final File classpathDir = Files.createTempDirectory("jbd_classpath_").toFile(); Runtime.getRuntime().addShutdownHook(new FileRemover(classpathDir)); List<String> pathsSimple = new ArrayList<String>(); List<String> pathsUnpacked = new ArrayList<String>(); for (File curElement : classpathElements) { String rootLevelElement = curElement.getAbsoluteFile().toURI().toURL().toExternalForm(); pathsSimple.add(rootLevelElement); pathsUnpacked.add(rootLevelElement); if (curElement.isFile() && curElement.getPath().endsWith(".jar")) { try (ZipFile jar = new ZipFile(curElement)) { Enumeration<? extends ZipEntry> entries = jar.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.getName().endsWith(".jar")) { try (InputStream in = jar.getInputStream(entry)) { File childJar = new File(classpathDir, Util.randomFileName() + ".jar"); Files.copy(in, childJar.toPath()); pathsUnpacked.add(childJar.getAbsoluteFile().toURI().toURL().toExternalForm()); childJar.deleteOnExit(); } } } } } } classpathSimpleTmp = createClasspathJar(classpathDir, "classpath-simple.jar", pathsSimple); classpathUnpackedTmp = createClasspathJar(classpathDir, "classpath-unpacked.jar", pathsUnpacked); } catch (Throwable t) { Util.handleException(t); } classpathSimpleArgs = Collections.unmodifiableList(classpathSimpleTmp); classpathUnpackedArgs = Collections.unmodifiableList(classpathUnpackedTmp); }
From source file:org.apache.geode.management.internal.web.http.support.HttpRequester.java
Object extractResponse(ClientHttpResponse response) throws IOException { MediaType mediaType = response.getHeaders().getContentType(); if (mediaType.equals(MediaType.APPLICATION_JSON)) { return org.apache.commons.io.IOUtils.toString(response.getBody(), "UTF-8"); } else {/*from ww w.j av a 2 s . c om*/ Path tempFile = Files.createTempFile("fileDownload", ""); if (tempFile.toFile().exists()) { FileUtils.deleteQuietly(tempFile.toFile()); } Files.copy(response.getBody(), tempFile); return tempFile; } }
From source file:grakn.core.rule.GraknTestServer.java
protected File buildCassandraConfigWithRandomPorts() throws IOException { byte[] bytes = Files.readAllBytes(originalCassandraConfigPath); String configString = new String(bytes, StandardCharsets.UTF_8); configString = configString + "\nstorage_port: " + storagePort; configString = configString + "\nnative_transport_port: " + nativeTransportPort; configString = configString + "\nrpc_port: " + rpcPort; InputStream configStream = new ByteArrayInputStream(configString.getBytes(StandardCharsets.UTF_8)); String directory = "target/embeddedCassandra"; org.apache.cassandra.io.util.FileUtils.createDirectory(directory); Path copyName = Paths.get(directory, "cassandra-embedded.yaml"); // Create file in directory we just created and copy the stream content into it. Files.copy(configStream, copyName); return copyName.toFile(); }
From source file:com.fizzed.stork.deploy.Archive.java
static public void packEntry(ArchiveOutputStream aos, Path dirOrFile, String base, boolean appendName) throws IOException { String entryName = base;/*from w ww.ja va2 s . co m*/ if (appendName) { if (!entryName.equals("")) { if (!entryName.endsWith("/")) { entryName += "/" + dirOrFile.getFileName(); } else { entryName += dirOrFile.getFileName(); } } else { entryName += dirOrFile.getFileName(); } } ArchiveEntry entry = aos.createArchiveEntry(dirOrFile.toFile(), entryName); if (Files.isRegularFile(dirOrFile)) { if (entry instanceof TarArchiveEntry && Files.isExecutable(dirOrFile)) { // -rwxr-xr-x ((TarArchiveEntry) entry).setMode(493); } else { // keep default mode } } aos.putArchiveEntry(entry); if (Files.isRegularFile(dirOrFile)) { Files.copy(dirOrFile, aos); aos.closeArchiveEntry(); } else { aos.closeArchiveEntry(); List<Path> children = Files.list(dirOrFile).collect(Collectors.toList()); if (children != null) { for (Path childFile : children) { packEntry(aos, childFile, entryName + "/", true); } } } }
From source file:com.bekwam.resignator.commands.UnsignCommand.java
private Path copyJAR(File sourceJarFile) throws CommandExecutionException { Path workingJarFile = Paths.get(tempDir.toString(), sourceJarFile.getName()); try {//from ww w . jav a 2s . c om Files.copy(Paths.get(sourceJarFile.getAbsolutePath()), workingJarFile); } catch (IOException exc) { String msg = String.format("can't copy %s to %s", sourceJarFile.getAbsolutePath(), workingJarFile.toString()); logger.error(msg, exc); throw new CommandExecutionException(msg); } return workingJarFile; }
From source file:api.wiki.WikiGenerator.java
private Path copyToReleaseDirectory(Path file, Path releaseDirectory) { try {/*from w ww.j av a 2 s.co m*/ Path target = releaseDirectory .resolve(file.subpath(wikiDirectory().getNameCount(), file.getNameCount())); Files.createDirectories(target.subpath(1, target.getNameCount() - 1)); return Files.copy(file, target); } catch (IOException e) { throw new IllegalStateException(e); } }
From source file:org.apache.archiva.web.test.tools.WebdriverUtility.java
public static Path takeScreenShot(String fileName, WebDriver driver) { Path result = null;//from ww w. j av a2 s . c o m try { Path snapDir = Paths.get("target", "errorshtmlsnap"); Path screenShotDir = Paths.get("target", "screenshots"); if (!Files.exists(snapDir)) { Files.createDirectories(snapDir); } Path htmlFile = snapDir.resolve(fileName + ".html"); Path screenShotFile = screenShotDir.resolve(fileName); String pageSource = null; String encoding = "ISO-8859-1"; try { pageSource = ((JavascriptExecutor) driver) .executeScript("return document.documentElement.outerHTML;").toString(); } catch (Exception e) { log.info("Could not create html source by javascript"); pageSource = driver.getPageSource(); } if (pageSource.contains("encoding=\"")) { encoding = pageSource.replaceFirst(".*encoding=\"([^\"]+)\".*", "$1"); } FileUtils.writeStringToFile(htmlFile.toFile(), pageSource, encoding); try { Path scrs = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).toPath(); Files.copy(scrs, screenShotFile); } catch (Exception e) { log.info("Could not create screenshot: " + e.getMessage()); } } catch (IOException e) { log.info("Creating screenshot failed " + e.getMessage()); } return result; }
From source file:gob.dp.simco.investigacion.controller.InvestigacionController.java
public void guardarCampoDetalle() { try {/* w w w. ja v a 2 s . c o m*/ DateFormat fechaHora = new SimpleDateFormat("yyyyMMddHHmmss"); String formato = fechaHora.format(new Date()); String ruta = ConstantesUtil.FILE_SYSTEM_INVESTIGACION + campo.getId().toString(); //+"/"+formato + getFilename(file1) File file = new File(ruta); if (!file.exists()) { file.mkdir(); } String filenameArchive = getFilename(file1); file = new File(ruta + "/" + formato + filenameArchive); try (InputStream input = file1.getInputStream()) { Files.copy(input, file.toPath()); } campoDetalle.setFechaRegistro(new Date()); campoDetalle.setIdCampo(campo.getId()); campoDetalle.setNombreArchivo(filenameArchive); campoDetalle.setNombreDocumento(formato + filenameArchive); campoDetalle.setRuta(campo.getId().toString() + "/" + formato + filenameArchive); campoDetalle.setUsuarioRegistro(investigacion.getUsuarioRegistro()); campoDetalle.setNombreRegistro(historialActividad.getNombre()); campoDetalleService.campoDetalleInsertar(campoDetalle); saveActividad(3); } catch (Exception e) { log.error(e.getMessage()); } }