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:at.ac.tuwien.ims.latex2mobiformulaconv.tests.integration.EndToEndConversionTest.java

/**
 * tests the renaming scheme for handling existing filenames
 *
 * @throws Exception//from   w w  w .  ja v  a 2s.c  o  m
 */
@Test
public void testConvertFileExists() throws Exception {
    Path existingFile = outputPath.resolve(filename + ext);
    assertTrue(Files.exists(existingFile) == false);
    Files.createFile(existingFile);
    assertTrue(Files.exists(existingFile));

    // Modify expected output file location
    outputFilePath = outputPath.resolve(filename + " (1)" + ext);
    testConvertCreatesFiles(dom_converter);
    assertTrue(Files.exists(existingFile));
    assertTrue(Files.exists(outputFilePath));

    // delete created stub file
    Files.deleteIfExists(existingFile);
}

From source file:uk.ac.ebi.metabolights.webservice.utils.FileUtil.java

/**
 * Delete a single file//from  w  ww.jav a  2s  .  c  o m
 *
 * @param fileName to be deleted
 * @return success/fail status
 * @author jrmacias
 * @date 20151012
 */
public static boolean deleteFile(String fileName) {

    boolean result = false;

    try {
        // try to delete the file
        result = Files.deleteIfExists(FileSystems.getDefault().getPath(fileName));
        logger.info("File {} have {} been deleted.", fileName, result ? "successfully" : "not");
    } catch (IOException ex) {
        logger.error("Error deleting file: {}", ex.getMessage());
    }
    return result;
}

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

@Test
public void createsContainerWithSignatureProfileIsBESForBDoc() 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", "B_BES" };

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

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

From source file:io.apiman.common.es.util.ApimanEmbeddedElastic.java

private void checkForDanglingProcesses() throws IOException {
    if (Files.exists(pidPath)) {
        for (String pid : Files.readAllLines(pidPath)) {
            System.err.println(//w  w w . j  av a 2  s . c o m
                    "Attempting to kill Elasticsearch process left over from previous execution: " + pid);
            Process result = Runtime.getRuntime().exec("kill " + pid);
            IOUtils.copy(result.getInputStream(), System.out);
            IOUtils.copy(result.getErrorStream(), System.err);
            result.destroy();
        }
        Files.deleteIfExists(pidPath);
    }
}

From source file:com.qwazr.library.audio.AudioParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {
    String format = getParameterValue(parameters, FORMAT, 0);
    if (StringUtils.isEmpty(format))
        format = extension;/* w w w  . j  a va  2s  .c o  m*/
    if (StringUtils.isEmpty(format) && mimeType != null)
        format = MIMEMAP.get(mimeType.intern());
    if (StringUtils.isEmpty(format))
        throw new Exception("The format is not found");
    final Path tempFile = ParserAbstract.createTempFile(inputStream, '.' + format);
    try {
        parseContent(parameters, tempFile, extension, mimeType, resultBuilder);
    } finally {
        Files.deleteIfExists(tempFile);
    }
}

From source file:org.digidoc4j.DataFileTest.java

@Ignore("Data files are not written on disk")
@Test(expected = DigiDoc4JException.class)
public void askingDataFileSizeWhenTemporoaryFileIsDeleted() throws Exception {
    try (ByteArrayInputStream inputStream = new ByteArrayInputStream("tere tere tipajalga".getBytes())) {
        DataFile dataFile = new DataFile(inputStream, "test.txt", "text/plain");
        Files.deleteIfExists(Paths.get(dataFile.getDocument().getAbsolutePath()));
        dataFile.getFileSize();/*from w w w  .jav  a2  s.  c  o  m*/
    }
}

From source file:io.specto.hoverfly.junit.HoverflyRule.java

@Override
protected void before() throws Throwable {

    if (hoverflyMode == CAPTURE) {
        final Path path = Paths.get(serviceDataURI);
        Files.deleteIfExists(path);
    }//from w  w w .jav  a 2 s .  c o m

    final String binaryName = String.format(BINARY_PATH, BINARY_VERSION, getOs(), getArchitectureType())
            + (SystemUtils.IS_OS_WINDOWS ? ".exe" : "");
    LOGGER.info("Selecting the following binary based on the current operating system: " + binaryName);

    this.binaryPath = extractBinary(binaryName);

    LOGGER.info("Executing binary at " + this.binaryPath);

    final List<String> commands = new ArrayList<>();

    commands.add(this.binaryPath.toString());
    commands.add("-db");
    commands.add("memory");
    commands.add("-pp");
    commands.add(String.valueOf(proxyPort));
    commands.add("-ap");
    commands.add(String.valueOf(adminPort));

    if (hoverflyMode == CAPTURE) {
        commands.add("-capture");
    } else {
        commands.add("-import");
        commands.add(serviceDataURI);
    }

    startedProcess = new ProcessExecutor().command(commands).redirectOutput(Slf4jStream.of(LOGGER).asInfo())
            .directory(this.binaryPath.getParent().toFile()).start();

    waitForHoverflyToStart();
}

