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:stroom.pipeline.destination.RollingFileDestination.java

private void roll() throws IOException {
    rolled = true;//  w  w  w.  j a  va 2  s .c o m

    boolean success = false;
    IOException exception = null;

    // If we have written then write a footer if we have one.
    if (footer != null && outputStream != null && outputStream.getBytesWritten() > 0) {
        // Write the footer.
        try {
            write(footer);
        } catch (final Throwable e) {
            exception = handleException(exception, e);
        }
    }
    // Try and close the output stream.
    try {
        close();
    } catch (final Throwable e) {
        exception = handleException(exception, e);
    }

    String destFileName = rolledFileName;
    destFileName = PathCreator.replaceTimeVars(destFileName);
    destFileName = PathCreator.replaceUUIDVars(destFileName);
    destFileName = PathCreator.replaceFileName(destFileName, fileName);

    // Create the destination file.
    final File destFile = new File(dir, destFileName);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Rolling file '%s' to '%s'", getFullPath(file), getFullPath(destFile));
    }

    // Create source path.
    Path source = null;
    try {
        source = file.toPath();
    } catch (final Throwable t) {
        exception = handleRollException(file, destFile, exception, t);
    }

    // Create destination path.
    Path dest = null;
    try {
        dest = destFile.toPath();
    } catch (final Throwable t) {
        exception = handleRollException(file, destFile, exception, t);
    }

    // If we have got valid paths for source and dest then attempt move.
    if (source != null && dest != null) {
        if (Files.isRegularFile(dest)) {
            LOGGER.error("Failed to roll file '%s' to '%s' as target exists", getFullPath(file),
                    getFullPath(destFile));
        } else {
            try {
                Files.move(source, dest);
                success = true;
            } catch (final Throwable t) {
                exception = handleRollException(file, destFile, exception, t);
            }
        }
    }

    if (source != null && !success) {
        try {
            int attempt = 1;
            while (!success && attempt <= MAX_FAILED_RENAME_ATTEMPTS) {
                // Try to rename the file to something else.
                final String suffix = StringUtils.leftPad(String.valueOf(attempt), 3, '0');
                final File failedFile = new File(dir, file.getName() + "." + suffix);
                try {
                    dest = null;
                    dest = failedFile.toPath();
                } catch (final Throwable t) {
                    LOGGER.error(t.getMessage(), t);
                }

                if (dest != null && !Files.isRegularFile(dest)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Renaming file '%s' to '%s'", getFullPath(file), getFullPath(failedFile));
                    }
                    try {
                        Files.move(source, dest);
                        success = true;
                    } catch (final Throwable t) {
                        LOGGER.debug(t.getMessage(), t);
                    }
                }
                attempt++;
            }

            // If we didn't succeed in renaming the file to a failed file
            // then try and delete the file.
            if (!success) {
                // Try to delete the file so we can continue to create a
                // destination.
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Deleting file '%s'", getFullPath(file));
                }
                if (!Files.deleteIfExists(source)) {
                    LOGGER.error("Failed to delete file '%s'", getFullPath(file));
                }
            }
        } catch (final Throwable t) {
            LOGGER.debug(t.getMessage(), t);
        }
    }

    if (exception != null) {
        throw exception;
    }
}

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

@Test(expected = AssertionError.class)
public void testGroovyUseEnvDuringConfigStage() throws Exception {
    MockHttpServletRequest r = new MockHttpServletRequest();
    r.getSession();/*from w w  w . ja v  a2 s  .c  o m*/
    final ServletWebRequest webRequest = new ServletWebRequest(r, new MockHttpServletResponse());
    final FormatterParams fparams = new FormatterParams();
    fparams.context = this.serviceContext;
    fparams.webRequest = webRequest;
    // make sure context is cleared
    EnvironmentProxy.setCurrentEnvironment(fparams);

    final String formatterName = "groovy-illegal-env-access-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.groovy");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    final String functionsXslName = "functions.xsl";
    Files.deleteIfExists(formatterDir.resolve(functionsXslName));
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve(functionsXslName),
            formatterDir.resolve(functionsXslName), false);

    formatService.exec("eng", "html", "" + id, null, formatterName, null, null, _100, webRequest);
}

From source file:org.ballerinalang.test.packaging.PackagingNegativeTestCase.java

