Example usage for java.nio.file Files deleteIfExists

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

Introduction

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

Prototype

public static boolean deleteIfExists(Path path) throws IOException 

Source Link

Document

Deletes a file if it exists.

Usage

From source file:org.apache.storm.localizer.LocalizedResource.java

@Override
public void cleanupOrphanedData() throws IOException {
    //There are a few possible files that we would want to clean up
    //baseDir + "/" + "_tmp_" + baseName
    //baseDir + "/" + "_tmp_" + baseName + ".current"
    //baseDir + "/" + baseName.<VERSION>
    //baseDir + "/" + baseName.current
    //baseDir + "/" + baseName.version
    //In general we always want to delete the _tmp_ files if they are there.

    Path tmpOutput = tmpOutputLocation();
    Files.deleteIfExists(tmpOutput);
    Path tmpSym = tmpSymlinkLocation();
    Files.deleteIfExists(tmpSym);

    try {//from www . j  a v  a 2  s .c  o  m
        String baseName = getKey();
        long version = getLocalVersion();
        Path current = getCurrentSymlinkPath();

        //If .current and .version do not match, we roll back the .version file to match
        // what .current is pointing to.
        if (Files.exists(current) && Files.isSymbolicLink(current)) {
            Path versionFile = Files.readSymbolicLink(current);
            Matcher m = VERSION_FILE_PATTERN.matcher(versionFile.getFileName().toString());
            if (m.matches()) {
                long foundVersion = Long.valueOf(m.group(2));
                if (foundVersion != version) {
                    LOG.error("{} does not match the version file so fix the version file", current);
                    //The versions are different so roll back to whatever current is
                    try (PrintWriter restoreWriter = new PrintWriter(
                            new BufferedWriter(new FileWriter(versionFilePath.toFile(), false)))) {
                        restoreWriter.println(foundVersion);
                    }
                    version = foundVersion;
                }
            }
        }

        // Finally delete any baseName.<VERSION> files that are not pointed to by the current version
        final long finalVersion = version;
        LOG.debug("Looking to clean up after {} in {}", getKey(), baseDir);
        try (DirectoryStream<Path> ds = fsOps.newDirectoryStream(baseDir, (path) -> {
            Matcher m = VERSION_FILE_PATTERN.matcher(path.getFileName().toString());
            if (m.matches()) {
                long foundVersion = Long.valueOf(m.group(2));
                return m.group(1).equals(baseName) && foundVersion != finalVersion;
            }
            return false;
        })) {
            for (Path p : ds) {
                LOG.info("Cleaning up old localized resource file {}", p);
                if (Files.isDirectory(p)) {
                    FileUtils.deleteDirectory(p.toFile());
                } else {
                    fsOps.deleteIfExists(p.toFile());
                }
            }
        }
    } catch (NoSuchFileException e) {
        LOG.warn("Nothing to cleanup with badeDir {} even though we expected there to be something there",
                baseDir);
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testExecXslt() throws Exception {
    final ServletContext context = _applicationContext.getBean(ServletContext.class);
    MockHttpServletRequest request = new MockHttpServletRequest(context, "GET",
            "http://localhost:8080/geonetwork/srv/eng/md.formatter");
    request.getSession();//w w  w .  jav  a 2  s.  co m
    request.setPathInfo("/eng/md.formatter");

    final String applicationContextAttributeKey = "srv";
    request.getServletContext().setAttribute(applicationContextAttributeKey, _applicationContext);
    ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);

    RequestContextHolder.setRequestAttributes(requestAttributes);
    final String formatterName = "xsl-test-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.xsl");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    Files.deleteIfExists(formatterDir.resolve("functions.xsl"));
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve("functions.xsl"), formatterDir, true);
    JeevesDelegatingFilterProxy.setApplicationContextAttributeKey(applicationContextAttributeKey);

    final MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
            new ServletWebRequest(request, response));
    final String viewXml = response.getContentAsString();
    final Element view = Xml.loadString(viewXml, false);
    assertEqualsText("fromFunction", view, "*//p");
    assertEqualsText("Title", view, "*//div[@class='tr']");
}

From source file:org.digidoc4j.main.DigiDoc4JTest.java