From source file:org.fao.geonet.services.mef.ImportWebMap.java

@Override
@Deprecated/* w ww.j a  v a2  s  .co m*/
public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception {
    String mapString = Util.getParam(params, "map_string");
    String mapUrl = Util.getParam(params, "map_url", "");
    String viewerUrl = Util.getParam(params, "map_viewer_url", "");
    String groupId = Util.getParam(params, "group_id", null);
    String mapAbstract = Util.getParam(params, "map_abstract", "");
    String title = Util.getParam(params, "map_title", "");
    String mapFileName = Util.getParam(params, "map_filename", "map-context.ows");
    String mapImage = Util.getParam(params, "map_image", "");
    String mapImageFilename = Util.getParam(params, "map_image_filename", "map.png");

    FilePathChecker.verify(mapFileName);

    String topic = Util.getParam(params, "topic", "");

    Map<String, Object> xslParams = new HashMap<String, Object>();
    xslParams.put("viewer_url", viewerUrl);
    xslParams.put("map_url", mapUrl);
    xslParams.put("topic", topic);
    xslParams.put("title", title);
    xslParams.put("abstract", mapAbstract);
    xslParams.put("lang", context.getLanguage());

    UserSession us = context.getUserSession();

    if (us != null) {
        xslParams.put("currentuser_name", us.getName() + " " + us.getSurname());
        // phone number is georchestra-specific
        //xslParams.put("currentuser_phone", us.getPrincipal().getPhone());
        xslParams.put("currentuser_mail", us.getEmailAddr());
        xslParams.put("currentuser_org", us.getOrganisation());
    }

    // 1. JDOMize the string
    Element wmcDoc = Xml.loadString(mapString, false);
    // 2. Apply XSL (styleSheetWmc)
    Element transformedMd = Xml.transform(wmcDoc, new File(styleSheetWmc).toPath(), xslParams);

    // 4. Inserts the metadata (does basically the same as the metadata.insert.paste service (see Insert.java)
    String uuid = UUID.randomUUID().toString();
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    SettingManager sm = context.getBean(SettingManager.class);
    DataManager dm = gc.getBean(DataManager.class);
    SchemaManager schemaMan = context.getBean(SchemaManager.class);

    String uuidAction = Util.getParam(params, Params.UUID_ACTION, Params.NOTHING);

    String date = new ISODate().toString();

    final List<String> id = new ArrayList<String>();
    final List<Element> md = new ArrayList<Element>();

    md.add(transformedMd);

    // Import record
    Importer.importRecord(uuid, MEFLib.UuidAction.parse(uuidAction), md, "iso19139", 0, sm.getSiteId(),
            sm.getSiteName(), null, context, id, date, date, groupId, MetadataType.METADATA);

    // Save the context if no context-url provided
    if (StringUtils.isEmpty(mapUrl)) {
        Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0));
        Files.createDirectories(dataDir);
        Path outFile = dataDir.resolve(mapFileName);
        Files.deleteIfExists(outFile);
        FileUtils.writeStringToFile(outFile.toFile(), Xml.getString(wmcDoc));

        // Update the MD
        Map<String, Object> onlineSrcParams = new HashMap<String, Object>();
        onlineSrcParams.put("protocol", "WWW:DOWNLOAD-OGC:OWS-C");
        onlineSrcParams.put("url",
                sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, mapFileName));
        onlineSrcParams.put("name", mapFileName);
        onlineSrcParams.put("desc", title);
        Element mdWithOLRes = Xml.transform(transformedMd,
                schemaMan.getSchemaDir("iso19139").resolve("process").resolve("onlinesrc-add.xsl"),
                onlineSrcParams);
        dm.updateMetadata(context, id.get(0), mdWithOLRes, false, true, true, context.getLanguage(), null,
                true);
    }

    if (StringUtils.isNotEmpty(mapImage) && StringUtils.isNotEmpty(mapImageFilename)) {
        Path dataDir = Lib.resource.getDir(context, Params.Access.PUBLIC, id.get(0));
        Files.createDirectories(dataDir);
        Path outFile = dataDir.resolve(mapImageFilename);
        Files.deleteIfExists(outFile);
        byte[] data = Base64.decodeBase64(mapImage);
        FileUtils.writeByteArrayToFile(outFile.toFile(), data);

        // Update the MD
        Map<String, Object> onlineSrcParams = new HashMap<String, Object>();
        onlineSrcParams.put("thumbnail_url",
                sm.getNodeURL() + String.format("api/records/%s/attachments/%s", uuid, mapFileName));
        Element mdWithOLRes = Xml.transform(transformedMd,
                schemaMan.getSchemaDir("iso19139").resolve("process").resolve("thumbnail-add.xsl"),
                onlineSrcParams);
        dm.updateMetadata(context, id.get(0), mdWithOLRes, false, true, true, context.getLanguage(), null,
                true);
    }

    dm.indexMetadata(id);

    Element result = new Element("uuid");
    result.setText(uuid);

    return result;
}

