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.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java
public synchronized Collection<ArduinoPlatform> getAvailablePlatforms(IProgressMonitor monitor) throws CoreException { List<ArduinoPlatform> platforms = new ArrayList<>(); URL[] urls = ArduinoPreferences.getBoardUrlList(); SubMonitor sub = SubMonitor.convert(monitor, urls.length + 1); sub.beginTask("Downloading package descriptions", urls.length); //$NON-NLS-1$ for (URL url : urls) { Path packagePath = ArduinoPreferences.getArduinoHome().resolve(Paths.get(url.getPath()).getFileName()); try {/*from w ww . ja v a2s . c om*/ Files.createDirectories(ArduinoPreferences.getArduinoHome()); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", //$NON-NLS-1$ "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); //$NON-NLS-1$ try (InputStream in = connection.getInputStream()) { Files.copy(in, packagePath, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { // Log and continue, URLs sometimes come and go Activator.log(e); } sub.worked(1); } sub.beginTask("Loading available packages", 1); //$NON-NLS-1$ resetPackages(); for (ArduinoPackage pkg : getPackages()) { platforms.addAll(pkg.getAvailablePlatforms()); } sub.done(); return platforms; }
From source file:org.cryptomator.webdav.jackrabbit.AbstractEncryptedNode.java
@Override public void copy(DavResource dest, boolean shallow) throws DavException { final Path src = ResourcePathUtils.getPhysicalPath(this); final Path dst = ResourcePathUtils.getPhysicalPath(dest); try {//from w w w. ja v a2 s. c o m // check for conflicts: if (Files.exists(dst) && Files.getLastModifiedTime(dst).toMillis() > Files.getLastModifiedTime(src).toMillis()) { throw new DavException(DavServletResponse.SC_CONFLICT, "File at destination already exists: " + dst.toString()); } // copy: try { Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { Files.copy(src, dst, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { LOG.error("Error copying file from " + src.toString() + " to " + dst.toString()); throw new IORuntimeException(e); } }
From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java
@ApiOperation(value = "Add a file uploads to property") @RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}) public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId, @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) { LOGGER.info("uploadPost called"); Configuration config = ConfigurationFactory.getConfiguration(); String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR); String baseUrl = config.getString("calipso.baseurl"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf;//from w ww.j a v a 2 s .c o m BinaryFile bf = new BinaryFile(); try { if (itr.hasNext()) { mpf = request.getFile(itr.next()); LOGGER.info("Uploading {}", mpf.getOriginalFilename()); bf.setName(mpf.getOriginalFilename()); bf.setFileNameExtention( mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1)); bf.setContentType(mpf.getContentType()); bf.setSize(mpf.getSize()); // request targets specific path? StringBuffer uploadsPath = new StringBuffer('/') .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class)) .append('/').append(subjectId).append("/uploads/").append(propertyName); bf.setParentPath(uploadsPath.toString()); LOGGER.info("Saving image entity with path: " + bf.getParentPath()); bf = binaryFileService.create(bf); LOGGER.info("file name: {}", bf.getNewFilename()); bf = binaryFileService.findById(bf.getId()); LOGGER.info("file name: {}", bf.getNewFilename()); File storageDirectory = new File(fileUploadDirectory + bf.getParentPath()); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); } LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath()); LOGGER.info("file name: {}", bf.getNewFilename()); File newFile = new File(storageDirectory, bf.getNewFilename()); newFile.createNewFile(); LOGGER.info("newFile path: {}", newFile.getAbsolutePath()); Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename()); ImageIO.write(thumbnail, "png", thumbnailFile); bf.setThumbnailSize(thumbnailFile.length()); bf = binaryFileService.update(bf); // attach file // TODO: add/update to collection Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName); Class clazz = fileField.getType(); if (BinaryFile.class.isAssignableFrom(clazz)) { T target = this.service.findById(subjectId); BeanUtils.setProperty(target, propertyName, bf); this.service.update(target); } bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId()); bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId()); bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId()); bf.setDeleteType("DELETE"); bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />"); } } catch (Exception e) { LOGGER.error("Could not upload file(s) ", e); } return bf; }
From source file:com.cloudbees.clickstack.util.Files2.java
/** * Copy the given {@code zipSubFilePath} of the given {@code zipFile} into the {@code destDir} if this sub file exists. * * @param zipFile the source zip file (e.g. {@code path/to/app.war} * @param zipSubFilePath sub file path in the zip file (e.g. {@code /WEB-INF/web.xml} * @param destDir/*from ww w . j a v a 2s.c o m*/ * @param trimSourcePath indicates if the source path should be trimmed creating the dest file (e.g. should {@code WEB-INF/web.xml} be copied as * {@code dest-dir/WEB-INF/web.xml} or as {@code dest-dir/web.xml}) * @throws RuntimeIOException */ @Nullable public static Path unzipSubFileIfExists(@Nonnull Path zipFile, @Nonnull String zipSubFilePath, @Nonnull final Path destDir, boolean trimSourcePath) throws RuntimeIOException { try { //if the destination doesn't exist, create it if (Files.notExists(destDir)) { logger.trace("Create dir: {}", destDir); Files.createDirectories(destDir); } try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) { final Path root = zipFileSystem.getPath("/"); Path subFile = root.resolve(zipSubFilePath); if (Files.exists(subFile)) { // make file path relative Path destFile; if (trimSourcePath) { destFile = destDir.resolve(subFile.getFileName().toString()); } else { if (Strings2.beginWith(zipSubFilePath, "/")) { destFile = destDir.resolve("." + zipSubFilePath); } else { destFile = destDir.resolve(zipSubFilePath); } } // create parent dirs if needed Files.createDirectories(destFile.getParent()); // copy return Files.copy(subFile, destFile, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); } else { return null; } } } catch (IOException e) { throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubFilePath + " to " + destDir, e); } }
From source file:org.dcm4che3.tool.wadors.WadoRS.java
private static SimpleHTTPResponse sendRequest(final WadoRS main) throws IOException { URL newUrl = new URL(main.getUrl()); LOG.info("WADO-RS URL: {}", newUrl); HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setDoOutput(true);/*from w w w. j a va2 s.co m*/ connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("charset", "utf-8"); String[] acceptHeaders = compileAcceptHeader(main.acceptTypes); LOG.info("Accept-Headers: {}", Arrays.toString(acceptHeaders)); for (String acceptStr : acceptHeaders) connection.addRequestProperty("Accept", acceptStr); if (main.getRequestTimeOut() != null) { connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut())); connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut())); } connection.setUseCaches(false); int responseCode = connection.getResponseCode(); String responseMessage = connection.getResponseMessage(); boolean isErrorCase = responseCode >= HttpURLConnection.HTTP_BAD_REQUEST; if (!isErrorCase) { InputStream in = null; if (connection.getHeaderField("content-type").contains("application/json") || connection.getHeaderField("content-type").contains("application/zip")) { String headerPath; in = connection.getInputStream(); if (main.dumpHeader) headerPath = writeHeader(connection.getHeaderFields(), new File(main.outDir, "out.json" + "-head")); else { headerPath = connection.getHeaderField("content-location"); } File f = new File(main.outDir, connection.getHeaderField("content-type").contains("application/json") ? "out.json" : "out.zip"); Files.copy(in, f.toPath(), StandardCopyOption.REPLACE_EXISTING); main.retrievedInstances.put(headerPath, f.toPath().toAbsolutePath()); } else { if (main.dumpHeader) dumpHeader(main, connection.getHeaderFields()); in = connection.getInputStream(); try { File spool = new File(main.outDir, "Spool"); Files.copy(in, spool.toPath(), StandardCopyOption.REPLACE_EXISTING); String boundary; BufferedReader rdr = new BufferedReader(new InputStreamReader(new FileInputStream(spool))); boundary = (rdr.readLine()); boundary = boundary.substring(2, boundary.length()); rdr.close(); FileInputStream fin = new FileInputStream(spool); new MultipartParser(boundary).parse(fin, new MultipartParser.Handler() { @Override public void bodyPart(int partNumber, MultipartInputStream partIn) throws IOException { Map<String, List<String>> headerParams = partIn.readHeaderParams(); String mediaType; String contentType = headerParams.get("content-type").get(0); if (contentType.contains("transfer-syntax")) mediaType = contentType.split(";")[0]; else mediaType = contentType; // choose writer if (main.isMetadata) { main.writerType = ResponseWriter.XML; } else { if (mediaType.equalsIgnoreCase("application/dicom")) { main.writerType = ResponseWriter.DICOM; } else if (isBulkMediaType(mediaType)) { main.writerType = ResponseWriter.BULK; } else { throw new IllegalArgumentException("Unknown media type " + "returned by server, media type = " + mediaType); } } try { main.writerType.readBody(main, partIn, headerParams); } catch (Exception e) { System.out.println("Error parsing media type to determine extension" + e); } } private boolean isBulkMediaType(String mediaType) { if (mediaType.contains("octet-stream")) return true; for (Field field : MediaTypes.class.getFields()) { try { if (field.getType().equals(String.class)) { String tmp = (String) field.get(field); if (tmp.equalsIgnoreCase(mediaType)) return true; } } catch (Exception e) { System.out.println("Error deciding media type " + e); } } return false; } }); fin.close(); spool.delete(); } catch (Exception e) { System.out.println("Error parsing Server response - " + e); } } } else { LOG.error("Server returned {} - {}", responseCode, responseMessage); } connection.disconnect(); main.response = new WadoRSResponse(responseCode, responseMessage, main.retrievedInstances); return new SimpleHTTPResponse(responseCode, responseMessage); }
From source file:fr.lirmm.yamplusplus.yampponline.YamFileHandler.java
/** * Upload a file from HTTP request. It downloads the file if it is an URL or * get it from the POST request. It stores the contentString in a file in the * tmp directory. In a subdirectory /tmp/yam-gui/ + subDir generated + / + * filename (source.owl or target.owl). Usually the sub directory is randomly * generated before calling uploadFile And return the path to the created * file. OntName can be "source" or "target" * * @param ontName/*from ww w .j av a 2s .c om*/ * @param subDir * @param request * @return file storage path * @throws IOException * @throws java.net.URISyntaxException * @throws javax.servlet.ServletException */ public String uploadFile(String ontName, String subDir, HttpServletRequest request) throws IOException, URISyntaxException, ServletException { // Store given ontology in /tmp/yam-gui/SUBDIR/source.owl String storagePath = this.tmpDir + subDir + "/" + ontName + ".owl"; // Check if an URL have been provided String ontologyUrl = request.getParameter(ontName + "Url"); // Use URL in priority. If not, then get the uploaded file from the form if (ontologyUrl != null && !ontologyUrl.isEmpty()) { //ontologyString = getUrlContent(ontologyUrl); TO REMOVE // Copy file from remote URL SystemUtils.copyFileFromURL(new URI(ontologyUrl), storagePath); } else { // Get file from uploaded file in form Part filePart = null; Logger.getLogger(Matcher.class.getName()).log(Level.INFO, "Justeeee AVANT request.getPart(fileParam) dans readFileFromRequest"); // Retrieve file from input where name is sourceFile or targetFile filePart = request.getPart(ontName + "File"); if (filePart != null) { //String uploadedFilename = filePart.getSubmittedFileName(); //storagePath = this.tmpDir + subDir + "/" + uploadedFilename; InputStream fileStream = filePart.getInputStream(); // Write InputStream to file File storageFile = new File(storagePath); storageFile.getParentFile().mkdirs(); java.nio.file.Files.copy(fileStream, storageFile.toPath(), StandardCopyOption.REPLACE_EXISTING); IOUtils.closeQuietly(fileStream); } } Logger.getLogger(Matcher.class.getName()).log(Level.SEVERE, "End uploadFileee"); // Store ontology in workDir if asked (/srv/yam-gui/save/field/username) return storagePath; }
From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceFileHandler.java
private File copyOrphanFileToWorkspace(File file, Workspace workspace) throws URISyntaxException { File wsOrphansDirectory = new File(workspaceBaseDirectory, workspace.getWorkspaceID() + "/" + orphansDirectoryName); File origOrphansDirectory = archiveFileLocationProvider .getOrphansDirectory(workspace.getTopNodeArchiveURL().toURI()); File destPath = new File(wsOrphansDirectory, origOrphansDirectory.toPath().relativize(file.getParentFile().toPath()).toString()); File destFile = null;/*from w w w . j ava 2 s.co m*/ try { //create directories if (destPath.exists()) { logger.info("Workspace directory: [" + destPath.toPath().toString() + "] for orphan: [" + file.getName() + "] already exists"); } else { if (destPath.mkdirs()) { logger.info("Workspace directory: [" + destPath.toPath().toString() + "] for orphan: [" + file.getName() + "] successfully created"); } else { String errorMessage = "Workspace directory: [" + destPath.toPath().toString() + "] for orphan: [" + file.getName() + "] could not be created"; throw new IOException(errorMessage); } } if (Files.isSymbolicLink(file.toPath())) { file = Files.readSymbolicLink(file.toPath()).toFile(); } destFile = new File(destPath, file.getName()); Files.copy(file.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("Cannot copy metadata file: [" + file.toPath() + "] to workspace directory: [" + destPath.toString(), e); } return destFile; }
From source file:password.pwm.config.stored.ConfigurationReader.java
public void saveConfiguration(final StoredConfigurationImpl storedConfiguration, final PwmApplication pwmApplication, final SessionLabel sessionLabel) throws IOException, PwmUnrecoverableException, PwmOperationalException { File backupDirectory = null;//from w w w .ja v a 2s . com int backupRotations = 0; if (pwmApplication != null) { final Configuration configuration = new Configuration(storedConfiguration); final String backupDirSetting = configuration.readAppProperty(AppProperty.BACKUP_LOCATION); if (backupDirSetting != null && backupDirSetting.length() > 0) { final File pwmPath = pwmApplication.getPwmEnvironment().getApplicationPath(); backupDirectory = FileSystemUtility.figureFilepath(backupDirSetting, pwmPath); } backupRotations = Integer.parseInt(configuration.readAppProperty(AppProperty.BACKUP_CONFIG_COUNT)); } { // increment the config epoch String epochStrValue = storedConfiguration.readConfigProperty(ConfigurationProperty.CONFIG_EPOCH); try { final BigInteger epochValue = epochStrValue == null || epochStrValue.length() < 0 ? BigInteger.ZERO : new BigInteger(epochStrValue); epochStrValue = epochValue.add(BigInteger.ONE).toString(); } catch (Exception e) { LOGGER.error(sessionLabel, "error trying to parse previous config epoch property: " + e.getMessage()); epochStrValue = "0"; } storedConfiguration.writeConfigProperty(ConfigurationProperty.CONFIG_EPOCH, epochStrValue); } if (backupDirectory != null && !backupDirectory.exists()) { if (!backupDirectory.mkdirs()) { throw new PwmOperationalException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unable to create backup directory structure '" + backupDirectory.toString() + "'")); } } try { final File tempWriteFile = new File(configFile.getAbsoluteFile() + ".new"); LOGGER.info(sessionLabel, "beginning write to configuration file " + tempWriteFile); saveInProgress = true; storedConfiguration.toXml(new FileOutputStream(tempWriteFile, false)); LOGGER.info("saved configuration " + JsonUtil.serialize(storedConfiguration.toJsonDebugObject())); if (pwmApplication != null) { final String actualChecksum = storedConfiguration.settingChecksum(); pwmApplication.writeAppAttribute(PwmApplication.AppAttribute.CONFIG_HASH, actualChecksum); } LOGGER.trace( "renaming file " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath()); try { Files.move(tempWriteFile.toPath(), configFile.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); } catch (Exception e) { final String errorMsg = "unable to rename temporary save file from " + tempWriteFile.getAbsolutePath() + " to " + configFile.getAbsolutePath() + "; error: " + e.getMessage(); throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, errorMsg)); } if (backupDirectory != null) { final String configFileName = configFile.getName(); final String backupFilePath = backupDirectory.getAbsolutePath() + File.separatorChar + configFileName + "-backup"; final File backupFile = new File(backupFilePath); FileSystemUtility.rotateBackups(backupFile, backupRotations); storedConfiguration.toXml(new FileOutputStream(backupFile, false)); } } finally { saveInProgress = false; } }
From source file:com.jeet.cli.Admin.java
private static void downloadFile(Map fileMap) { System.out.print("Enter File Index(0 to cancel): "); String choise = null;//w w w . ja va 2 s.c o m try { choise = bufferRead.readLine(); } catch (IOException ioe) { System.err.println("Error in reading option."); System.err.println("Please try again."); downloadFile(fileMap); } if (choise != null && NumberUtils.isDigits(choise)) { Integer choiseInt = Integer.parseInt(choise); if (fileMap.containsKey(choiseInt)) { try { String key = fileMap.get(choiseInt).toString(); File file = FileUtil.downloadAndDecryptFile(key); String downloadFilePath = Constants.DOWNLOAD_FOLDER + fileMap.get(choiseInt).toString(); downloadFilePath = downloadFilePath.replaceAll("/", "\\\\"); Files.copy(file.toPath(), (new File(downloadFilePath)).toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("File Downloaded to: " + downloadFilePath); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Error in downlaoding file."); } askFileListInputs(fileMap); } else if (choiseInt.equals(0)) { System.out.println("Download file canceled."); askFileListInputs(fileMap); } else { System.err.println("Please select from provided options only."); downloadFile(fileMap); } } else { System.err.println("Please enter digits only."); downloadFile(fileMap); } }
From source file:org.wso2.carbon.container.CarbonTestContainer.java
/** * Copy files specified in the carbon file copy option to the destination path. * * @param carbonHome carbon home/* w ww .j a v a 2s. c o m*/ */ private void copyFiles(Path carbonHome) { Arrays.asList(system.getOptions(CopyFileOption.class)).forEach(option -> { try { Files.copy(option.getSourcePath(), carbonHome.resolve(option.getDestinationPath()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new TestContainerException("Error while copying configuration files", e); } }); }