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.sleuthkit.autopsy.experimental.configuration.SharedConfiguration.java

/**
 * Upload the current multi-user ingest settings to a shared folder.
 *
 * @throws SharedConfigurationException/*from  w  ww .  java  2  s.c o  m*/
 * @throws CoordinationServiceException
 * @throws InterruptedException
 */
public SharedConfigResult uploadConfiguration()
        throws SharedConfigurationException, CoordinationServiceException, InterruptedException {
    publishTask("Starting shared configuration upload");

    File remoteFolder = getSharedFolder();

    try (Lock writeLock = CoordinationService.getInstance(LOCK_ROOT).tryGetExclusiveLock(
            CoordinationService.CategoryNode.CONFIG, remoteFolder.getAbsolutePath(), 30, TimeUnit.MINUTES)) {
        if (writeLock == null) {
            logger.log(Level.INFO, String.format(
                    "Failed to lock %s - another node is currently uploading or downloading configuration",
                    remoteFolder.getAbsolutePath()));
            return SharedConfigResult.LOCKED;
        }

        // Make sure the local settings have been initialized
        if (!isConfigFolderPopulated(new File(moduleDirPath), false)) {
            logger.log(Level.INFO, "Local configuration has not been initialized.");
            throw new SharedConfigurationException(
                    "Local configuration has not been initialized. Please verify/update and save the settings using the Ingest Module Settings button and then retry the upload.");
        }

        // Write a file to indicate that uploading is in progress. If we crash or
        // have an error, this file will remain in the shared folder.
        File uploadInProgress = new File(remoteFolder, UPLOAD_IN_PROGRESS_FILE);
        if (!uploadInProgress.exists()) {
            try {
                Files.createFile(uploadInProgress.toPath());
            } catch (IOException ex) {
                throw new SharedConfigurationException(
                        String.format("Failed to create %s", uploadInProgress.toPath()), ex);
            }
        }

        // Make sure all recent changes are saved to the preference file
        // Current testing suggests that we do not need to do this for the ingest settings
        // because there is a longer delay between setting them and copying the files.
        try {
            // Make sure all recent changes are saved to the preference file
            // Current testing suggests that we do not need to do this for the ingest settings
            // because there is a longer delay between setting them and copying the files.
            UserPreferences.saveToStorage();
        } catch (BackingStoreException ex) {
            throw new SharedConfigurationException("Failed to save shared configuration settings", ex);
        }

        uploadAutoModeContextSettings(remoteFolder);
        uploadEnabledModulesSettings(remoteFolder);
        uploadFileTypeSettings(remoteFolder);
        uploadInterestingFilesSettings(remoteFolder);
        uploadKeywordSearchSettings(remoteFolder);
        uploadFileExtMismatchSettings(remoteFolder);
        uploadAndroidTriageSettings(remoteFolder);
        uploadMultiUserAndGeneralSettings(remoteFolder);
        uploadHashDbSettings(remoteFolder);
        uploadFileExporterSettings(remoteFolder);

        try {
            Files.deleteIfExists(uploadInProgress.toPath());
        } catch (IOException ex) {
            throw new SharedConfigurationException(
                    String.format("Failed to delete %s", uploadInProgress.toPath()), ex);
        }
    }

    return SharedConfigResult.SUCCESS;
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected void deleteFile(JsonNode stepJsonNode) throws Exception {
    SyncSite syncSite = getSyncSite(stepJsonNode);

    String source = getString(stepJsonNode, "source");

    Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(), source));

    Files.deleteIfExists(targetFilePath);
}

From source file:au.org.ands.vocabs.toolkit.provider.publish.SISSVocPublishProvider.java

/** Remove any existing spec file for SISSVoc.
 * @param taskInfo The TaskInfo object for this task.
 * @param subtask The specification of this publish subtask
 * @param results HashMap representing the result of the unpublish.
 * @return True iff success./*from   ww  w.j  a va 2 s.  c om*/
 */