@Test(description = "Test pushing a package without Ballerina.toml in the project directory")
public void testPushWithoutBallerinaToml() throws Exception {
    Path projectPath = tempProjectDirectory.resolve("projectWithoutToml");
    initProject(projectPath);//from   ww  w .  j ava2  s. c om

    // Remove Ballerina.toml
    Files.deleteIfExists(projectPath.resolve("Ballerina.toml"));

    String msg = "ballerina: couldn't locate Ballerina.toml in the project directory. Run 'ballerina init' to "
            + "create the Ballerina.toml file automatically and re-run the 'ballerina push' command";

    String[] clientArgs = { moduleName };
    balClient.runMain("push", clientArgs, envVariables, new String[0], new LogLeecher[] { new LogLeecher(msg) },
            projectPath.toString());
}

From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * saves temporary file in the correct file path.
 *
 * @param path path to save file//from   w w  w  .  j av a  2 s  .c  o  m
 * @param item file upload item
 * @param param the parameter
 * @param context ckfinder context
 * @throws IOException when IO Exception occurs.
 * @throws ConnectorException when error occurs
 */
private void saveTemporaryFile(Path path, MultipartFile item, FileUploadParameter param,
        CKFinderContext context) throws IOException, ConnectorException {
    Path file = getPath(path, param.getNewFileName());

    if (ImageUtils.isImageExtension(file)) {
        if (!context.isCheckSizeAfterScaling() && !ImageUtils.checkImageSize(item, context)) {
            param.throwException(ErrorCode.UPLOADED_TOO_BIG);
        }
        ImageUtils.createTmpThumb(item, file, getFileItemName(item), context);
        if (context.isCheckSizeAfterScaling()
                && !FileUtils.isFileSizeInRange(param.getType(), Files.size(file))) {
            Files.deleteIfExists(file);
            param.throwException(ErrorCode.UPLOADED_TOO_BIG);
        }
    } else {
        try (InputStream in = item.getInputStream()) {
            Files.copy(in, file);
        }
    }
    FileUploadEvent args = new FileUploadEvent(param.getCurrentFolder(), file);
    context.fireOnFileUpload(args);
}

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

@Test
public void createsContainerWithTypeSettingBDoc() throws Exception {
    String fileName = "test1.ddoc";
    Files.deleteIfExists(Paths.get(fileName));

    String[] params = new String[] { "-in", fileName, "-type", "BDOC", "-add", "testFiles/test.txt",
            "text/plain", "-pkcs12", "testFiles/signout.p12", "test" };

    callMainWithoutSystemExit(params);//ww  w  .j  a  va 2 s  . co m

    Container container = ContainerOpener.open(fileName);
    assertEquals("BDOC", container.getType());
}

From source file:org.matonto.etl.rest.impl.DelimitedRestImpl.java

