List of usage examples for java.nio.file Files deleteIfExists
public static boolean deleteIfExists(Path path) throws IOException
From source file:com.eucalyptus.blockstorage.ceph.CephRbdProvider.java
@Override public StorageResource generateSnapshotDelta(String volumeId, String snapshotId, String snapPointId, String prevSnapshotId, String prevSnapPointId) throws EucalyptusCloudException { LOG.info("Generating snapshot delta volumeId=" + volumeId + ", snapshot=" + snapshotId + ", snapshotPointId=" + snapPointId + ", prevSnapshotId=" + prevSnapshotId + ", prevSnapPointId=" + prevSnapPointId);/*ww w . j a v a2 s . c o m*/ String diffName = null; try { String prevSnapPoint = null; if (StringUtils.isBlank(prevSnapPointId)) { prevSnapPoint = CephRbdInfo.SNAPSHOT_FOR_PREFIX + prevSnapshotId; } else if (prevSnapPointId.contains(CephRbdInfo.POOL_IMAGE_DELIMITER) && prevSnapPointId.contains(CephRbdInfo.IMAGE_SNAPSHOT_DELIMITER)) { CanonicalRbdObject prevSnap = CanonicalRbdObject.parse(prevSnapPointId); if (prevSnap != null && !Strings.isNullOrEmpty(prevSnap.getSnapshot())) { prevSnapPoint = prevSnap.getSnapshot(); } else { throw new EucalyptusCloudException( "Invalid snapshotPointId, expected pool/image@snapshot format but got " + prevSnapPointId); } } else { prevSnapPoint = prevSnapPointId; } Path diffPath = Files.createTempFile(Paths.get("/var/tmp"), snapshotId + "_" + prevSnapshotId + "_", ".diff"); Files.deleteIfExists(diffPath); // Delete the file before invoking rbd. rbd does not like the file being present diffName = diffPath.toString(); String[] cmd = new String[] { StorageProperties.EUCA_ROOT_WRAPPER, "rbd", "--id", cachedConfig.getCephUser(), "--keyring", cachedConfig.getCephKeyringFile(), "export-diff", snapPointId, diffName, "--from-snap", prevSnapPoint }; LOG.debug("Executing: " + Joiner.on(" ").skipNulls().join(cmd)); CommandOutput output = SystemUtil.runWithRawOutput(cmd); if (output != null) { LOG.debug("Dump from rbd command:\nreturn=" + output.returnValue + "\nstdout=" + output.output + "\nstderr=" + output.error); if (output.returnValue != 0) { throw new EucalyptusCloudException("Unable to execute rbd command. return=" + output.returnValue + ", stdout=" + output.output + ", stderr=" + output.error); } } return new FileResource(snapshotId, diffName); } catch (Exception e) { LOG.warn("Failed to generate snapshot delta between " + snapshotId + " and " + prevSnapshotId, e); try { if (!Strings.isNullOrEmpty(diffName)) { LOG.debug("Deleting file " + diffName); new File(diffName).delete(); } } catch (Exception ie) { LOG.warn("Failed to delete file " + diffName, ie); } throw new EucalyptusCloudException( "Failed to generate snapshot delta between " + snapshotId + " and " + prevSnapshotId, e); } }
From source file:org.tinymediamanager.core.Utils.java
/** * <b>PHYSICALLY</b> deletes a file by moving it to datasource backup folder<br> * DS\.backup\<filename><br> * maintaining its originating directory * /* ww w . j a va 2 s . c o m*/ * @param file * the file to be deleted * @param datasource * the data source (for the location of the backup folder) * @return true/false if successful */ public static boolean deleteFileWithBackup(Path file, String datasource) { String fn = file.toAbsolutePath().toString(); if (!fn.startsWith(datasource)) { // safety LOGGER.warn("could not delete file '" + fn + "': datasource '" + datasource + "' does not match"); return false; } if (Files.isDirectory(file)) { LOGGER.warn("could not delete file '" + fn + "': file is a directory!"); return false; } // inject backup path fn = fn.replace(datasource, datasource + FileSystems.getDefault().getSeparator() + Constants.BACKUP_FOLDER); // backup try { // create path Path backup = Paths.get(fn); if (!Files.exists(backup.getParent())) { Files.createDirectories(backup.getParent()); } // overwrite backup file by deletion prior Files.deleteIfExists(backup); return moveFileSafe(file, backup); } catch (IOException e) { LOGGER.warn("Could not delete file: " + e.getMessage()); return false; } }
From source file:org.tinymediamanager.core.Utils.java
/** * <b>PHYSICALLY</b> deletes a file (w/o backup)<br> * only doing a check if it is not a directory * //from w ww. ja va 2 s . com * @param file * the file to be deleted * @return true/false if successful */ public static boolean deleteFileSafely(Path file) { file = file.toAbsolutePath(); if (Files.isDirectory(file)) { LOGGER.warn("Will not delete file '" + file + "': file is a directory!"); return false; } try { Files.deleteIfExists(file); } catch (Exception e) { LOGGER.warn("Could not delete file: " + e.getMessage()); return false; } return true; }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
public boolean createSiteCloneRemoteGitRepo(String siteId, String sandboxBranch, String remoteName, String remoteUrl, String remoteBranch, boolean singleBranch, String authenticationType, String remoteUsername, String remotePassword, String remoteToken, String remotePrivateKey) throws InvalidRemoteRepositoryException, InvalidRemoteRepositoryCredentialsException, RemoteRepositoryNotFoundException, ServiceException { boolean toRet = true; // prepare a new folder for the cloned repository Path siteSandboxPath = buildRepoPath(SANDBOX, siteId); File localPath = siteSandboxPath.toFile(); localPath.delete();//from ww w. jav a2 s . com logger.debug("Add user credentials if provided"); // then clone logger.debug("Cloning from " + remoteUrl + " to " + localPath); CloneCommand cloneCommand = Git.cloneRepository(); Git cloneResult = null; try { final Path tempKey = Files.createTempFile(UUID.randomUUID().toString(), ".tmp"); switch (authenticationType) { case RemoteRepository.AuthenticationType.NONE: logger.debug("No authentication"); break; case RemoteRepository.AuthenticationType.BASIC: logger.debug("Basic authentication"); cloneCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider(remoteUsername, remotePassword)); break; case RemoteRepository.AuthenticationType.TOKEN: logger.debug("Token based authentication"); cloneCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider(remoteToken, StringUtils.EMPTY)); break; case RemoteRepository.AuthenticationType.PRIVATE_KEY: logger.debug("Private key authentication"); tempKey.toFile().deleteOnExit(); cloneCommand.setTransportConfigCallback(new TransportConfigCallback() { @Override public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(getSshSessionFactory(remotePrivateKey, tempKey)); } }); break; default: throw new ServiceException("Unsupported authentication type " + authenticationType); } if (StringUtils.isNotEmpty(remoteBranch)) { cloneCommand.setBranch(remoteBranch); } cloneResult = cloneCommand.setURI(remoteUrl).setDirectory(localPath).setRemote(remoteName) .setCloneAllBranches(!singleBranch).call(); Files.deleteIfExists(tempKey); Repository sandboxRepo = checkIfCloneWasOk(cloneResult, remoteName, remoteUrl); sandboxRepo = optimizeRepository(sandboxRepo); sandboxes.put(siteId, sandboxRepo); } catch (InvalidRemoteException e) { logger.error("Invalid remote repository: " + remoteName + " (" + remoteUrl + ")", e); throw new InvalidRemoteRepositoryException( "Invalid remote repository: " + remoteName + " (" + remoteUrl + ")"); } catch (TransportException e) { if (StringUtils.endsWithIgnoreCase(e.getMessage(), "not authorized")) { logger.error("Bad credentials or read only repository: " + remoteName + " (" + remoteUrl + ")", e); throw new InvalidRemoteRepositoryCredentialsException("Bad credentials or read only repository: " + remoteName + " (" + remoteUrl + ") for username " + remoteUsername, e); } else { logger.error("Remote repository not found: " + remoteName + " (" + remoteUrl + ")", e); throw new RemoteRepositoryNotFoundException( "Remote repository not found: " + remoteName + " (" + remoteUrl + ")"); } } catch (GitAPIException | IOException e) { logger.error("Error while creating repository for site with path" + siteSandboxPath.toString(), e); toRet = false; } finally { if (cloneResult != null) { cloneResult.close(); } } return toRet; }
From source file:com.eucalyptus.blockstorage.S3SnapshotTransfer.java
private void deleteFile(String fileName) { if (StringUtils.isNotBlank(fileName)) { try {// w w w. ja v a 2 s. c om Files.deleteIfExists(Paths.get(fileName)); } catch (IOException e) { LOG.debug("Failed to delete file: " + fileName); } } }
From source file:com.eucalyptus.blockstorage.S3SnapshotTransfer.java
private void deleteFile(Path path) { try {// w w w .j a v a2 s . co m Files.deleteIfExists(path); } catch (IOException e) { LOG.debug("Failed to delete file: " + path.toString()); } }
From source file:misc.FileHandler.java
/** * Writes the given synchronization version to the version file which * belongs to the given file name. The version file is created, if it does * not exist yet. Returns whether the version file was successfully written. * /*from w ww. ja v a2 s . co m*/ * @param version * the version number up to which all actions have been executed. * Must be at least <code>0</code>. * @param clientRoot * the complete path to the client's root directory. Must exist. * @param syncRoot * the complete path to the synchronization root directory. Must * exist. * @param pathLocal * the local path to synchronize containing an access bundle. * Must be relative to <code>clientRoot</code>. May not be * <code>null</code>. * @return <code>true</code>, if the version file was successfully written. * Otherwise, <code>false</code>. */ public static boolean writeVersion(int version, Path clientRoot, Path syncRoot, Path pathLocal) { if (version < 0) { throw new IllegalArgumentException("version must be at least 0!"); } if ((clientRoot == null) || !Files.isDirectory(clientRoot)) { throw new IllegalArgumentException("clientRoot must be an existing directory!"); } if ((syncRoot == null) || !Files.isDirectory(syncRoot)) { throw new IllegalArgumentException("syncRoot must be an existing directory!"); } if (pathLocal == null) { throw new NullPointerException("pathLocal may not be null!"); } boolean success = false; Path arbitraryFileName = Paths.get(pathLocal.toString(), "arbitrary"); Path accessBundleDirectory = FileHandler.getAccessBundleDirectory(clientRoot, arbitraryFileName); if (accessBundleDirectory != null) { Path versionFile = Paths.get(syncRoot.toString(), accessBundleDirectory.toString(), SynchronizationExecutor.VERSION_FILE); FileHandler.makeParentDirs(versionFile); /* * Write the new version into a temporary file and rename it to the * version file. */ Path tempFile = FileHandler.getTempFile(versionFile); if (tempFile != null) { try (BufferedWriter writer = Files.newBufferedWriter(tempFile, Coder.CHARSET);) { writer.write(String.valueOf(version)); writer.write('\n'); writer.flush(); Files.move(tempFile, versionFile, StandardCopyOption.REPLACE_EXISTING); success = true; } catch (IOException e) { Logger.logError(e); } finally { if (tempFile != null) { try { Files.deleteIfExists(tempFile); } catch (IOException e) { Logger.logError(e); } } } } } return success; }
From source file:org.fao.geonet.api.records.MetadataInsertDeleteApi.java
@ApiOperation(value = "Add a map metadata record from OGC OWS context", notes = "Add record in the catalog by uploading a map context.", nickname = "insertOgcMapContextFile") @RequestMapping(value = "/importfrommap", method = { RequestMethod.POST, }, produces = { MediaType.APPLICATION_JSON_VALUE }) @ApiResponses(value = { @ApiResponse(code = 201, message = API_PARAM_REPORT_ABOUT_IMPORTED_RECORDS), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_EDITOR) }) @PreAuthorize("hasRole('Editor')") @ResponseStatus(HttpStatus.CREATED)//from w w w . j a v a 2s.co m @ResponseBody public SimpleMetadataProcessingReport insertOgcMapContextFile( @ApiParam(value = "A map title", required = true) @RequestParam(value = "title", required = true) final String title, @ApiParam(value = "A map abstract", required = false) @RequestParam(value = "recordAbstract", required = false) final String recordAbstract, @ApiParam(value = "OGC OWS context as string", required = false) @RequestParam(value = "xml", required = false) final String xml, @ApiParam(value = "OGC OWS context file name", required = false) @RequestParam(value = "filename", required = false) final String filename, @ApiParam(value = "OGC OWS context URL", required = false) @RequestParam(value = "url", required = false) final String url, @ApiParam(value = "A map viewer URL to visualize the map", required = false) @RequestParam(value = "viewerUrl", required = false) final String viewerUrl, @ApiParam(value = "Map overview as PNG (base64 encoded)", required = false) @RequestParam(value = "overview", required = false) final String overview, @ApiParam(value = "Map overview filename", required = false) @RequestParam(value = "overviewFilename", required = false) final String overviewFilename, @ApiParam(value = "Topic category", required = false) @RequestParam(value = "topic", required = false) final String topic, @ApiParam(value = API_PARAM_RECORD_UUID_PROCESSING, required = false, defaultValue = "NOTHING") @RequestParam(required = false, defaultValue = "NOTHING") final MEFLib.UuidAction uuidProcessing, @ApiParam(value = API_PARAP_RECORD_GROUP, required = false) @RequestParam(required = false) final String group, HttpServletRequest request) throws Exception { if (StringUtils.isEmpty(xml) && StringUtils.isEmpty(url)) { throw new IllegalArgumentException(String.format("A context as XML or a remote URL MUST be provided.")); } if (StringUtils.isEmpty(xml) && StringUtils.isEmpty(filename)) { throw new IllegalArgumentException( String.format("A context as XML will be saved as a record attachement. " + "You MUST provide a filename in this case.")); } ServiceContext context = ApiUtils.createServiceContext(request); ApplicationContext applicationContext = ApplicationContextHolder.get(); GeonetworkDataDirectory dataDirectory = applicationContext.getBean(GeonetworkDataDirectory.class); String styleSheetWmc = dataDirectory.getWebappDir() + File.separator + Geonet.Path.IMPORT_STYLESHEETS + File.separator + "OGCWMC-OR-OWSC-to-ISO19139.xsl"; FilePathChecker.verify(filename); // Convert the context in an ISO19139 records Map<String, Object> xslParams = new HashMap<String, Object>(); xslParams.put("viewer_url", viewerUrl); xslParams.put("map_url", url); xslParams.put("topic", topic); xslParams.put("title", title); xslParams.put("abstract", recordAbstract); xslParams.put("lang", context.getLanguage()); // Assign current user to the record UserSession us = context.getUserSession(); if (us != null) { xslParams.put("currentuser_name", us.getName() + " " + us.getSurname()); // phone number is georchestra-specific // xslParams.put("currentuser_phone", us.getPrincipal().getPhone()); xslParams.put("currentuser_mail", us.getEmailAddr()); xslParams.put("currentuser_org", us.getOrganisation()); } // 1. JDOMize the string Element wmcDoc = Xml.loadString(xml, false); // 2. Apply XSL (styleSheetWmc) Element transformedMd = Xml.transform(wmcDoc, new File(styleSheetWmc).toPath(), xslParams); // 4. Inserts the metadata (does basically the same as the metadata.insert.paste // service (see Insert.java) String uuid = UUID.randomUUID().toString(); SettingManager sm = applicationContext.getBean(SettingManager.class); DataManager dm = applicationContext.getBean(DataManager.class); SchemaManager schemaMan = applicationContext.getBean(SchemaManager.class); String date = new ISODate().toString(); SimpleMetadataProcessingReport report = new SimpleMetadataProcessingReport(); final List<String> id = new ArrayList<String>(); final List<Element> md = new ArrayList<Element>(); md.add(transformedMd); // Import record Importer.importRecord(uuid, uuidProcessing, md, "iso19139", 0, sm.getSiteId(), sm.getSiteName(), null, context, id, date, date, group, MetadataType.METADATA); // Save the context if no context-url provided if (StringUtils.isEmpty(url)) { Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0)); Files.createDirectories(dataDir); Path outFile = dataDir.resolve(filename); Files.deleteIfExists(outFile); FileUtils.writeStringToFile(outFile.toFile(), Xml.getString(wmcDoc)); // Update the MD Map<String, Object> onlineSrcParams = new HashMap<String, Object>(); onlineSrcParams.put("protocol", "WWW:DOWNLOAD-OGC:OWS-C"); onlineSrcParams.put("url", sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, filename)); onlineSrcParams.put("name", filename); onlineSrcParams.put("desc", title); transformedMd = Xml.transform(transformedMd, schemaMan.getSchemaDir("iso19139").resolve("process").resolve("onlinesrc-add.xsl"), onlineSrcParams); dm.updateMetadata(context, id.get(0), transformedMd, false, true, false, context.getLanguage(), null, true); } if (StringUtils.isNotEmpty(overview) && StringUtils.isNotEmpty(overviewFilename)) { Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0)); Files.createDirectories(dataDir); Path outFile = dataDir.resolve(overviewFilename); Files.deleteIfExists(outFile); byte[] data = Base64.decodeBase64(overview); FileUtils.writeByteArrayToFile(outFile.toFile(), data); // Update the MD Map<String, Object> onlineSrcParams = new HashMap<String, Object>(); onlineSrcParams.put("thumbnail_url", sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, overviewFilename)); transformedMd = Xml.transform(transformedMd, schemaMan.getSchemaDir("iso19139").resolve("process").resolve("thumbnail-add.xsl"), onlineSrcParams); dm.updateMetadata(context, id.get(0), transformedMd, false, true, false, context.getLanguage(), null, true); } dm.indexMetadata(id); report.addMetadataInfos(Integer.parseInt(id.get(0)), uuid); triggerCreationEvent(request, uuid); report.incrementProcessedRecords(); report.close(); return report; }
From source file:com.eucalyptus.blockstorage.ceph.CephRbdProvider.java
@Override public void restoreSnapshotDelta(String baseIqn, StorageResource sr) throws EucalyptusCloudException { LOG.info("Restoring delta on base=" + baseIqn + ", snapshotId=" + sr.getId() + ", snapsDeltaFile=" + sr.getPath());/*from w w w . j a v a2s.co m*/ try { // Apply diff String[] cmd = new String[] { StorageProperties.EUCA_ROOT_WRAPPER, "rbd", "--id", cachedConfig.getCephUser(), "--keyring", cachedConfig.getCephKeyringFile(), "import-diff", sr.getPath(), baseIqn }; LOG.debug("Executing: " + Joiner.on(" ").skipNulls().join(cmd)); CommandOutput output = SystemUtil.runWithRawOutput(cmd); if (output != null) { LOG.debug("Dump from rbd command:\nReturn value=" + output.returnValue + "\nOutput=" + output.output + "\nDebug=" + output.error); if (output.returnValue != 0) { throw new EucalyptusCloudException("Unable to execute rbd command. Failed with error: " + output.output + "\n" + output.error); } } } catch (Exception e) { LOG.warn("Failed to apply snapshot delta on " + baseIqn, e); throw new EucalyptusCloudException("Failed to apply snapshot delta on " + baseIqn, e); } finally { // clean up the diff file try { LOG.trace("About to delete diff file " + sr.getPath()); if (!Files.deleteIfExists(Paths.get(sr.getPath()))) { LOG.warn("Diff file " + sr.getPath() + "did not exist to delete."); } else { LOG.trace("Successfully deleted diff file " + sr.getPath()); } } catch (Exception e) { LOG.warn("Failed to delete diff file " + sr.getPath(), e); } } }
From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java
protected ModelAndView performExport(final HttpServletResponse response, final String filename, final IOConsumer<OutputStream> exporter) { try {/*from w ww.j a v a2s . c o m*/ final Path tmp = Files.createTempFile("export-", null); try { try (OutputStream tmpStream = new BufferedOutputStream(new FileOutputStream(tmp.toFile()))) { // first we spool this out to temp file, so that we don't block the channel for too long exporter.accept(tmpStream); } response.setContentLengthLong(tmp.toFile().length()); response.setContentType("application/zip"); response.setHeader("Content-Disposition", String.format("attachment; filename=%s", filename)); try (InputStream inStream = new BufferedInputStream(new FileInputStream(tmp.toFile()))) { ByteStreams.copy(inStream, response.getOutputStream()); } return null; } finally { Files.deleteIfExists(tmp); } } catch (final IOException e) { return CommonController.createError("Failed to export", null, e); } }