@Test
public void createsContainerAndAddsFileWithoutMimeType() throws Exception {
    exit.expectSystemExitWithStatus(2);//www .  j  a  v a 2s . c om
    Files.deleteIfExists(Paths.get("test1.ddoc"));
    String[] params = new String[] { "-in", "test1.ddoc", "-add", "testFiles/test.txt", "-pkcs12",
            "testFiles/signout.p12", "test" };
    DigiDoc4J.main(params);
}

From source file:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for copying a file with non existent source file")
public void testCopyFileNonExistSource() throws IOException {
    try {/*  ww w.  j a v a 2s . c o  m*/
        BValue[] args = { new BString(destFilePath.toString()), new BString(tempDestPath.toString()),
                new BBoolean(false) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testCopy", args);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}INVALID_OPERATION");
        log.info("Ballerina error: " + error.getDetails().stringValue());
    } finally {
        Files.deleteIfExists(tempDestPath);
    }
}

From source file:org.cryptomator.cryptofs.CryptoFileSystemImpl.java

void delete(CryptoPath cleartextPath) throws IOException {
    Path ciphertextFile = cryptoPathMapper.getCiphertextFilePath(cleartextPath, CiphertextFileType.FILE);
    // try to delete ciphertext file:
    if (!Files.deleteIfExists(ciphertextFile)) {
        // filePath doesn't exist, maybe it's an directory:
        Path ciphertextDir = cryptoPathMapper.getCiphertextDirPath(cleartextPath);
        Path ciphertextDirFile = cryptoPathMapper.getCiphertextFilePath(cleartextPath,
                CiphertextFileType.DIRECTORY);
        try {/*  w  w  w  . ja v  a2  s .  co m*/
            Files.delete(ciphertextDir);
            if (!Files.deleteIfExists(ciphertextDirFile)) {
                // should not happen. Nevertheless this is a valid state, so who no big deal...
                LOG.warn("Successfully deleted dir {}, but didn't find corresponding dir file {}",
                        ciphertextDir, ciphertextDirFile);
            }
            dirIdProvider.delete(ciphertextDirFile);
        } catch (NoSuchFileException e) {
            // translate ciphertext path to cleartext path
            throw new NoSuchFileException(cleartextPath.toString());
        } catch (DirectoryNotEmptyException e) {
            // translate ciphertext path to cleartext path
            throw new DirectoryNotEmptyException(cleartextPath.toString());
        }
    }
}

From source file:org.sejda.core.service.TaskTestContext.java

@Override
public void close() throws IOException {
    IOUtils.closeQuietly(streamOutput);/* ww  w.jav  a 2 s  .c o  m*/
    this.streamOutput = null;
    IOUtils.closeQuietly(outputDocument);
    this.outputDocument = null;
    if (nonNull(fileOutput)) {
        if (fileOutput.isDirectory()) {
            Files.walkFileTree(fileOutput.toPath(), new SimpleFileVisitor<Path>() {
                @Override
                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;
                }

            });
        }
        Files.deleteIfExists(fileOutput.toPath());
    }
    this.fileOutput = null;
}

From source file:cc.arduino.contributions.packages.ContributionInstaller.java

private File download(MultiStepProgress progress, String packageIndexUrl, ProgressListener progressListener)
        throws Exception {
    String statusText = tr("Downloading platforms index...");
    URL url = new URL(packageIndexUrl);
    String[] urlPathParts = url.getFile().split("/");
    File outputFile = BaseNoGui.indexer.getIndexFile(urlPathParts[urlPathParts.length - 1]);
    File tmpFile = new File(outputFile.getAbsolutePath() + ".tmp");
    DownloadableContributionsDownloader downloader = new DownloadableContributionsDownloader(
            BaseNoGui.indexer.getStagingFolder());
    boolean noResume = true;
    downloader.download(url, tmpFile, progress, statusText, progressListener, noResume);

    Files.deleteIfExists(outputFile.toPath());
    Files.move(tmpFile.toPath(), outputFile.toPath());

    return outputFile;
}

From source file:org.codice.alliance.nsili.client.NsiliClient.java