From source file:org.jboss.as.test.integration.management.http.HttpDeploymentUploadUnitTestCase.java

@Test
public void testHttpDeploymentUpload() throws Exception {
    final String basicUrl = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort()
            + "/" + MANAGEMENT_URL_PART;
    final String uploadUrl = basicUrl + "/" + UPLOAD_URL_PART;
    final Path deploymentFile = Files.createTempFile("test-http-deployment", ".sar");

    try (CloseableHttpClient client = createHttpClient()) {
        // Create the deployment
        final JavaArchive archive = ServiceActivatorDeploymentUtil
                .createServiceActivatorDeploymentArchive(DEPLOYMENT_NAME, Collections.emptyMap());
        // Create the HTTP connection to the upload URL
        final HttpPost addContentPost = new HttpPost(uploadUrl);

        // Create a deployment file
        archive.as(ZipExporter.class).exportTo(deploymentFile.toFile(), true);
        addContentPost.setEntity(createUploadEntity(deploymentFile.toFile()));

        final byte[] hash;

        // Execute the request and get the HTTP response
        try (CloseableHttpResponse response = client.execute(addContentPost)) {
            final ModelNode result = validateStatus(response);
            hash = Operations.readResult(result).asBytes();
            // JBAS-9291
            assertEquals("text/html; charset=utf-8", response.getEntity().getContentType().getValue());
        }/*  w  w w .j av a 2  s .c  o m*/

        final HttpPost addHashContentPost = new HttpPost(basicUrl);
        addHashContentPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        addHashContentPost.setEntity(createAddEntity(hash));
        try (CloseableHttpResponse response = client.execute(addHashContentPost)) {
            validateStatus(response);
        }

        // Remove the deployment
        final HttpPost removePost = new HttpPost(basicUrl);
        removePost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        removePost.setEntity(createRemoveEntity());
        try (CloseableHttpResponse response = client.execute(removePost)) {
            validateStatus(response);
        }
    } finally {
        Files.deleteIfExists(deploymentFile);
        boolean found = false;
        final ModelControllerClient client = managementClient.getControllerClient();
        // Use the management client to ensure we removed the deployment
        final ModelNode readOp = Operations.createOperation("read-children-names");
        readOp.get("child-type").set("deployment");
        ModelNode result = client.execute(readOp);
        if (Operations.isSuccessfulOutcome(result)) {
            final List<ModelNode> deployments = Operations.readResult(result).asList();
            for (ModelNode deployment : deployments) {
                if (deployment.asString().equals(DEPLOYMENT_NAME)) {
                    found = true;
                    break;
                }
            }
        }
        if (found) {
            result = client.execute(Operations.createRemoveOperation(deploymentAddress));
            if (!Operations.isSuccessfulOutcome(result)) {
                fail(String.format("Failed to remove deployment %s: %s", DEPLOYMENT_NAME,
                        Operations.getFailureDescription(result).asString()));
            }
        }
    }
}

From source file:org.jboss.as.test.manualmode.logging.PerDeployLoggingTestCase.java

private void clearLogFiles() throws IOException {
    Files.deleteIfExists(customLog);
    Files.deleteIfExists(perDeployLog);
}