List of usage examples for java.nio.file StandardCopyOption REPLACE_EXISTING
StandardCopyOption REPLACE_EXISTING
To view the source code for java.nio.file StandardCopyOption REPLACE_EXISTING.
Click Source Link
From source file:org.n52.wps.server.database.PostgresDatabase.java
@Override protected synchronized String insertResultEntity(InputStream stream, String id, String type, String mimeType) { Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); FileInputStream fis = null;// w w w. jav a 2 s.com Boolean storingOutput = null != id && id.toLowerCase().contains("output"); Boolean saveResultsToDB = Boolean.parseBoolean(getDatabaseProperties("saveResultsToDB")); String filename = storingOutput ? id : UUID.randomUUID().toString(); Path filePath = new File(BASE_DIRECTORY, filename).toPath(); try { filePath = Files.createFile(filePath); Files.copy(stream, filePath, StandardCopyOption.REPLACE_EXISTING); fis = new FileInputStream(filePath.toFile()); AbstractDatabase.insertSQL.setString(INSERT_COLUMN_REQUEST_ID, id); AbstractDatabase.insertSQL.setTimestamp(INSERT_COLUMN_REQUEST_DATE, timestamp); AbstractDatabase.insertSQL.setString(INSERT_COLUMN_RESPONSE_TYPE, type); AbstractDatabase.insertSQL.setString(INSERT_COLUMN_MIME_TYPE, mimeType); if (storingOutput) { if (!saveResultsToDB) { byte[] filePathByteArray = filePath.toUri().toString().getBytes(); AbstractDatabase.insertSQL.setAsciiStream(INSERT_COLUMN_RESPONSE, new ByteArrayInputStream(filePathByteArray), filePathByteArray.length); } else { AbstractDatabase.insertSQL.setAsciiStream(INSERT_COLUMN_RESPONSE, fis, (int) filePath.toFile().length()); } } else { AbstractDatabase.insertSQL.setAsciiStream(INSERT_COLUMN_RESPONSE, fis, (int) filePath.toFile().length()); } AbstractDatabase.insertSQL.executeUpdate(); getConnection().commit(); } catch (SQLException e) { LOGGER.error("Could not insert Response into database.", e); } catch (IOException e) { LOGGER.error("Could not insert Response into database.", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { LOGGER.error("Could not close file input stream", e); } } // If we are storing output, we want to only delete the file if we're // storing the results to the database. Otherwise, don't delete the // file since that will be served on request if (filePath != null) { try { if (storingOutput) { if (saveResultsToDB) { Files.deleteIfExists(filePath); } } else { Files.deleteIfExists(filePath); } } catch (IOException e) { LOGGER.error("Could not delete file: " + filePath.toString(), e); } } } return generateRetrieveResultURL(id); }
From source file:org.holodeckb2b.ebms3.submit.core.MessageSubmitter.java
/** * Helper method to copy or move the payloads to an internal directory so they will be kept available during the * processing of the message (which may include resending). * /*from ww w.j a v a2s . c o m*/ * @param um The meta data on the submitted user message * @param pmode The P-Mode that governs the processing this user message * @throws IOException When the payload could not be moved/copied to the internal payload storage * @throws DatabaseException When the new payload locations couldn't be saved to the database */ private void moveOrCopyPayloads(EntityProxy<UserMessage> um, boolean move) throws IOException, DatabaseException { // Path to the "temp" dir where to store payloads during processing String intPlDir = HolodeckB2BCoreInterface.getConfiguration().getTempDirectory() + "plcout"; // Create the directory if needed Path pathPlDir = Paths.get(intPlDir); if (!Files.exists(pathPlDir)) { log.debug("Create the directory [" + intPlDir + "] for storing payload files"); Files.createDirectories(pathPlDir); } Collection<IPayload> payloads = um.entity.getPayloads(); if (!Utils.isNullOrEmpty(payloads)) { for (IPayload ip : payloads) { Payload p = (Payload) ip; Path srcPath = Paths.get(p.getContentLocation()); // Ensure that the filename in the temp directory is unique Path destPath = Paths.get(Utils.preventDuplicateFileName(intPlDir + "/" + srcPath.getFileName())); if (move) { log.debug("Moving payload [" + p.getContentLocation() + "] to internal directory"); Files.move(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING); } else { log.debug("Copying payload [" + p.getContentLocation() + "] to internal directory"); Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING); } log.debug("Payload moved/copied to internal directory"); p.setContentLocation(destPath.toString()); } // Update the database with new locations MessageUnitDAO.updateMessageUnitInfo(um); } }
From source file:sonicScream.controllers.CategoryTabController.java
/** * See replaceSound(). This method is used for testing, so we can avoid needing to invoke a FileChooser. * @param newSoundFile The sound file to use for replacement. * @throws IOException//from w w w . j a va 2 s . c o m */ public void replaceSound(Path newSoundFile) throws IOException { TreeItem<String> selectedNode = (TreeItem<String>) CategoryTabTreeView.getSelectionModel() .getSelectedItem(); SettingsService settings = (SettingsService) ServiceLocator.getService(SettingsService.class); Script activeScript = (Script) CategoryTabComboBox.getValue(); activeScript.getVPKPath(); String trimmedFileName = newSoundFile.getFileName().toString().toLowerCase().replace(" ", "_"); String profileDir = SettingsUtils.getProfileDirectory(activeScript.getParentCategoryName()).toString(); Path destPath = Paths.get(profileDir, "/sonic-scream/sounds", trimmedFileName); if (!Files.exists(destPath)) { Files.createDirectories(destPath.getParent()); } Files.copy(newSoundFile, destPath, StandardCopyOption.REPLACE_EXISTING); selectedNode.setValue("sounds/" + trimmedFileName.replace(".mp3", ".vsnd").replace(".wav", ".vsnd")); activeScript.convertToLocalScript(); }
From source file:gov.vha.isaac.rf2.filter.RF2Filter.java
private void handleFile(Path inputFile, Path outputFile) throws IOException { boolean justCopy = true; boolean justSkip = false; if (inputFile.toFile().getName().toLowerCase().endsWith(".txt")) { justCopy = false;// ww w . j a v a 2 s. c om //Filter the file BufferedReader fileReader = new BufferedReader( new InputStreamReader(new BOMInputStream(new FileInputStream(inputFile.toFile())), "UTF-8")); BufferedWriter fileWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(outputFile.toFile()), "UTF-8")); PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); CSVReader csvReader = new CSVReader(new InputStreamReader(pis), '\t', CSVParser.NULL_CHARACTER); //don't look for quotes, the data is bad, and has floating instances of '"' all by itself boolean firstLine = true; String line = null; long kept = 0; long skipped = 0; long total = 0; int moduleColumn = -1; while ((line = fileReader.readLine()) != null) { total++; //Write this line into the CSV parser pos.write(line.getBytes()); pos.write("\r\n".getBytes()); pos.flush(); String[] fields = csvReader.readNext(); boolean correctModule = false; for (String ms : moduleStrings_) { if (moduleColumn >= 0 && fields[moduleColumn].equals(ms)) { correctModule = true; break; } } if (firstLine || correctModule) { kept++; fileWriter.write(line); fileWriter.write("\r\n"); } else { //don't write line skipped++; } if (firstLine) { log("Filtering file " + inputDirectory.toPath().relativize(inputFile).toString()); firstLine = false; if (fields.length < 2) { log("txt file doesn't look like a data file - abort and just copy."); justCopy = true; break; } for (int i = 0; i < fields.length; i++) { if (fields[i].equals("moduleId")) { moduleColumn = i; break; } } if (moduleColumn < 0) { log("No moduleId column found - skipping file"); justSkip = true; break; } } } fileReader.close(); csvReader.close(); fileWriter.close(); if (!justCopy) { log("Kept " + kept + " Skipped " + skipped + " out of " + total + " lines in " + inputDirectory.toPath().relativize(inputFile).toString()); } } if (justCopy) { //Just copy the file Files.copy(inputFile, outputFile, StandardCopyOption.REPLACE_EXISTING); log("Copied file " + inputDirectory.toPath().relativize(inputFile).toString()); } if (justSkip) { Files.delete(outputFile); log("Skipped file " + inputDirectory.toPath().relativize(inputFile).toString() + " because it doesn't contain a moduleId"); } }
From source file:schemacrawler.tools.integration.maven.SchemaCrawlerMojo.java
/** * {@inheritDoc}//from w w w. j av a 2 s . com * * @see org.apache.maven.reporting.AbstractMavenReport#executeReport(java.util.Locale) */ @Override protected void executeReport(final Locale locale) throws MavenReportException { final Log logger = getLog(); try { fixClassPath(); final Sink sink = getSink(); logger.info(sink.getClass().getName()); final Path outputFile = executeSchemaCrawler(); final Consumer<? super String> outputLine = line -> { sink.rawText(line); sink.rawText("\n"); sink.flush(); }; final OutputFormat outputFormat = getOutputFormat(); sink.comment("BEGIN SchemaCrawler Report"); if (outputFormat == TextOutputFormat.html || outputFormat == GraphOutputFormat.htmlx) { Files.lines(outputFile).forEach(outputLine); } else if (outputFormat instanceof TextOutputFormat) { sink.rawText("<pre>"); Files.lines(outputFile).forEach(outputLine); sink.rawText("</pre>"); } else if (outputFormat instanceof GraphOutputFormat) { final Path graphFile = Paths.get(getReportOutputDirectory().getAbsolutePath(), "schemacrawler." + outputFormat.getFormat()); Files.move(outputFile, graphFile, StandardCopyOption.REPLACE_EXISTING); sink.figure(); sink.figureGraphics(graphFile.getFileName().toString()); sink.figure_(); } sink.comment("END SchemaCrawler Report"); sink.flush(); } catch (final Exception e) { throw new MavenReportException("Error executing SchemaCrawler command " + command, e); } }
From source file:io.takari.maven.testing.executor.junit.MavenVersionResolver.java
private void createMavenInstallation(List<Repository> repositories, String version, File localrepo, File targetdir) throws Exception { String versionDir = "org/apache/maven/apache-maven/" + version + "/"; String filename = "apache-maven-" + version + "-bin.tar.gz"; File archive = new File(localrepo, versionDir + filename); if (archive.canRead()) { unarchive(archive, targetdir);/* w w w . ja v a2s. c o m*/ return; } Exception cause = null; for (Repository repository : repositories) { setHttpCredentials(repository.credentials); String effectiveVersion; if (isSnapshot(version)) { try { effectiveVersion = getQualifiedVersion(repository.url, versionDir); } catch (FileNotFoundException e) { continue; } catch (IOException e) { cause = e; continue; } if (effectiveVersion == null) { continue; } } else { effectiveVersion = version; } filename = "apache-maven-" + effectiveVersion + "-bin.tar.gz"; archive = new File(localrepo, versionDir + filename); if (archive.canRead()) { unarchive(archive, targetdir); return; } URL resource = new URL(repository.url, versionDir + filename); try (InputStream is = openStream(resource)) { archive.getParentFile().mkdirs(); File tmpfile = File.createTempFile(filename, ".tmp", archive.getParentFile()); try { copy(is, tmpfile); unarchive(tmpfile, targetdir); Files.move(tmpfile.toPath(), archive.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } finally { tmpfile.delete(); } return; } catch (FileNotFoundException e) { // ignore the exception. this is expected to happen quite often and not a failure by iteself } catch (IOException e) { cause = e; } } Exception exception = new FileNotFoundException( "Could not download maven version " + version + " from any configured repository"); exception.initCause(cause); throw exception; }
From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java
@Test public void testCopyToPathWithOptions() throws IOException { InputStream inputStream = new ByteArrayInputStream("hello!".getBytes(UTF_8)); filesystem.copyToPath(inputStream, Paths.get("replace_me.txt")); inputStream = new ByteArrayInputStream("hello again!".getBytes(UTF_8)); filesystem.copyToPath(inputStream, Paths.get("replace_me.txt"), StandardCopyOption.REPLACE_EXISTING); assertEquals("The bytes on disk should match those from the second InputStream.", "hello again!", new String(Files.readAllBytes(tmp.getRoot().resolve("replace_me.txt")), UTF_8)); }
From source file:dialog.DialogFunctionUser.java
private void actionEditUser() { if (!isValidData()) { return;// w w w. j a va 2 s . co m } if (!isValidData()) { return; } String username = tfUsername.getText(); String fullname = tfFullname.getText(); String password = mUser.getPassword(); if (tfPassword.getPassword().length == 0) { password = new String(tfPassword.getPassword()); password = LibraryString.md5(password); } int role = cbRole.getSelectedIndex(); if (mAvatar != null) { User objUser = new User(mUser.getIdUser(), username, password, fullname, role, new Date(System.currentTimeMillis()), mAvatar.getPath()); if (mControllerUser.editItem(objUser, mRow)) { String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "." + FilenameUtils.getExtension(mAvatar.getName()); Path source = Paths.get(mAvatar.toURI()); Path destination = Paths.get("files/" + fileName); Path pathOldAvatar = Paths.get(mUser.getAvatar()); try { Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); Files.deleteIfExists(pathOldAvatar); } catch (IOException ex) { Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex); } ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } } else { User objUser = new User(mUser.getIdUser(), username, password, fullname, role, new Date(System.currentTimeMillis()), mUser.getAvatar()); if (mControllerUser.editItem(objUser, mRow)) { ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png")); JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success", JOptionPane.INFORMATION_MESSAGE, icon); } else { JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail", JOptionPane.ERROR_MESSAGE); } } this.dispose(); }
From source file:cn.edu.zjnu.acm.judge.core.Judger.java
private boolean compile(RunRecord runRecord) throws IOException { String source = runRecord.getSource(); if (StringUtils.isEmptyOrWhitespace(source)) { return false; }/*from ww w . ja v a 2 s . c o m*/ Path work = runRecord.getWorkDirectory(); final String main = "Main"; Files.createDirectories(work); Path sourceFile = work.resolve(main + "." + runRecord.getLanguage().getSourceExtension()); //??? Files.copy(new ByteArrayInputStream(source.getBytes(Platform.getCharset())), sourceFile, StandardCopyOption.REPLACE_EXISTING); String compileCommand = runRecord.getLanguage().getCompileCommand(); log.debug("Compile Command: {}", compileCommand); // if (StringUtils.isEmptyOrWhitespace(compileCommand)) { return true; } assert compileCommand != null; // // VC++? // G++? Path compileInfo = work.resolve("compileinfo.txt"); Process process = ProcessCreationHelper.execute(new ProcessBuilder(compileCommand.split("\\s+")) .directory(work.toFile()).redirectOutput(compileInfo.toFile()).redirectErrorStream(true)::start); process.getInputStream().close(); try { process.waitFor(45, TimeUnit.SECONDS); } catch (InterruptedException ex) { throw new InterruptedIOException(); } //? String errorInfo; if (process.isAlive()) { process.destroy(); try { process.waitFor(); } catch (InterruptedException ex) { throw new InterruptedIOException(); } errorInfo = "Compile timeout\nOutput:\n" + collectLines(compileInfo); } else { errorInfo = collectLines(compileInfo); } log.debug("errorInfo = {}", errorInfo); Path executable = work.resolve(main + "." + runRecord.getLanguage().getExecutableExtension()); //?? log.debug("executable = {}", executable); boolean compileOK = Files.exists(executable); // if (!compileOK) { submissionMapper.updateResult(runRecord.getSubmissionId(), ResultType.COMPILE_ERROR, 0, 0); submissionMapper.saveCompileInfo(runRecord.getSubmissionId(), errorInfo); updateSubmissionStatus(runRecord); } return compileOK; }
From source file:com.twentyn.bioreactor.sensors.Sensor.java
private void atomicWrite(SensorData sensorData) throws IOException { // Write a sensor reading to a temporary file objectMapper.writeValue(sensorReadingTmp, sensorData); // Atomically move the temporary file once written to the location Files.move(sensorReadingTmp.toPath(), sensorReadingFilePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); // Append sensor reading to log file objectMapper.writeValue(jsonGenerator, sensorData); }