public void retrieveProductFromDAG(DAG dag) throws MalformedURLException {
    System.out.println("Downloading products...");
    for (int i = 0; i < dag.nodes.length; i++) {
        Node node = dag.nodes[i];
        if (node.attribute_name.equals("productUrl")) {

            String url = node.value.extract_string();
            URL fileDownload = new URL(url);
            String productPath = "product.jpg";
            System.out.println("Downloading product : " + url);
            try (FileOutputStream outputStream = new FileOutputStream(new File(productPath));
                    BufferedInputStream inputStream = new BufferedInputStream(fileDownload.openStream());) {

                byte[] data = new byte[1024];
                int count;
                while ((count = inputStream.read(data, 0, 1024)) != -1) {
                    outputStream.write(data, 0, count);
                }/*from  w  w w  .j ava  2 s .com*/

                System.out.println("Successfully downloaded product from " + url + ".\n");
                Files.deleteIfExists(Paths.get(productPath));

            } catch (IOException e) {
                System.out.println("Unable to download product from " + url + ".\n");
                e.printStackTrace();
            }
        }
    }
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibAj.java

/**
 * @param joinPoint//from  ww w.j a va  2 s.c o m
 * @param apkFile
 * @param outDir
 * @param resTable
 */
@After("execution(* brut.androlib.Androlib.decodeUnknownFiles(..))" + "&& args(apkFile, outDir, resTable)")
public void decodeUnknownFiles_after(JoinPoint joinPoint, ExtFile apkFile, File outDir, ResTable resTable) {
    try {
        File unknownOut = new File(outDir, getUNK_DIRNAME());
        ResUnknownFiles mResUnknownFiles = Reflect.on(joinPoint.getThis()).get("mResUnknownFiles");

        Directory unk = apkFile.getDirectory();
        // loop all items in container recursively, ignoring any that are pre-defined by aapt
        Set<String> files = unk.getFiles(true);
        for (String file : files) {
            if (file.equals("classes.dex") || file.equals("resources.arsc")) {
                continue;
            }

            /**
             * ??
             */
            if (file.replaceFirst("META-INF[/\\\\]+[^/\\\\]+\\.(SF|RSA)", "").isEmpty()) {
                continue;
            }

            /**
             * dex
             */
            if (DexMaps.containsKey(file)) {
                continue;
            }

            String decodeMapFileName = getDecodeFileMapName(file);
            File resFile = new File(outDir, decodeMapFileName);
            if (resFile.exists()) {
                //??,
                mResUnknownFiles.getUnknownFiles().remove(file);
                File needDeleteFile = new File(unknownOut, file);
                if (needDeleteFile.exists()) {
                    //?,?
                    needDeleteFile.delete();
                }
            } else {
                File unFile = new File(unknownOut, file);
                if (unFile.exists()) {
                    //?
                    continue;
                }

                //?,
                // copy file out of archive into special "unknown" folder
                unk.copyToDir(unknownOut, file);
                // lets record the name of the file, and its compression type
                // so that we may re-include it the same way
                mResUnknownFiles.addUnknownFileInfo(file, String.valueOf(unk.getCompressionLevel(file)));
            }

        }

        if (unknownOut.exists()) {
            //
            Files.walkFileTree(Paths.get(unknownOut.getAbsolutePath()), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    try {
                        Files.deleteIfExists(dir);
                    } catch (Exception e) {
                        // ignore exception
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.schemaspy.SchemaAnalyzer.java

private void generateHtmlDoc(Config config, ProgressListener progressListener, File outputDir, Database db,
        long duration, Collection<Table> tables) throws IOException {
    LineWriter out;/*  www .j  av  a 2s  . c  o  m*/
    LOGGER.info("Gathered schema details in {} seconds", duration / 1000);
    LOGGER.info("Writing/graphing summary");

    prepareLayoutFiles(outputDir);

    progressListener.graphingSummaryProgressed();

    boolean showDetailedTables = tables.size() <= config.getMaxDetailedTables();
    final boolean includeImpliedConstraints = config.isImpliedConstraintsEnabled();

    // if evaluating a 'ruby on rails-based' database then connect the columns
    // based on RoR conventions
    // note that this is done before 'hasRealRelationships' gets evaluated so
    // we get a relationships ER diagram
    if (config.isRailsEnabled())
        DbAnalyzer.getRailsConstraints(db.getTablesByName());

    File summaryDir = new File(outputDir, "diagrams/summary");

    // generate the compact form of the relationships .dot file
    String dotBaseFilespec = "relationships";
    out = new LineWriter(new File(summaryDir, dotBaseFilespec + ".real.compact.dot"), Config.DOT_CHARSET);
    WriteStats stats = new WriteStats(tables);
    DotFormatter.getInstance().writeRealRelationships(db, tables, true, showDetailedTables, stats, out,
            outputDir);
    boolean hasRealRelationships = stats.getNumTablesWritten() > 0 || stats.getNumViewsWritten() > 0;
    out.close();

    if (hasRealRelationships) {
        // real relationships exist so generate the 'big' form of the relationships .dot file
        progressListener.graphingSummaryProgressed();
        out = new LineWriter(new File(summaryDir, dotBaseFilespec + ".real.large.dot"), Config.DOT_CHARSET);
        DotFormatter.getInstance().writeRealRelationships(db, tables, false, showDetailedTables, stats, out,
                outputDir);
        out.close();
    }

    // getting implied constraints has a side-effect of associating the parent/child tables, so don't do it
    // here unless they want that behavior
    List<ImpliedForeignKeyConstraint> impliedConstraints = new ArrayList();
    if (includeImpliedConstraints)
        impliedConstraints.addAll(DbAnalyzer.getImpliedConstraints(tables));

    List<Table> orphans = DbAnalyzer.getOrphans(tables);
    config.setHasOrphans(!orphans.isEmpty() && Dot.getInstance().isValid());
    config.setHasRoutines(!db.getRoutines().isEmpty());

    progressListener.graphingSummaryProgressed();

    File impliedDotFile = new File(summaryDir, dotBaseFilespec + ".implied.compact.dot");
    out = new LineWriter(impliedDotFile, Config.DOT_CHARSET);
    boolean hasImplied = DotFormatter.getInstance().writeAllRelationships(db, tables, true, showDetailedTables,
            stats, out, outputDir);

    Set<TableColumn> excludedColumns = stats.getExcludedColumns();
    out.close();
    if (hasImplied) {
        impliedDotFile = new File(summaryDir, dotBaseFilespec + ".implied.large.dot");
        out = new LineWriter(impliedDotFile, Config.DOT_CHARSET);
        DotFormatter.getInstance().writeAllRelationships(db, tables, false, showDetailedTables, stats, out,
                outputDir);
        out.close();
    } else {
        Files.deleteIfExists(impliedDotFile.toPath());
    }

    HtmlRelationshipsPage.getInstance().write(db, summaryDir, dotBaseFilespec, hasRealRelationships, hasImplied,
            excludedColumns, progressListener, outputDir);

    progressListener.graphingSummaryProgressed();

    File orphansDir = new File(outputDir, "diagrams/orphans");
    FileUtils.forceMkdir(orphansDir);
    HtmlOrphansPage.getInstance().write(db, orphans, orphansDir, outputDir);
    out.close();

    progressListener.graphingSummaryProgressed();

    HtmlMainIndexPage.getInstance().write(db, tables, impliedConstraints, outputDir);

    progressListener.graphingSummaryProgressed();

    List<ForeignKeyConstraint> constraints = DbAnalyzer.getForeignKeyConstraints(tables);
    HtmlConstraintsPage constraintIndexFormatter = HtmlConstraintsPage.getInstance();
    constraintIndexFormatter.write(db, constraints, tables, outputDir);

    progressListener.graphingSummaryProgressed();

    HtmlAnomaliesPage.getInstance().write(db, tables, impliedConstraints, outputDir);

    progressListener.graphingSummaryProgressed();

    for (HtmlColumnsPage.ColumnInfo columnInfo : HtmlColumnsPage.getInstance().getColumnInfos().values()) {
        HtmlColumnsPage.getInstance().write(db, tables, columnInfo, outputDir);
    }

    progressListener.graphingSummaryProgressed();

    HtmlRoutinesPage.getInstance().write(db, outputDir);

    // create detailed diagrams

    duration = progressListener.startedGraphingDetails();

    LOGGER.info("Completed summary in {} seconds", duration / 1000);
    LOGGER.info("Writing/diagramming details");

    generateTables(progressListener, outputDir, db, tables, stats);
    HtmlComponentPage.getInstance().write(db, tables, outputDir);
}