List of usage examples for java.nio.file Files deleteIfExists
public static boolean deleteIfExists(Path path) throws IOException
From source file:it.polimi.diceH2020.launcher.Experiment.java
void wipeResultDir() throws IOException { Path result = Paths.get(settings.getResultDir()); if (Files.exists(result)) { Files.walkFileTree(result, new SimpleFileVisitor<Path>() { @Override//from w w w. ja va 2 s . com public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } }); Files.deleteIfExists(result); Files.createDirectory(result); } }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java
public boolean createGlobalRepo() { boolean toReturn = false; Path globalConfigRepoPath = buildRepoPath(GitRepositories.GLOBAL).resolve(GIT_ROOT); if (!Files.exists(globalConfigRepoPath)) { // Git repository doesn't exist for global, but the folder might be present, let's delete if exists Path globalConfigPath = globalConfigRepoPath.getParent(); // Create the global repository folder try {/*w w w .j a va 2s . c o m*/ Files.deleteIfExists(globalConfigPath); logger.info("Bootstrapping repository..."); Files.createDirectories(globalConfigPath); globalRepo = createGitRepository(globalConfigPath); toReturn = true; } catch (IOException e) { // Something very wrong has happened logger.error("Bootstrapping repository failed", e); } } else { logger.info("Detected existing global repository, will not create new one."); toReturn = false; } return toReturn; }
From source file:jsondb.JsonDBTemplate.java
@Override public void dropCollection(String collectionName) { CollectionMetaData cmd = cmdMap.get(collectionName); if ((null == cmd) || (!collectionsRef.get().containsKey(collectionName))) { throw new InvalidJsonDbApiUsageException( "Collection by name '" + collectionName + "' not found. Create collection first."); }//from w w w. j a va2 s. com cmd.getCollectionLock().writeLock().lock(); try { File toDelete = fileObjectsRef.get().get(collectionName); try { Files.deleteIfExists(toDelete.toPath()); } catch (IOException e) { Logger.error("IO Exception deleting the collection file {}", toDelete.getName(), e); throw new InvalidJsonDbApiUsageException( "Unable to create a collection file for collection: " + collectionName); } //cmdMap.remove(collectionName); //Do not remove it from the CollectionMetaData Map. //Someone might want to re insert a new collection of this type. fileObjectsRef.get().remove(collectionName); collectionsRef.get().remove(collectionName); contextsRef.get().remove(collectionName); } finally { cmd.getCollectionLock().writeLock().unlock(); } }
From source file:org.codice.alliance.nsili.client.SampleNsiliClient.java
public void downloadProductFromDAG(DAG dag) { LOGGER.info("Downloading products..."); for (Node node : dag.nodes) { if (node.attribute_name.equals(NsiliConstants.PRODUCT_URL)) { URI fileDownloadUri = null; try { fileDownloadUri = getEncodedUriFromString(node.value.extract_string()); } catch (URISyntaxException | MalformedURLException e) { LOGGER.error("Unable to encode fileDownloadUrl. {}", e); return; }/*from w w w . ja va 2 s. com*/ final String productPath = "product.jpg"; LOGGER.info("Downloading product : {}", fileDownloadUri); try { try (BufferedInputStream inputStream = new BufferedInputStream( fileDownloadUri.toURL().openStream()); FileOutputStream outputStream = new FileOutputStream(new File(productPath))) { final byte data[] = new byte[1024]; int count; while ((count = inputStream.read(data, 0, 1024)) != -1) { outputStream.write(data, 0, count); } LOGGER.info("Successfully downloaded product from {}.", fileDownloadUri); Files.deleteIfExists(Paths.get(productPath)); } } catch (IOException e) { LOGGER.error("Unable to download product from {}.", fileDownloadUri, e); } } } }
From source file:io.jsondb.JsonDBTemplate.java
@Override public void dropCollection(String collectionName) { CollectionMetaData cmd = cmdMap.get(collectionName); if ((null == cmd) || (!collectionsRef.get().containsKey(collectionName))) { throw new InvalidJsonDbApiUsageException( "Collection by name '" + collectionName + "' not found. Create collection first."); }/* www . j ava2s . c o m*/ cmd.getCollectionLock().writeLock().lock(); try { File toDelete = fileObjectsRef.get().get(collectionName); try { Files.deleteIfExists(toDelete.toPath()); } catch (IOException e) { logger.error("IO Exception deleting the collection file {}", toDelete.getName(), e); throw new InvalidJsonDbApiUsageException( "Unable to create a collection file for collection: " + collectionName); } //cmdMap.remove(collectionName); //Do not remove it from the CollectionMetaData Map. //Someone might want to re insert a new collection of this type. fileObjectsRef.get().remove(collectionName); collectionsRef.get().remove(collectionName); contextsRef.get().remove(collectionName); } finally { cmd.getCollectionLock().writeLock().unlock(); } }
From source file:org.opencb.opencga.server.rest.FileWSServer.java
@POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @ApiOperation(httpMethod = "POST", position = 4, value = "Resource to upload a file by chunks", response = File.class) public Response upload(@FormDataParam("chunk_content") byte[] chunkBytes, @FormDataParam("chunk_content") FormDataContentDisposition contentDisposition, @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition fileMetaData, @DefaultValue("") @FormDataParam("chunk_id") String chunk_id, @DefaultValue("false") @FormDataParam("last_chunk") String last_chunk, @DefaultValue("") @FormDataParam("chunk_total") String chunk_total, @DefaultValue("") @FormDataParam("chunk_size") String chunk_size, @DefaultValue("") @FormDataParam("chunk_hash") String chunkHash, @DefaultValue("false") @FormDataParam("resume_upload") String resume_upload, @ApiParam(value = "filename", required = false) @FormDataParam("filename") String filename, @ApiParam(value = "fileFormat", required = true) @DefaultValue("") @FormDataParam("fileFormat") String fileFormat, @ApiParam(value = "bioformat", required = true) @DefaultValue("") @FormDataParam("bioformat") String bioformat, // @ApiParam(value = "userId", required = true) @DefaultValue("") @FormDataParam("userId") String userId, // @ApiParam(defaultValue = "projectId", required = true) @DefaultValue("") @FormDataParam("projectId") String projectId, @ApiParam(value = "studyId", required = true) @FormDataParam("studyId") String studyIdStr, @ApiParam(value = "Path within catalog where the file will be located (default: root folder)", required = false) @DefaultValue(".") @FormDataParam("relativeFilePath") String relativeFilePath, @ApiParam(value = "description", required = false) @DefaultValue("") @FormDataParam("description") String description, @ApiParam(value = "Create the parent directories if they do not exist", required = false) @DefaultValue("true") @FormDataParam("parents") boolean parents) { long t = System.currentTimeMillis(); if (relativeFilePath.endsWith("/")) { relativeFilePath = relativeFilePath.substring(0, relativeFilePath.length() - 1); }/*ww w . j ava 2s . c o m*/ if (relativeFilePath.startsWith("/")) { return createErrorResponse(new CatalogException("The path cannot be absolute")); } java.nio.file.Path filePath = null; final long studyId; try { studyId = catalogManager.getStudyId(studyIdStr, sessionId); } catch (Exception e) { return createErrorResponse(e); } try { filePath = Paths.get(catalogManager.getFileUri(studyId, relativeFilePath)); System.out.println(filePath); } catch (CatalogIOException e) { System.out.println("catalogManager.getFilePath"); e.printStackTrace(); } catch (CatalogException e) { e.printStackTrace(); } if (chunkBytes != null) { java.nio.file.Path completedFilePath = filePath.getParent().resolve("_" + filename); java.nio.file.Path folderPath = filePath.getParent().resolve("__" + filename); logger.info(relativeFilePath + ""); logger.info(folderPath + ""); logger.info(filePath + ""); boolean resume = Boolean.parseBoolean(resume_upload); try { logger.info("---resume is: " + resume); if (resume) { logger.info("Resume ms :" + (System.currentTimeMillis() - t)); return createOkResponse(getResumeFileJSON(folderPath)); } int chunkId = Integer.parseInt(chunk_id); int chunkSize = Integer.parseInt(chunk_size); boolean lastChunk = Boolean.parseBoolean(last_chunk); logger.info("---saving chunk: " + chunkId); logger.info("lastChunk: " + lastChunk); // WRITE CHUNK TYPE_FILE if (!Files.exists(folderPath)) { logger.info("createDirectory(): " + folderPath); Files.createDirectory(folderPath); } logger.info("check dir " + Files.exists(folderPath)); // String hash = StringUtils.sha1(new String(chunkBytes)); // logger.info("bytesHash: " + hash); // logger.info("chunkHash: " + chunkHash); // hash = chunkHash; if (chunkBytes.length == chunkSize) { Files.write(folderPath.resolve(chunkId + "_" + chunkBytes.length + "_partial"), chunkBytes); } else { String errorMessage = "Chunk content size (" + chunkBytes.length + ") " + "!= chunk_size (" + chunk_size + ")."; logger.error(errorMessage); return createErrorResponse(new IOException(errorMessage)); } if (lastChunk) { logger.info("lastChunk is true..."); Files.deleteIfExists(completedFilePath); Files.createFile(completedFilePath); List<java.nio.file.Path> chunks = getSortedChunkList(folderPath); logger.info("----ordered chunks length: " + chunks.size()); for (java.nio.file.Path partPath : chunks) { logger.info(partPath.getFileName().toString()); Files.write(completedFilePath, Files.readAllBytes(partPath), StandardOpenOption.APPEND); } IOUtils.deleteDirectory(folderPath); try { QueryResult<File> queryResult = catalogManager.createFile(studyId, File.Format.valueOf(fileFormat.toUpperCase()), File.Bioformat.valueOf(bioformat.toUpperCase()), relativeFilePath, completedFilePath.toUri(), description, parents, sessionId); File file = new FileMetadataReader(catalogManager).setMetadataInformation( queryResult.first(), null, new QueryOptions(queryOptions), sessionId, false); queryResult.setResult(Collections.singletonList(file)); return createOkResponse(queryResult); } catch (Exception e) { logger.error(e.toString()); return createErrorResponse(e); } } } catch (IOException e) { System.out.println("e = " + e); // TODO Auto-generated catch block e.printStackTrace(); } logger.info("chunk saved ms :" + (System.currentTimeMillis() - t)); return createOkResponse("ok"); } else if (fileInputStream != null) { logger.info("filePath: {}", filePath.toString()); // We obtain the basic studyPath where we will upload the file temporarily java.nio.file.Path studyPath = null; try { studyPath = Paths.get(catalogManager.getStudyUri(studyId)); } catch (CatalogException e) { e.printStackTrace(); return createErrorResponse("Upload file", e.getMessage()); } if (filename == null) { filename = fileMetaData.getFileName(); } java.nio.file.Path tempFilePath = studyPath.resolve("tmp_" + filename).resolve(filename); logger.info("tempFilePath: {}", tempFilePath.toString()); logger.info("tempParent: {}", tempFilePath.getParent().toString()); // Create the temporal directory and upload the file try { if (!Files.exists(tempFilePath.getParent())) { logger.info("createDirectory(): " + tempFilePath.getParent()); Files.createDirectory(tempFilePath.getParent()); } logger.info("check dir " + Files.exists(tempFilePath.getParent())); // Start uploading the file to the temporal directory int read; byte[] bytes = new byte[1024]; // Upload the file to a temporary folder OutputStream out = new FileOutputStream(new java.io.File(tempFilePath.toString())); while ((read = fileInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } // Register the file in catalog try { String destinationPath; // Check if the relativeFilePath is not the root folder if (relativeFilePath.length() > 1 && !relativeFilePath.equals("./")) { try { // Create parents directory if necessary catalogManager.createFolder(studyId, Paths.get(relativeFilePath), parents, null, sessionId); } catch (CatalogException e) { logger.debug("The folder {} already exists", relativeFilePath); } destinationPath = Paths.get(relativeFilePath).resolve(filename).toString(); } else { destinationPath = filename; } logger.debug("Relative path: {}", relativeFilePath); logger.debug("Destination path: {}", destinationPath); logger.debug("File name {}", filename); // Register the file and move it to the proper directory QueryResult<File> queryResult = catalogManager.createFile(studyId, File.Format.valueOf(fileFormat.toUpperCase()), File.Bioformat.valueOf(bioformat.toUpperCase()), destinationPath, tempFilePath.toUri(), description, parents, sessionId); File file = new FileMetadataReader(catalogManager).setMetadataInformation(queryResult.first(), null, new QueryOptions(queryOptions), sessionId, false); queryResult.setResult(Collections.singletonList(file)); // Remove the temporal directory Files.delete(tempFilePath.getParent()); return createOkResponse(queryResult); } catch (CatalogException e) { e.printStackTrace(); return createErrorResponse("Upload file", e.getMessage()); } catch (IOException e) { e.printStackTrace(); return createErrorResponse("Upload file", e.getMessage()); } } else { return createErrorResponse("Upload file", "No file or chunk found"); } }
From source file:com.alibaba.jstorm.blobstore.BlobStoreUtils.java
private static boolean downloadResourcesAsSupervisorAttempt(ClientBlobStore cb, String key, String localFile) { boolean isSuccess = false; FileOutputStream out = null;/*from w w w . j a va 2s . c om*/ InputStreamWithMeta in = null; try { out = new FileOutputStream(localFile); in = cb.getBlob(key); long fileSize = in.getFileLength(); byte[] buffer = new byte[1024]; int len; int downloadFileSize = 0; while ((len = in.read(buffer)) >= 0) { out.write(buffer, 0, len); downloadFileSize += len; } isSuccess = (fileSize == downloadFileSize); } catch (TException | IOException e) { LOG.error("An exception happened while downloading {} from blob store.", localFile, e); } finally { try { if (out != null) { out.close(); } } catch (IOException ignored) { } try { if (in != null) { in.close(); } } catch (IOException ignored) { } } if (!isSuccess) { try { Files.deleteIfExists(Paths.get(localFile)); } catch (IOException ex) { LOG.error("Failed trying to delete the partially downloaded {}", localFile, ex); } } return isSuccess; }
From source file:org.apache.storm.localizer.LocalizedResource.java
@Override public void completelyRemove() throws IOException { Path fileWithVersion = getFilePathWithVersion(); Path currentSymLink = getCurrentSymlinkPath(); if (uncompressed) { if (Files.exists(fileWithVersion)) { // this doesn't follow symlinks, which is what we want FileUtils.deleteDirectory(fileWithVersion.toFile()); }/*from ww w. j a v a2s . c o m*/ } else { Files.deleteIfExists(fileWithVersion); } Files.deleteIfExists(currentSymLink); Files.deleteIfExists(versionFilePath); }
From source file:io.fabric8.vertx.maven.plugin.mojos.AbstractRunMojo.java
/** * This method to load Vert.X application configurations. * This will use the pattern ${basedir}/src/main/conf/application.[json/yaml/yml] *///from w w w. j a va 2 s .c o m protected void scanAndLoadConfigs() throws MojoExecutionException { Path confBaseDir = Paths.get(this.project.getBasedir().toString(), "src", "main", "conf"); if (Files.exists(confBaseDir) && Files.isDirectory(confBaseDir)) { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(this.project.getBasedir() + DEFAULT_CONF_DIR); directoryScanner.setIncludes(WILDCARD_CONFIG_FILES); directoryScanner.scan(); String[] configFiles = directoryScanner.getIncludedFiles(); if (configFiles != null && configFiles.length != 0) { String configFile = configFiles[0]; Path confPath = Paths.get(confBaseDir.toFile().toString(), configFile); //Check if its JSON if (isJson(configFile)) { config = confPath.toFile(); } else if (isYaml(configFile)) { //Check if its YAML or YML Path jsonConfDir = Paths.get(this.projectBuildDir, "conf"); jsonConfDir.toFile().mkdirs(); Path jsonConfPath = Paths.get(jsonConfDir.toString(), VERTX_CONFIG_FILE_JSON); try { Files.deleteIfExists(jsonConfPath); if (Files.createFile(jsonConfPath).toFile().exists()) { ConfigConverterUtil.convertYamlToJson(confPath, jsonConfPath); config = jsonConfPath.toFile(); } } catch (IOException e) { throw new MojoExecutionException("Error loading configuration file:" + confPath.toString(), e); } catch (Exception e) { throw new MojoExecutionException( "Error loading and converting configuration file:" + confPath.toString(), e); } } } } }
From source file:com.ibm.iotf.sample.client.gateway.devicemgmt.GatewayFirmwareHandlerSample.java
public static void deleteFile(String fileName) { /**/*from ww w.ja v a 2s . c o m*/ * Delete the temporary firmware file */ try { Path path = new File(fileName).toPath(); Files.deleteIfExists(path); } catch (IOException e) { e.printStackTrace(); } }