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.wso2.carbon.event.simulator.core.internal.generator.csv.util.FileUploader.java

/**
 * Method to delete an uploaded file./*ww  w  . j  av  a  2s  . c om*/
 *
 * @param fileName name of CSV file to be deleted
 * @throws FileOperationsException if an IOException occurs while deleting file
 */
public boolean deleteFile(String fileName, String destination) throws FileOperationsException {
    try {
        if (fileStore.checkExists(fileName)) {
            /*
             * Update deletes the csv file and uploads the new file.
             * since the deployer takes about 15 seconds to update the fileStore, a request to update a csv file
             * where existing file name and new file names is the same may fail if the filename isn't deleted
             * from the fileStore.
             * */
            fileStore.deleteFile(fileName);
        }
        return Files.deleteIfExists(Paths.get(destination, fileName));
    } catch (IOException e) {
        log.error("Error occurred while deleting the file '" + fileName + "'", e);
        throw new FileOperationsException("Error occurred while deleting the file '" + fileName + "'", e);
    }
}

From source file:org.onehippo.cms7.essentials.dashboard.utils.JavaSourceUtilsTest.java

@Override
@After/*ww  w . j  av a2s. c  o  m*/
public void tearDown() throws Exception {
    super.tearDown();
    if (path != null) {
        Files.deleteIfExists(path);
    }
    if (docPath != null) {
        Files.deleteIfExists(docPath);
    }
    if (componentFile != null) {
        Files.deleteIfExists(componentFile);
    }

}

From source file:org.linagora.linshare.webservice.uploadrequest.impl.FlowUploaderRestServiceImpl.java

