Example usage for java.nio.file Files delete

List of usage examples for java.nio.file Files delete

Introduction

In this page you can find the example usage for java.nio.file Files delete.

Prototype

public static void delete(Path path) throws IOException 

Source Link

Document

Deletes a file.

Usage

From source file:com.cirrus.server.osgi.service.local.LocalStorageService.java

@Override
public ICirrusData delete(final String path) throws ServiceRequestFailedException {
    final Path newPath = Paths.get(this.getGlobalContext().getRootPath(), path);

    if (!Files.exists(newPath)) {
        throw new ServiceRequestFailedException("The entry <" + newPath + "> doesn't exist");
    } else {/* w  w w  .jav a  2  s .c  o  m*/
        try {
            final ICirrusData cirrusData = this.createCirrusDataFromFile(newPath);
            Files.delete(newPath);
            return cirrusData;
        } catch (final IOException e) {
            throw new ServiceRequestFailedException(e);
        }
    }
}

From source file:codes.thischwa.c5c.DispatcherPUT.java

@Override
GenericResponse doRequest() {/* w ww  . jav a2s .c  o m*/
    logger.debug("Entering DispatcherPUT#doRequest");

    InputStream in = null;
    try {
        Context ctx = RequestData.getContext();
        FilemanagerAction mode = ctx.getMode();
        HttpServletRequest req = ctx.getServletRequest();
        FilemanagerConfig conf = UserObjectProxy.getFilemanagerUserConfig(req);
        switch (mode) {
        case UPLOAD: {
            boolean overwrite = conf.getUpload().isOverwrite();
            String currentPath = IOUtils.toString(req.getPart("currentpath").getInputStream());
            String backendPath = buildBackendPath(currentPath);
            Part uploadPart = req.getPart("newfile");
            String newName = getFileName(uploadPart);

            // Some browsers transfer the entire source path not just the filename
            String fileName = FilenameUtils.getName(newName); // TODO check forceSingleExtension
            String sanitizedName = FileUtils.sanitizeName(fileName);
            if (!overwrite)
                sanitizedName = getUniqueName(backendPath, sanitizedName);
            logger.debug("* upload -> currentpath: {}, filename: {}, sanitized filename: {}", currentPath,
                    fileName, sanitizedName);

            // check 'overwrite' and unambiguity
            String uniqueName = getUniqueName(backendPath, sanitizedName);
            if (!overwrite && !uniqueName.equals(sanitizedName)) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD,
                        FilemanagerException.Key.FileAlreadyExists, sanitizedName);
            }
            sanitizedName = uniqueName;

            in = uploadPart.getInputStream();

            // save the file temporary
            Path tempPath = saveTemp(in, sanitizedName);

            // pre-process the upload
            imageProcessingAndSizeCheck(tempPath, sanitizedName, uploadPart.getSize(), conf);

            connector.upload(backendPath, sanitizedName,
                    new BufferedInputStream(Files.newInputStream(tempPath)));

            logger.debug("successful uploaded {} bytes", uploadPart.getSize());
            Files.delete(tempPath);
            UploadFile ufResp = new UploadFile(currentPath, sanitizedName);
            ufResp.setName(newName);
            ufResp.setPath(currentPath);
            return ufResp;
        }
        case REPLACE: {
            String newFilePath = IOUtils.toString(req.getPart("newfilepath").getInputStream());
            String backendPath = buildBackendPath(newFilePath);
            Part uploadPart = req.getPart("fileR");
            logger.debug("* replacefile -> urlPath: {}, backendPath: {}", newFilePath, backendPath);

            // check if backendPath is protected
            boolean protect = connector.isProtected(backendPath);
            if (protect) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD,
                        FilemanagerException.Key.NotAllowedSystem, backendPath);
            }

            // check if file already exits
            VirtualFile vf = new VirtualFile(backendPath, false);
            String fileName = vf.getName();
            String uniqueName = getUniqueName(vf.getFolder(), fileName);
            if (uniqueName.equals(fileName)) {
                throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileNotExists,
                        backendPath);
            }

            in = uploadPart.getInputStream();

            // save the file temporary
            Path tempPath = saveTemp(in, fileName);

            // pre-process the upload
            imageProcessingAndSizeCheck(tempPath, fileName, uploadPart.getSize(), conf);

            connector.replace(backendPath, new BufferedInputStream(Files.newInputStream(tempPath)));
            logger.debug("successful replaced {} bytes", uploadPart.getSize());
            VirtualFile vfUrlPath = new VirtualFile(newFilePath, false);
            return new Replace(vfUrlPath.getFolder(), vfUrlPath.getName());
        }
        case SAVEFILE: {
            String urlPath = req.getParameter("path");
            String backendPath = buildBackendPath(urlPath);
            logger.debug("* savefile -> urlPath: {}, backendPath: {}", urlPath, backendPath);
            String content = req.getParameter("content");
            connector.saveFile(backendPath, content);
            return new SaveFile(urlPath);
        }
        default: {
            logger.error("Unknown 'mode' for POST: {}", req.getParameter("mode"));
            throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(Key.ModeError));
        }
        }
    } catch (C5CException e) {
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage());
    } catch (ServletException e) {
        logger.error("A ServletException was thrown while uploading: " + e.getMessage(), e);
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200);
    } catch (IOException e) {
        logger.error("A IOException was thrown while uploading: " + e.getMessage(), e);
        return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.etl.resource.OutputResource.java

@DELETE
@Path("/output/{destinationId}")
public Response doDelete(@PathParam("destinationId") String inId) {
    try {// ww w  . j  a  v  a  2s. co  m
        final File outputFile = new File(this.etlProperties.outputFileDirectory(inId),
                this.patientSetSenderSupport.getOutputName(inId));
        if (!outputFile.exists()) {
            throw new HttpStatusException(Status.NOT_FOUND);
        }
        Files.delete(outputFile.toPath());
        return Response.noContent().build();
    } catch (IOException ex) {
        throw new HttpStatusException(Status.INTERNAL_SERVER_ERROR, ex);
    }
}

From source file:org.cirdles.webServices.calamari.PrawnFileHandlerService.java

public Path generateReports(String myFileName, InputStream prawnFile, boolean useSBM, boolean userLinFits,
        String firstLetterRM) throws IOException, JAXBException, SAXException {

    String fileName = myFileName;
    if (myFileName == null) {
        fileName = DEFAULT_PRAWNFILE_NAME;
    }/*from w  w  w .java2  s  .  co  m*/

    Path uploadDirectory = Files.createTempDirectory("upload");
    Path prawnFilePath = uploadDirectory.resolve("prawn-file.xml");
    Files.copy(prawnFile, prawnFilePath);

    Path calamarirReportsFolderAlias = Files.createTempDirectory("reports-destination");
    File reportsDestinationFile = calamarirReportsFolderAlias.toFile();

    reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile);

    // this gives reportengine the name of the Prawnfile for use in report names
    prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName);

    prawnFileHandler.writeReportsFromPrawnFile(prawnFilePath.toString(), useSBM, userLinFits, firstLetterRM);

    Files.delete(prawnFilePath);

    Path reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReportsPath()).getParent()
            .toAbsolutePath();

    Path reports = Files.list(reportsFolder).findFirst().orElseThrow(() -> new IllegalStateException());

    Path reportsZip = zip(reports);
    recursiveDelete(reports);

    return reportsZip;
}

