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.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private void commitUpdates(StorageRequest request) throws StorageException {
    try {//from w  w w.  ja  v  a  2  s. com
        for (String contentUri : updateMap.get(request.getId())) {
            Path contentIdDir = getTempContentItemDir(request.getId(), new URI(contentUri));
            Path target = getContentItemDir(new URI(contentUri));
            try {
                if (Files.exists(contentIdDir)) {
                    if (Files.exists(target)) {
                        List<Path> files = listPaths(target);
                        for (Path file : files) {
                            if (!Files.isDirectory(file)) {
                                Files.deleteIfExists(file);
                            }
                        }
                    }
                    Files.createDirectories(target.getParent());
                    Files.move(contentIdDir, target, StandardCopyOption.REPLACE_EXISTING);
                }
            } catch (IOException e) {
                LOGGER.debug(
                        "Unable to move files by simple rename, resorting to copy. This will impact performance.",
                        e);
                try {
                    Path createdTarget = Files.createDirectories(target);
                    List<Path> files = listPaths(contentIdDir);
                    Files.copy(files.get(0), Paths.get(createdTarget.toAbsolutePath().toString(),
                            files.get(0).getFileName().toString()));
                } catch (IOException e1) {
                    throw new StorageException("Unable to commit changes for request: " + request.getId(), e1);
                }
            }
        }
    } catch (URISyntaxException e) {
        throw new StorageException(e);
    } finally {
        rollback(request);
    }
}

From source file:org.apache.solr.handler.PingRequestHandler.java

protected void handleEnable(boolean enable) throws SolrException {
    if (healthcheck == null) {
        throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "No healthcheck file defined.");
    }/*from   w w w. j  a  v  a2 s.com*/
    if (enable) {
        try {
            // write out when the file was created
            FileUtils.write(healthcheck, Instant.now().toString(), "UTF-8");
        } catch (IOException e) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unable to write healthcheck flag file", e);
        }
    } else {
        try {
            Files.deleteIfExists(healthcheck.toPath());
        } catch (Throwable cause) {
            throw new SolrException(SolrException.ErrorCode.NOT_FOUND,
                    "Did not successfully delete healthcheck file: " + healthcheck.getAbsolutePath(), cause);
        }
    }
}

From source file:com.sumzerotrading.eod.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,Short,XYZ,50,250.34,0,251.34,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;
    double shortEntryFillPrice = 250.34;
    double shortExitFillPrice = 251.34;
    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);

    TradeOrder longExit = new TradeOrder("123", longTicker, longSize, TradeDirection.SELL);
    longExit.setFilledPrice(longExitFillPrice);
    longExit.setOrderFilledTime(exitTime);

    TradeOrder shortEntry = new TradeOrder("123", shortTicker, shortSize, TradeDirection.SELL);
    shortEntry.setFilledPrice(shortEntryFillPrice);
    shortEntry.setOrderFilledTime(entryTime);

    TradeOrder shortExit = new TradeOrder("123", shortTicker, shortSize, TradeDirection.BUY);
    shortExit.setFilledPrice(shortExitFillPrice);
    shortExit.setOrderFilledTime(exitTime);

    RoundTrip roundTrip = new RoundTrip();
    roundTrip.longEntry = longEntry;//  w w w.  j  a  v a2s . c om
    roundTrip.longExit = longExit;
    roundTrip.shortEntry = shortEntry;
    roundTrip.shortExit = shortExit;

    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:org.digidoc4j.main.DigiDoc4JTest.java

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

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

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

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

From source file:org.jboss.as.test.integration.domain.SlaveHostControllerAuthenticationTestCase.java

private void removeCredentialStore(String storeName, Path storageFile) throws Exception {
    ModelNode op = new ModelNode();
    op.get(OP).set(REMOVE);//  w  w w.  j  a  va2  s  .c o  m
    op.get(OP_ADDR).add(HOST, "slave").add(SUBSYSTEM, "elytron").add("credential-store", storeName);
    getDomainSlaveClient().execute(new OperationBuilder(op).build());
    Files.deleteIfExists(CREDNETIAL_STORE_STORAGE_FILE);
    reloadSlave();
    testSupport.getDomainSlaveLifecycleUtil().awaitHostController(System.currentTimeMillis());
}

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