@Path("/")
@POST/*  ww  w  . ja v a 2s.  c o  m*/
@Consumes("multipart/form-data")
@Override
public Response uploadChunk(@Multipart(CHUNK_NUMBER) long chunkNumber,
        @Multipart(TOTAL_CHUNKS) long totalChunks, @Multipart(CHUNK_SIZE) long chunkSize,
        @Multipart(TOTAL_SIZE) long totalSize, @Multipart(IDENTIFIER) String identifier,
        @Multipart(FILENAME) String filename, @Multipart(RELATIVE_PATH) String relativePath,
        @Multipart(FILE) InputStream file, MultipartBody body,
        @Multipart(REQUEST_URL_UUID) String uploadRequestUrlUuid, @Multipart(PASSWORD) String password)
        throws BusinessException {

    logger.debug("upload chunk number : " + chunkNumber);
    identifier = cleanIdentifier(identifier);
    Validate.isTrue(isValid(chunkNumber, chunkSize, totalSize, identifier, filename));
    try {
        logger.debug("writing chunk number : " + chunkNumber);
        java.nio.file.Path tempFile = getTempFile(identifier);
        FileChannel fc = FileChannel.open(tempFile, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        byte[] byteArray = IOUtils.toByteArray(file);
        fc.write(ByteBuffer.wrap(byteArray), (chunkNumber - 1) * chunkSize);
        fc.close();
        chunkedFiles.get(identifier).addChunk(chunkNumber);
        if (isUploadFinished(identifier, chunkSize, totalSize)) {
            logger.debug("upload finished ");
            InputStream inputStream = Files.newInputStream(tempFile, StandardOpenOption.READ);
            File tempFile2 = getTempFile(inputStream, "rest-flowuploader", filename);
            try {
                uploadRequestUrlFacade.addUploadRequestEntry(uploadRequestUrlUuid, password, tempFile2,
                        filename);
            } finally {
                deleteTempFile(tempFile2);
            }
            ChunkedFile remove = chunkedFiles.remove(identifier);
            Files.deleteIfExists(remove.getPath());
            return Response.ok("upload success").build();
        } else {
            logger.debug("upload pending ");
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return Response.ok("upload success").build();
}

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

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

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

    callMainWithoutSystemExit(params);/*ww  w  . j  a  v  a2  s. c  o m*/

    Container container = ContainerOpener.open(fileName);
    assertEquals(SignatureProfile.LT, container.getSignature(0).getProfile());
}

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

public String generateOrderAuthReport(Approval appr, String state) throws DocumentException, IOException {
    Bid bid = bidDao.get(appr.getForId());
    OrderView order = orderDao.get(bid.getOrderRef());
    Item item = itemDao.get(order.getItemId());
    List<BidView> bids = bidDao.list(order.getId());

    String orginalHtml = conf.getFile("orderAuth.html");
    Estimate est = estService.totalEstimate(order, null, bid, item);

    String editedHtml = orginalHtml.replace("ORDER_DATE", Util.parseDate(order.getCreatedOn()));
    editedHtml = setPaths(editedHtml, state);
    editedHtml = editedHtml.replace("PRODUCT_NAME", item.getName());
    editedHtml = editedHtml.replace("ORDERED_BY", order.getOrderedBy());
    editedHtml = editedHtml.replace("BRAND_NAME", item.getBrand());
    editedHtml = editedHtml.replace("DEPARTMENT", "Import"); // whose department ?
    editedHtml = editedHtml.replace("PACKAGING",
            order.getBaseSize().toString() + order.getBaseUnit() + "X" + order.getQtyPerPack() + "pcs");
    editedHtml = editedHtml.replace("BUDGET_REF", order.getBudgetRef());
    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("LATEST_ETA", Util.parseDate(order.getLatestETA()));

    editedHtml = editedHtml.replace("IN_TRANSIT", shipDao.InTransitCount(item.getId()).toString());
    editedHtml = editedHtml.replace("IN_PORT", shipDao.InPortCount(item.getId()).toString());
    editedHtml = editedHtml.replace("IN_TERMINAL", shipDao.InTerminalCount(item.getId()).toString());
    BigInteger newItemOrders = orderDao.newOrdersCount(item.getId()).subtract(new BigInteger("1"));
    editedHtml = editedHtml.replace("NEW_ORDERS", newItemOrders.toString());
    editedHtml = editedHtml.replace("ORDER_DATE", bid.getUpdatedOn());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bids.size(); i++) {
        BidView abid = bids.get(i);//from   w  w  w .ja  va  2 s .  c o m
        sb.append("<tr>");
        sb.append("<td>");
        sb.append(i + 1);
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getSupplier());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getCifCnf());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getFob());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getCurrency());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getPaymentMethod() == null ? "" : abid.getPaymentMethod());
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.isSelected() ? "Yes" : "No");
        sb.append("</td>");
        sb.append("<td>");
        sb.append(abid.getRemark() == null ? "" : abid.getRemark());
        sb.append("</td>");
        sb.append("</tr>");
    }

    editedHtml = editedHtml.replace("BID_DATA_TABLE", sb.toString());
    editedHtml = editedHtml.replace("EST_TRANSIT_DAYS", bid.getEstTransitDays().toString());
    Calendar c = Calendar.getInstance();
    c.setTime(order.getLatestETA());
    c.add(Calendar.DATE, bid.getEstTransitDays());
    editedHtml = editedHtml.replace("LATEST_DATE_OF_SHIP", Util.parseDate(c.getTime()));
    editedHtml = editedHtml.replace("IMPORTER", order.getImporter());

    Exchange cur = exchangeDao.get("Other", "Other", "USD", "AOA");
    if (cur == null) {
        return null;
    }

    editedHtml = editedHtml.replace("TOTAL_CNF_USD", Util.parseCurrency(bid.getTotalBid()));
    Double pricePerPack = (bid.getTotalBid() * cur.getRate() + est.getValue()) / order.getContQnt()
            / order.getPckPerCont();
    pricePerPack = pricePerPack / cur.getRate();
    pricePerPack = (double) (Math.round(pricePerPack * 100.0) / 100);
    editedHtml = editedHtml.replace("LANDED_COST_TO_WH", pricePerPack.toString());
    Double totalEstPrice = pricePerPack * 1.12;
    editedHtml = editedHtml.replace("COST_PLUS_MRG", totalEstPrice.toString());
    String emailTo = appr.getRequestedBy() + " [" + (userDao.getUserName(appr.getRequestedBy())).getEmail()
            + "]";
    String emailCC = appr.getApprover() + " [" + (userDao.getUserName(appr.getApprover())).getEmail() + "]";
    editedHtml = editedHtml.replace("EMAIL_TO", emailTo);
    editedHtml = editedHtml.replace("EMAIL_CC", emailCC);

    if (!state.equals("preview")) {
        editedHtml = editedHtml.replace("SIGNATURE", appr.getApprover());
        editedHtml = editedHtml.replace("APPROVED_ON", 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(appr, pdfFilePath, order);
        Files.deleteIfExists(path);

        Document doc = new Document(order.getId(), fileName, "Order Authorization", Util.parseDate(new Date()),
                "");
        docDao.saveOrUpdate(doc);
    } else {
        editedHtml = editedHtml.replace("APPROVED_ON", "");
    }
    return editedHtml;
}

From source file:com.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ????./*from www . j  a va  2  s.c  om*/
 * 
 * @param metadata ?urlTree
 * @param ctx urlTree
 */
@Override
public void delete(UrlTreeMetaData<InputStream> metadata, UrlTreeContext ctx) throws BadContentException {
    Path f = generateFileObj(metadata.getAbsolutePath());
    logger.debug("delete: " + f.getFileName());
    try {
        boolean deleted = Files.deleteIfExists(f);
        if (!deleted) {
            throw new IOException("file not exists");
        }
    } catch (IOException e) {
        // TargetNotFound???BadContent???
        throw new GenericResourceException("cannot delete file", e);
    }
}