@SuppressWarnings("unused")
private boolean removeSpecFile(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {
    try {
        Files.deleteIfExists(Paths.get(sissvocSpecOutputPath)
                .resolve(ToolkitFileUtils.getSesameRepositoryId(taskInfo) + ".ttl"));
    } catch (IOException e) {
        // This may mean a file permissions problem, so do log it.
        results.put(TaskStatus.EXCEPTION, "SISSVoc removeSpecFile: failed");
        logger.error("removeSpecFile failed", e);
        return false;
    }
    return true;
}

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

@Test
public void testLoggingNullPointerBug() throws Exception {
    final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Geonet.FORMATTER);
    Level level = logger.getLevel();
    logger.setLevel(Level.ALL);// www  .  ja  v  a 2 s  .  c o m
    try {
        MockHttpServletRequest webRequest = new MockHttpServletRequest();
        webRequest.getSession();
        final ServletWebRequest request = new ServletWebRequest(webRequest, new MockHttpServletResponse());
        final FormatterParams fparams = new FormatterParams();
        fparams.context = this.serviceContext;
        fparams.webRequest = request;
        // make sure context is cleared
        EnvironmentProxy.setCurrentEnvironment(fparams);

        final String formatterName = "logging-null-pointer";
        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, request);

        // no Error is success
    } finally {
        logger.setLevel(level);
    }
}

From source file:de.digiway.rapidbreeze.server.infrastructure.objectstorage.ObjectStorage.java

/**
 * Removes the given entity of the storagea.
 *
 * @param obj/*  ww  w  .  j  a  v  a2s.  com*/
 * @throws IllegalArgumentException if the given object is not a valid
 * entity or does not exist in the storage.
 */
public void remove(Object obj) {
    if (!ObjectStorageHelper.isEntity(obj)) {
        throw new IllegalArgumentException("The given object: " + obj + " is not a valid entity.");
    }
    if (!ObjectStorageHelper.hasValidId(obj)) {
        throw new IllegalArgumentException("The given object: " + obj + " does not have a valid identifier.");
    }

    String tablename = ObjectStorageHelper.getEntityTable(obj);
    String identifier = ObjectStorageHelper.getId(obj);

    if (classMap.containsKey(tablename)) {
        String classIndexFilename = classMap.get(tablename);
        PlainStorageMap classIndexMap = getStorageMap(classIndexFilename);
        if (classIndexMap.containsKey(identifier)) {
            try {
                String objectMapFilename = classIndexMap.remove(identifier);
                Path objectMapPath = fileSystem.getPath(root.toString(), objectMapFilename);
                classIndexMap.commit();
                Files.deleteIfExists(objectMapPath);
            } catch (IOException ex) {
                LOG.log(Level.WARNING, "Cannot remove object property file. Leaving it there.", ex);
            } catch (Exception ex) {
                classIndexMap.rollback();
                throw ex;
            }
            return;
        }
    }
    throw new IllegalArgumentException("Cannot find object: " + obj + " in storage.");
}

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

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

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

    callMainWithoutSystemExit(params);/* www  . j  a va  2s  .  c  o m*/

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

From source file:com.sumzerotrading.intraday.trading.strategy.ReportGeneratorTest.java

@Test
public void testWriteRoundTrip() throws Exception {
    Path path = Files.createTempFile("ReportGeneratorUnitTest", ".txt");
    reportGenerator.outputFile = path.toString();
    String expected = "2016-03-19T07:01:10,LONG,ABC,100,100.23,0,2016-03-20T06:01:10,101.23,0";

    Ticker longTicker = new StockTicker("ABC");
    Ticker shortTicker = new StockTicker("XYZ");
    int longSize = 100;
    int shortSize = 50;
    double longEntryFillPrice = 100.23;
    double longExitFillPrice = 101.23;
    ZonedDateTime entryTime = ZonedDateTime.of(2016, 3, 19, 7, 1, 10, 0, ZoneId.systemDefault());
    ZonedDateTime exitTime = ZonedDateTime.of(2016, 3, 20, 6, 1, 10, 0, ZoneId.systemDefault());

    TradeOrder longEntry = new TradeOrder("123", longTicker, longSize, TradeDirection.BUY);
    longEntry.setFilledPrice(longEntryFillPrice);
    longEntry.setOrderFilledTime(entryTime);
    TradeReferenceLine entryLine = new TradeReferenceLine();
    entryLine.correlationId = "123";
    entryLine.direction = Direction.LONG;
    entryLine.side = Side.ENTRY;//from   w  ww.  j a va 2  s .  com

    TradeOrder longExit = new TradeOrder("123", longTicker, longSize, TradeDirection.SELL);
    longExit.setFilledPrice(longExitFillPrice);
    longExit.setOrderFilledTime(exitTime);
    TradeReferenceLine exitLine = new TradeReferenceLine();
    exitLine.correlationId = "123";
    exitLine.direction = LONG;
    exitLine.side = Side.EXIT;

    RoundTrip roundTrip = new RoundTrip();
    roundTrip.addTradeReference(longEntry, entryLine);
    roundTrip.addTradeReference(longExit, exitLine);

    System.out.println("Writing out to file: " + path);

    reportGenerator.writeRoundTripToFile(roundTrip);

    List<String> lines = Files.readAllLines(path);
    assertEquals(1, lines.size());
    assertEquals(expected, lines.get(0));

    Files.deleteIfExists(path);

}