@Test
public void testReportGeneratorEndToEnd() throws Exception {
    StockTicker longTicker = new StockTicker("ABC");
    StockTicker shortTicker = new StockTicker("XYZ");

    ZonedDateTime entryOrderTime = ZonedDateTime.of(2016, 3, 25, 6, 18, 35, 0, ZoneId.systemDefault());
    ZonedDateTime exitOrderTime = ZonedDateTime.of(2016, 3, 25, 6, 19, 35, 0, ZoneId.systemDefault());

    String directory = System.getProperty("java.io.tmpdir");
    if (!directory.endsWith("/")) {
        directory += "/";
    }//w  w w . j  a  v  a  2s  .  c  o m
    Path reportPath = Paths.get(directory + "report.csv");
    Files.deleteIfExists(reportPath);
    System.out.println("Creating directory at: " + directory);
    ReportGenerator generator = new ReportGenerator(directory);

    TradeOrder longEntryOrder = new TradeOrder("123", longTicker, 100, TradeDirection.BUY);
    longEntryOrder.setFilledPrice(100.00);
    longEntryOrder.setReference("Intraday-Strategy:guid-123:Entry:Long*");
    longEntryOrder.setCurrentStatus(OrderStatus.Status.FILLED);
    longEntryOrder.setOrderFilledTime(entryOrderTime);

    generator.orderEvent(new OrderEvent(longEntryOrder, null));
    assertFalse(Files.exists(reportPath));

    TradeOrder longExitOrder = new TradeOrder("1234", longTicker, 100, TradeDirection.SELL);
    longExitOrder.setFilledPrice(105.00);
    longExitOrder.setReference("Intraday-Strategy:guid-123:Exit:Long*");
    longExitOrder.setCurrentStatus(OrderStatus.Status.FILLED);
    longExitOrder.setOrderFilledTime(exitOrderTime);

    generator.orderEvent(new OrderEvent(longExitOrder, null));
    assertTrue(Files.exists(reportPath));

    List<String> lines = Files.readAllLines(reportPath);
    assertEquals(1, lines.size());

    String line = lines.get(0);
    String expected = "2016-03-25T06:18:35,LONG,ABC,100,100.0,0,2016-03-25T06:19:35,105.0,0";
    assertEquals(expected, line);

    generator.orderEvent(new OrderEvent(longEntryOrder, null));
    generator.orderEvent(new OrderEvent(longExitOrder, null));

    lines = Files.readAllLines(reportPath);
    assertEquals(2, lines.size());
    assertEquals(expected, lines.get(0));
    assertEquals(expected, lines.get(1));

}

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

@Test
public void testReportGeneratorEndToEnd() throws Exception {
    StockTicker longTicker = new StockTicker("ABC");
    StockTicker shortTicker = new StockTicker("XYZ");

    ZonedDateTime entryOrderTime = ZonedDateTime.of(2016, 3, 25, 6, 18, 35, 0, ZoneId.systemDefault());
    ZonedDateTime exitOrderTime = ZonedDateTime.of(2016, 3, 25, 6, 19, 35, 0, ZoneId.systemDefault());

    String directory = System.getProperty("java.io.tmpdir");
    if (!directory.endsWith("/")) {
        directory += "/";
    }//  w  w w. j  a  v  a2 s.co  m
    Path reportPath = Paths.get(directory + "report.csv");
    Files.deleteIfExists(reportPath);
    System.out.println("Creating directory at: " + directory);
    ReportGenerator generator = new ReportGenerator(directory);

    TradeOrder longEntryOrder = new TradeOrder("123", longTicker, 100, TradeDirection.BUY);
    longEntryOrder.setFilledPrice(100.00);
    longEntryOrder.setReference("EOD-Pair-Strategy:guid-123:Entry:Long*");
    longEntryOrder.setCurrentStatus(OrderStatus.Status.FILLED);
    longEntryOrder.setOrderFilledTime(entryOrderTime);

    TradeOrder shortEntryOrder = new TradeOrder("234", shortTicker, 50, TradeDirection.SELL);
    shortEntryOrder.setFilledPrice(50.00);
    shortEntryOrder.setReference("EOD-Pair-Strategy:guid-123:Entry:Short*");
    shortEntryOrder.setCurrentStatus(OrderStatus.Status.FILLED);
    shortEntryOrder.setOrderFilledTime(entryOrderTime);

    generator.orderEvent(new OrderEvent(longEntryOrder, null));
    assertFalse(Files.exists(reportPath));

    generator.orderEvent(new OrderEvent(shortEntryOrder, null));
    assertFalse(Files.exists(reportPath));

    TradeOrder longExitOrder = new TradeOrder("1234", longTicker, 100, TradeDirection.SELL);
    longExitOrder.setFilledPrice(105.00);
    longExitOrder.setReference("EOD-Pair-Strategy:guid-123:Exit:Long*");
    longExitOrder.setCurrentStatus(OrderStatus.Status.FILLED);
    longExitOrder.setOrderFilledTime(exitOrderTime);

    TradeOrder shortExitOrder = new TradeOrder("2345", shortTicker, 50, TradeDirection.BUY);
    shortExitOrder.setFilledPrice(40.00);
    shortExitOrder.setReference("EOD-Pair-Strategy:guid-123:Exit:Short*");
    shortExitOrder.setCurrentStatus(OrderStatus.Status.FILLED);
    shortExitOrder.setOrderFilledTime(exitOrderTime);

    generator.orderEvent(new OrderEvent(longExitOrder, null));
    assertFalse(Files.exists(reportPath));

    generator.orderEvent(new OrderEvent(shortExitOrder, null));
    assertTrue(Files.exists(reportPath));

    List<String> lines = Files.readAllLines(reportPath);
    assertEquals(1, lines.size());

    String line = lines.get(0);
    String expected = "2016-03-25T06:18:35,Long,ABC,100,100.0,0,2016-03-25T06:19:35,105.0,0,Short,XYZ,50,50.0,0,40.0,0";
    assertEquals(expected, line);

    generator.orderEvent(new OrderEvent(longEntryOrder, null));
    generator.orderEvent(new OrderEvent(longExitOrder, null));
    generator.orderEvent(new OrderEvent(shortEntryOrder, null));
    generator.orderEvent(new OrderEvent(shortExitOrder, null));

    lines = Files.readAllLines(reportPath);
    assertEquals(2, lines.size());
    assertEquals(expected, lines.get(0));
    assertEquals(expected, lines.get(1));

}