From source file:com.gitpitch.services.DiskService.java

public void delete(Path filePath) {

    try {
        Files.deleteIfExists(filePath);
    } catch (Exception dex) {
    }
}

From source file:org.talend.dataprep.folder.store.file.FileSystemFolderRepository.java

@Override
public FolderEntry addFolderEntry(FolderEntry folderEntry, String folderId) {
    FolderPath folderPath = fromId(folderId);

    if (folderPath == null) {
        throw new TDPException(FOLDER_DOES_NOT_EXIST, build().put("id", folderId));
    }/*  www .jav a  2s  . c  o m*/

    // we store the FolderEntry bean content as properties the file name is the name
    try {
        String fileName = buildFileName(folderEntry);

        Path entryFilepath = pathsConverter.toPath(folderPath).resolve(fileName);

        // we delete it if exists
        Files.deleteIfExists(entryFilepath);

        Path parentPath = entryFilepath.getParent();
        // check parent path first
        if (Files.notExists(parentPath)) {
            Files.createDirectories(parentPath);
        }

        entryFilepath = Files.createFile(entryFilepath);
        folderEntry.setFolderId(folderId);

        try (OutputStream outputStream = Files.newOutputStream(entryFilepath)) {
            writeEntryToStream(folderEntry, outputStream);
        }
        return folderEntry;
    } catch (IOException e) {
        throw new TDPException(UNABLE_TO_ADD_FOLDER_ENTRY, e, build().put("path", folderPath));
    }
}

From source file:org.elasticwarehouse.core.ElasticWarehouseAPIProcessorUpload.java

public boolean processRequest(Client esClient, OutputStream os, ElasticWarehouseAPIProcessorUploadParams params)
        throws FileNotFoundException, IOException {
    boolean ret = false;
    if (params.validateInputParams(esClient, os)) {
        String tempfolder = conf_.getWarehouseValue(ElasticWarehouseConf.TMPPATH);

        String tmpfilename = params.filename;
        String tmpfilepath = tempfolder;
        if (!tmpfilepath.endsWith("/"))
            tmpfilepath += "/";
        LOGGER.debug("Uploading file to: " + tmpfilepath + tmpfilename);
        FileOutputStream fos = new FileOutputStream(tmpfilepath + tmpfilename);
        fos.write(params.bytes);//from   w  ww  . j  ava  2  s  .  c  o m
        fos.close();

        if (params.folder != null && params.folder.length() > 0) {
            ElasticWarehouseFolder fldr = new ElasticWarehouseFolder(params.folder, conf_);
            elasticSearchAccessor_.indexFolder(fldr);
        }

        IndexingResponse indexingreponse = elasticSearchAccessor_.uploadFile(tmpfilepath, tmpfilename,
                params.folder, params.id, "upload");
        if (indexingreponse != null) {
            if (indexingreponse.error_ == null && indexingreponse.error_.length() > 0) {
                os.write(responser.errorMessage("Indexing error: " + indexingreponse.error_,
                        ElasticWarehouseConf.URL_GUIDE_UPLOAD));
            } else {
                IndexResponse ir = indexingreponse.response_;

                XContentBuilder builder = jsonBuilder().startObject().field("id", ir.getId())
                        .field("version", ir.getVersion()).field("created", ir.isCreated());
                String s = builder.endObject().string();
                os.write(s.getBytes());
                ret = true;
            }
        } else {
            os.write(responser.errorMessage("Someting went wrong. Please upload file once again.",
                    ElasticWarehouseConf.URL_GUIDE_UPLOAD));
        }
        Files.deleteIfExists(new File(tmpfilepath + tmpfilename).toPath());
    }
    return ret;
}

From source file:org.corehunter.tests.data.simple.SimpleFrequencyGenotypeDataTest.java

@Test
public void toTxtFile() throws IOException {
    dataName = "out.txt";
    expectedHeaders = HEADERS_UNIQUE_NAMES;
    expectedMarkerNames = MARKER_NAMES;/*from w  w  w  .j a  va 2s  .  c  o  m*/
    expectedAlleleNames = UNDEFINED_ALLELE_NAMES;

    SimpleFrequencyGenotypeData genotypicData = new SimpleFrequencyGenotypeData(expectedHeaders,
            expectedMarkerNames, expectedAlleleNames, ALLELE_FREQUENCIES);

    Path path = Paths.get(TEST_OUTPUT);

    Files.createDirectories(path);

    path = Files.createTempDirectory(path, "GenoFreqs-Txt");

    path = Paths.get(path.toString(), dataName);

    Files.deleteIfExists(path);

    System.out.println(" |- Write File " + dataName);
    genotypicData.writeData(path, FileType.TXT);

    System.out.println(" |- Read written File " + dataName);
    testData(SimpleFrequencyGenotypeData.readData(path, FileType.TXT));
}