From source file:de.tiqsolutions.hdfs.HadoopFileSystemProvider.java

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {
    List<CopyOption> optionList = Arrays.asList(options);
    if (!optionList.contains(StandardCopyOption.REPLACE_EXISTING)) {
        if (Files.exists(target))
            throw new java.nio.file.FileAlreadyExistsException(source.toString(), target.toString(),
                    "could not copy file to destination");
    } else {/*from  ww  w .j a  va  2 s.c  o  m*/
        Files.deleteIfExists(target);
    }

    FileSystem sourceFS = source.getFileSystem();
    FileSystem targetFS = target.getFileSystem();

    if (optionList.contains(HadoopCopyOption.REMOTE_COPY) && sourceFS.equals(targetFS)) {

        remoteCopy(source, target, options);
        return;

    }
    try (SeekableByteChannel sourceChannel = sourceFS.provider().newByteChannel(source,
            EnumSet.of(StandardOpenOption.READ))) {

        Set<StandardOpenOption> openOptions = EnumSet.of(StandardOpenOption.WRITE);

        if (optionList.contains(StandardCopyOption.REPLACE_EXISTING))
            openOptions.add(StandardOpenOption.CREATE);
        else
            openOptions.add(StandardOpenOption.CREATE_NEW);
        List<FileAttribute<?>> fileAttributes = new ArrayList<>();
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {

            Set<String> sourceAttrViews = sourceFS.supportedFileAttributeViews();
            Set<String> targetAttrViews = targetFS.supportedFileAttributeViews();
            if (sourceAttrViews.contains(PosixFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(PosixFileAttributeViewImpl.NAME)) {
                PosixFileAttributes posixAttributes = sourceFS.provider().readAttributes(source,
                        PosixFileAttributes.class);
                fileAttributes.add(PosixFilePermissions.asFileAttribute(posixAttributes.permissions()));
            }

            if (sourceAttrViews.contains(HadoopFileAttributeViewImpl.NAME)
                    && targetAttrViews.contains(HadoopFileAttributeViewImpl.NAME)) {
                final HadoopFileAttributes hdfsAttributes = sourceFS.provider().readAttributes(source,
                        HadoopFileAttributes.class);
                fileAttributes.add(new FileAttribute<Long>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":blockSize";
                    }

                    @Override
                    public Long value() {
                        return hdfsAttributes.getBlockSize();
                    }
                });
                fileAttributes.add(new FileAttribute<Short>() {
                    @Override
                    public String name() {
                        return HadoopFileAttributeViewImpl.NAME + ":replication";
                    }

                    @Override
                    public Short value() {
                        return hdfsAttributes.getReplication();
                    }
                });

            }
        }

        FileAttribute<?>[] attributes = fileAttributes.toArray(new FileAttribute<?>[fileAttributes.size()]);

        try (SeekableByteChannel targetChannel = targetFS.provider().newByteChannel(target, openOptions,
                attributes)) {
            int buffSize = getConfiguration().getInt(DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_KEY,
                    DFSConfigKeys.DFS_STREAM_BUFFER_SIZE_DEFAULT);
            ByteBuffer buffer = ByteBuffer.allocate(buffSize);
            buffer.clear();
            while (sourceChannel.read(buffer) > 0) {
                buffer.flip();
                targetChannel.write(buffer);
                buffer.clear();
            }

        }
        if (optionList.contains(StandardCopyOption.COPY_ATTRIBUTES)) {
            BasicFileAttributes attrs = sourceFS.provider().readAttributes(source, BasicFileAttributes.class);
            BasicFileAttributeView view = targetFS.provider().getFileAttributeView(target,
                    BasicFileAttributeView.class);
            view.setTimes(attrs.lastModifiedTime(), attrs.lastAccessTime(), attrs.creationTime());

        }

    }

}