From source file:com.chortitzer.web.admin.controller.TiemposBean.java

public void processMarcasFile() {
    try {//from www .  j  a  v a  2  s  .com
        FacesContext.getCurrentInstance().addMessage("form:msgs",
                new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Cargando..."));
        String fileName = "C:\\Users\\adriang\\Documents\\Synel\\SYBridge\\Data\\Collect.dat";
        if (Files.exists(Paths.get(fileName))) {

            Path file = Paths.get(fileName);
            Integer countNoRegistrados = 0;
            Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name());
            while (scanner.hasNextLine()) {
                String aLine = scanner.nextLine();
                SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyHHmm");
                Date d = formatter.parse(aLine.substring(10, 16) + aLine.substring(29, 33));
                //System.out.println(d.toString());
                //System.out.println(aLine.substring(18, 29));
                //System.out.println(aLine.substring(16, 17));

                RrhhMarcas rrhhMarcas = new RrhhMarcas();
                rrhhMarcas.setFechahora(d);
                rrhhMarcas.setNroEmpleado(rrhhEmpleadosRepo.findOne(Integer.parseInt(aLine.substring(18, 29))));
                rrhhMarcas.setEntradaSalida(Integer.parseInt(aLine.substring(17, 18)));

                //if (em.find(RrhhTiempos.class, rrhhTiemposPK) == null) {
                if (rrhhMarcas.getNroEmpleado() == null) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                            FacesMessage.SEVERITY_ERROR, "Error!",
                            "Existen registros para empleados no identificacdos en la base de datos! - Nro.: "
                                    + aLine.substring(18, 29)));
                    countNoRegistrados += 1;
                    System.out.println("Empleado sin registro: " + aLine.substring(18, 29));
                } else {
                    rrhhMarcasRepo.save(rrhhMarcas);
                }

            }
            limpiarMarcasDobles();
            if (countNoRegistrados == 0) {
                Files.deleteIfExists(file);
            }
        }
    } catch (Exception ex) {
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
        FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage()));
    }
}

From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java

@Override
public String delResource(ServiceContext context, String metadataUuid, String resourceId) throws Exception {
    canEdit(context, metadataUuid);/*from  w w w .  ja va2 s.  c  o m*/

    Path filePath = getResource(context, metadataUuid, resourceId);

    try {
        Files.deleteIfExists(filePath);
        return String.format("MetadataResource '%s' removed.", resourceId);
    } catch (IOException e) {
        return String.format("Unable to remove resource '%s'.", resourceId);
    }
}

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

@Test
public void createsContainerWithTypeSettingBDocIfNoSuitableFileExtensionAndNoType() throws Exception {
    System.setProperty("digidoc4j.mode", "TEST");
    String fileName = "test1.test";
    Files.deleteIfExists(Paths.get(fileName));

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

    callMainWithoutSystemExit(params);//from  w w w. j  a v a  2  s . co  m

    Container container = ContainerOpener.open(fileName);
    assertEquals("BDOC", container.getType());
    System.setProperty("digidoc4j.mode", "PROD");
}