From source file:ch.bender.evacuate.Helper.java

/**
 * If the given target is already present, the method retains this older version in a kind of
 * FIFO buffer (but persistent on disk). The given MaxBackups number indicates how many such
 * backups are kept./*from www . ja v  a  2 s. com*/
 * <p>
 * This routine is valid for files and directories. With files, the numbering suffix is done
 * before the last dot in the file name, with directories the number suffix is appended at the
 * end. 
 * <p>
 * Example: target is "Target.txt" and there are already present:
 * <pre>
 *     Target.txt
 *     Target_01.txt
 *     Target_02.txt
 * <pre>
 * Target_02.txt is renamed to Target_03.txt, Target_01.txt to Target_02.txt and Target.txt Target_01.txt.
 * <p>
 * If MaxBackup would be 3, then Target_02.txt would have been deleted instead renamed.
 * <p>   
 * 
 * @param aTarget
 * @param aMaxBackups
 * @param aFailedPreparations 
 * @throws IOException
 */
public static void prepareTrashChain(Path aTarget, int aMaxBackups, Map<Path, Throwable> aFailedPreparations) {
    myLog.debug("preparing trash chain for " + aTarget.toString());

    try {

        int i = aMaxBackups - 1;

        while (i > 0) {
            Path targetUpper = appendNumberSuffix(aTarget, i);
            Path targetLower = (i > 1) ? appendNumberSuffix(aTarget, i - 1) : aTarget;

            i--;

            if (Files.notExists(targetUpper) && Files.notExists(targetLower)) {
                continue;
            }

            if (Files.exists(targetUpper)) {
                myLog.info("There are already " + (i + 2) + " trashed versions of " + aTarget.toString()
                        + ". Deleting the oldest one");

                if (Files.exists(targetUpper)) {
                    if (Files.isDirectory(targetUpper)) {
                        Helper.deleteDirRecursive(targetUpper);
                    } else {
                        Files.delete(targetUpper);
                    }
                }
            }

            if (Files.notExists(targetLower)) {
                continue;
            }

            myLog.debug("Renaming " + targetLower.toString() + " to " + targetUpper.toString());
            Files.move(targetLower, targetUpper, StandardCopyOption.ATOMIC_MOVE);
        }
    } catch (Throwable e) {
        aFailedPreparations.put(aTarget, e);
    }
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void closeAndSaveBundleDelete() throws Exception {
    Bundle bundle = Bundles.createBundle();
    Path destination = Files.createTempFile("test", ".zip");
    destination.toFile().deleteOnExit();
    Files.delete(destination);
    assertFalse(Files.exists(destination));
    Bundles.closeAndSaveBundle(bundle, destination);
    assertTrue(Files.exists(destination));
    assertFalse(Files.exists(bundle.getSource()));
}

From source file:com.spotify.docker.client.CompressedDirectory.java

@Override
public void close() throws IOException {
    Files.delete(file);
}

From source file:controller.servlet.AllDataDelete.java

/**
 * Mtodo deleteServerFiles, permite eliminar los ficheros del servidor.
 *//* ww w. j av  a 2 s. c om*/
private void deleteServerFiles() {

    // Bsqueda y borrado de los ficheros en las carpetas del servidor.
    String path = this.getServletContext().getRealPath("");
    path += File.separator + Path.UPLOADEDFILES_FOLDER;
    File directory = new File(path);
    if (directory.exists()) {
        try {
            FileUtils.cleanDirectory(directory);
            try {
                Files.delete(Paths.get(path));
            } catch (IOException ex) {
                Logger.getLogger(AllDataDelete.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(AllDataDelete.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    path = this.getServletContext().getRealPath("");
    path += File.separator + Path.POIS_FOLDER;
    directory = new File(path);
    if (directory.exists()) {
        try {
            FileUtils.cleanDirectory(directory);
            try {
                Files.delete(Paths.get(path));
            } catch (IOException ex) {
                Logger.getLogger(AllDataDelete.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(AllDataDelete.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.kakao.hbase.manager.command.ExportKeysTest.java

@Test
public void testRunOptimize() throws Exception {
    String outputFile = "exportkeys_test.keys";

    try {//w w w  .j av a  2s . co m
        String splitPoint = "splitpoint";

        splitTable(splitPoint.getBytes());

        String[] argsParam = { "zookeeper", tableName, outputFile, "--optimize=1g" };
        Args args = new ManagerArgs(argsParam);
        assertEquals("zookeeper", args.getZookeeperQuorum());
        ExportKeys command = new ExportKeys(admin, args);

        waitForSplitting(2);
        command.run();

        List<Triple<String, String, String>> results = new ArrayList<>();
        for (String keys : Files.readAllLines(Paths.get(outputFile), Constant.CHARSET)) {

            String[] split = keys.split(ExportKeys.DELIMITER);
            results.add(new ImmutableTriple<>(split[0], split[1], split[2]));
        }
        assertEquals(0, results.size());
    } finally {
        Files.delete(Paths.get(outputFile));
    }
}

From source file:io.syndesis.project.converter.DefaultProjectGeneratorTest.java

@After
public void tearDown() throws Exception {
    if (runtimeDir != null) {
        Files.walkFileTree(runtimeDir, new SimpleFileVisitor<Path>() {
            @Override//from   w ww. j av a2 s.  c om
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    }
}