From source file:com.sesnu.orion.web.service.ReportService.java

public String generatePayAuthReport(Approval app, String state) throws DocumentException, IOException {
    Payment pay = payDao.get(app.getForId());
    OrderView order = orderDao.get(pay.getOrderRef());
    Item item = itemDao.get(order.getItemId());
    List<DuLicenseView> licenses = licenseDao.listByOrderId(order.getId());
    String git = "NA";
    if (licenses.size() > 0) {
        git = licenses.get(0).getGit();//from   w ww.j  a  va2  s. co  m
    }

    String orginalHtml = conf.getFile("payAuth.html");

    String editedHtml = orginalHtml.replace("ORDER_REF", order.getInvNo());
    editedHtml = setPaths(editedHtml, state);
    editedHtml = editedHtml.replace("PRODUCT_NAME", item.getName());
    String bl = order.getBl() == null ? "NA" : order.getBl();
    editedHtml = editedHtml.replace("BILL_OF_LOADING", bl);
    editedHtml = editedHtml.replace("BRAND_NAME", item.getBrand());
    editedHtml = editedHtml.replace("G_I_T", git);
    editedHtml = editedHtml.replace("PACKAGING",
            order.getBaseSize().toString() + order.getBaseUnit() + "X" + order.getQtyPerPack() + "pcs");
    editedHtml = editedHtml.replace("QTY_PER_CONT", order.getPckPerCont().toString());
    editedHtml = editedHtml.replace("DESTINATION", order.getDestinationPort());
    editedHtml = editedHtml.replace("QUANTITY", order.getContQnt() + "X" + order.getContSize() + "'");
    editedHtml = editedHtml.replace("PAYMENT_DATE", pay.getUpdatedOn());

    // create request body
    StringBuilder sb = new StringBuilder();
    sb.append("<tr>");
    sb.append("<td>" + pay.getName() + "</td>");
    sb.append("<td>" + pay.getPaymentMethod() + "</td>");
    sb.append("<td>" + pay.getCurr() + "</td>");
    sb.append("<td>" + pay.getDeposit() + "</td>");
    sb.append("<td>" + pay.getEstimate() + "</td>");
    sb.append("<td>" + pay.getPaymentAmount() + "</td>");
    String rmrk = pay.getRemark() == null ? "" : pay.getRemark();
    sb.append("<td>" + rmrk + "</td>");
    sb.append("</tr>");
    editedHtml = editedHtml.replace("BID_DATA_TABLE", sb.toString());

    String emailTo = app.getRequestedBy() + " [" + (userDao.getUserName(app.getRequestedBy())).getEmail() + "]";
    String emailCC = app.getApprover() + " [" + (userDao.getUserName(app.getApprover())).getEmail() + "]";
    editedHtml = editedHtml.replace("EMAIL_TO", emailTo);
    editedHtml = editedHtml.replace("EMAIL_CC", emailCC);

    if (!state.equals("preview")) {
        editedHtml = editedHtml.replace("SIGNATURE", app.getApprover());
        editedHtml = editedHtml.replace("APPROVED_DATE", new Date().toGMTString());
        String pdfFilePath = util.convertToPdf(editedHtml); // convert to pdf
        Path path = Paths.get(pdfFilePath);
        byte[] data = Files.readAllBytes(path); // convert to byte array
        String[] frag = pdfFilePath.split("/");
        String fileName = frag[frag.length - 1]; // get file name
        util.writeToS3(data, fileName); // write to s3
        sendApprovalEmail(app, pdfFilePath, order);
        Files.deleteIfExists(path);

        Document doc = new Document(order.getId(), fileName, "Payment[" + pay.getName() + "]",
                Util.parseDate(new Date()), "Approval");
        docDao.saveOrUpdate(doc);
    } else {
        editedHtml = editedHtml.replace("APPROVED_DATE", "");
    }

    return editedHtml;
}

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public void upload(String urlDirectory, String sanitizedName, InputStream in) throws C5CException {
    Path parentFolder = buildRealPathAndCheck(urlDirectory);
    Path fileToSave = parentFolder.resolve(sanitizedName);
    try {/*from  w  w  w  . ja v a 2 s  . c o  m*/
        Files.deleteIfExists(fileToSave);
        Files.copy(in, fileToSave, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.InvalidFileUpload,
                sanitizedName);
    }
}