@Override
public Response etlFile(String fileName, String mappingIRI, String format, boolean containsHeaders,
        String separator, String downloadFileName) {
    if (mappingIRI == null || mappingIRI.equals("")) {
        throw ErrorUtils.sendError("Must provide the name of an uploaded mapping", Response.Status.BAD_REQUEST);
    }/*  w w w.j  av  a 2 s .co  m*/

    File delimitedFile = getUploadedFile(fileName)
            .orElseThrow(() -> ErrorUtils.sendError("Document not found", Response.Status.BAD_REQUEST));
    String extension = FilenameUtils.getExtension(delimitedFile.getName());

    // Collect uploaded mapping model
    Model mappingModel;
    Resource mappingId = mappingManager.createMappingId(factory.createIRI(mappingIRI)).getMappingIdentifier();
    Optional<MappingWrapper> mappingOptional = mappingManager.retrieveMapping(mappingId);
    if (mappingOptional.isPresent()) {
        mappingModel = transformer.sesameModel(mappingOptional.get().getModel());
    } else {
        throw ErrorUtils.sendError("Mapping " + mappingId + " does not exist", Response.Status.BAD_REQUEST);
    }

    String result;
    InputStream data = getDocumentInputStream(delimitedFile);
    if (extension.equals("xls") || extension.equals("xlsx")) {
        ExcelConfig config = new ExcelConfig.Builder(data, transformer.matontoModel(mappingModel))
                .containsHeaders(containsHeaders).build();
        result = etlFile(format, () -> converter.convert(config));
    } else {
        SVConfig config = new SVConfig.Builder(data, transformer.matontoModel(mappingModel))
                .containsHeaders(containsHeaders).separator(separator.charAt(0)).build();
        result = etlFile(format, () -> converter.convert(config));
    }
    logger.info("File mapped: " + delimitedFile.getPath());

    // Write data into a stream
    StreamingOutput stream = os -> {
        Writer writer = new BufferedWriter(new OutputStreamWriter(os));
        writer.write(result);
        writer.flush();
        writer.close();
    };
    String fileExtension = getRDFFormat(format).getDefaultFileExtension();
    String mimeType = getRDFFormat(format).getDefaultMIMEType();
    String dataFileName = downloadFileName == null ? fileName : downloadFileName;
    Response response = Response.ok(stream)
            .header("Content-Disposition", "attachment;filename=" + dataFileName + "." + fileExtension)
            .header("Content-Type", mimeType).build();

    // Remove temp file
    try {
        Files.deleteIfExists(Paths.get(TEMP_DIR + "/" + fileName));
    } catch (IOException e) {
        throw ErrorUtils.sendError(e, "Error deleting delimited file", Response.Status.BAD_REQUEST);
    }

    return response;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitDeployer.java

private Repository getSiteRepositoryInstance(String site) throws IOException {

    Path siteRepoPath = Paths.get(rootPath, "sites", site, ".git");
    if (Files.exists(siteRepoPath)) {
        return openGitRepository(siteRepoPath);
    } else {//from w  w  w .ja  v  a2s  . c  o m
        Files.deleteIfExists(siteRepoPath);
        //return cloneRemoteRepository(siteConfiguration.getGitRepositoryUrl(), siteConfiguration.getLocalRepositoryRoot());
    }
    return null;
}

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

@Test(description = "Test for creating new file")
public void testCreateFile() throws IOException {
    Files.deleteIfExists(tempDestPath);
    try {/*  w w w  . j av a2 s  .  c o  m*/
        BValue[] args = { new BString(tempDestPath.toString()) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testCreateFile", args);
        assertTrue(returns[0] instanceof BString);
        assertTrue(Files.exists(tempDestPath));
    } finally {
        Files.deleteIfExists(tempDestPath);
    }
}

From source file:dialog.DialogFunctionUser.java

private void actionEditUser() {
    if (!isValidData()) {
        return;/*from  w w  w.ja  v a 2 s.c  o  m*/
    }
    if (!isValidData()) {
        return;
    }
    String username = tfUsername.getText();
    String fullname = tfFullname.getText();
    String password = mUser.getPassword();
    if (tfPassword.getPassword().length == 0) {
        password = new String(tfPassword.getPassword());
        password = LibraryString.md5(password);
    }
    int role = cbRole.getSelectedIndex();
    if (mAvatar != null) {
        User objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mAvatar.getPath());
        if (mControllerUser.editItem(objUser, mRow)) {
            String fileName = FilenameUtils.getBaseName(mAvatar.getName()) + "-" + System.nanoTime() + "."
                    + FilenameUtils.getExtension(mAvatar.getName());
            Path source = Paths.get(mAvatar.toURI());
            Path destination = Paths.get("files/" + fileName);
            Path pathOldAvatar = Paths.get(mUser.getAvatar());
            try {
                Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
                Files.deleteIfExists(pathOldAvatar);
            } catch (IOException ex) {
                Logger.getLogger(DialogFunctionRoom.class.getName()).log(Level.SEVERE, null, ex);
            }
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    } else {
        User objUser = new User(mUser.getIdUser(), username, password, fullname, role,
                new Date(System.currentTimeMillis()), mUser.getAvatar());
        if (mControllerUser.editItem(objUser, mRow)) {
            ImageIcon icon = new ImageIcon(getClass().getResource("/images/ic_success.png"));
            JOptionPane.showMessageDialog(this.getParent(), "Sa thnh cng", "Success",
                    JOptionPane.INFORMATION_MESSAGE, icon);
        } else {
            JOptionPane.showMessageDialog(this.getParent(), "Sa tht bi", "Fail",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    this.dispose();
}

From source file:com.facebook.presto.hive.TestPrestoS3FileSystem.java

@Test(expectedExceptions = IOException.class, expectedExceptionsMessageRegExp = "Configured staging path is not a directory: .*")
public void testCreateWithStagingDirectoryFile() throws Exception {
    java.nio.file.Path tmpdir = Paths.get(StandardSystemProperty.JAVA_IO_TMPDIR.value());
    java.nio.file.Path staging = Files.createTempFile(tmpdir, "staging", null);
    // staging = /tmp/stagingXXX.tmp

    try (PrestoS3FileSystem fs = new PrestoS3FileSystem()) {
        MockAmazonS3 s3 = new MockAmazonS3();
        Configuration conf = new Configuration();
        conf.set(PrestoS3FileSystem.S3_STAGING_DIRECTORY, staging.toString());
        fs.initialize(new URI("s3n://test-bucket/"), conf);
        fs.setS3Client(s3);//from  w w w .  ja  v  a2  s. c om
        fs.create(new Path("s3n://test-bucket/test"));
    } finally {
        Files.deleteIfExists(staging);
    }
}