Example usage for java.nio.file Files isSameFile

List of usage examples for java.nio.file Files isSameFile

Introduction

In this page you can find the example usage for java.nio.file Files isSameFile.

Prototype

public static boolean isSameFile(Path path, Path path2) throws IOException 

Source Link

Document

Tests if two paths locate the same file.

Usage

From source file:com.facebook.buck.util.unarchive.UntarTest.java

/**
 * Assert that a symlink exists inside of the temp directory with given contents and that links to
 * the right file//w  ww . j av  a 2 s  .c o m
 */
private void assertOutputSymlinkExists(Path symlinkPath, Path expectedLinkedToPath, String expectedContents)
        throws IOException {
    Path fullPath = tmpFolder.getRoot().resolve(symlinkPath);
    if (Platform.detect() != Platform.WINDOWS) {
        Assert.assertTrue(String.format("Expected %s to be a symlink", fullPath),
                Files.isSymbolicLink(fullPath));
        Path linkedToPath = Files.readSymbolicLink(fullPath);
        Assert.assertEquals(String.format("Expected symlink at %s to point to %s, not %s", symlinkPath,
                expectedLinkedToPath, linkedToPath), expectedLinkedToPath, linkedToPath);
    }

    Path realExpectedLinkedToPath = filesystem.getRootPath()
            .resolve(symlinkPath.getParent().resolve(expectedLinkedToPath).normalize());
    Assert.assertTrue(
            String.format("Expected link %s to be the same file as %s", fullPath, realExpectedLinkedToPath),
            Files.isSameFile(fullPath, realExpectedLinkedToPath));

    String contents = Joiner.on('\n').join(Files.readAllLines(fullPath));
    Assert.assertEquals(expectedContents, contents);
}

From source file:org.wildfly.swarm.proc.Monitor.java

private static boolean isSameFile(Path path1, Path path2) {
    try {// w w  w . ja  v a  2 s. com
        return Files.isSameFile(path1, path2);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void getErrorCause() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    Path portIn1 = DataBundles.getPort(inputs, "in1");
    Path cause1 = DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
    Path portIn2 = DataBundles.getPort(inputs, "in2");
    Path cause2 = DataBundles.setError(portIn2, "Something else did not work", "Shorter trace");

    Path outputs = DataBundles.getOutputs(dataBundle);
    Path portOut1 = DataBundles.getPort(outputs, "out1");
    DataBundles.setError(portOut1, "Errors in input", "", cause1, cause2);

    ErrorDocument error = DataBundles.getError(portOut1);
    assertEquals("Errors in input", error.getMessage());
    assertEquals("", error.getTrace());
    assertEquals(2, error.getCausedBy().size());

    assertTrue(Files.isSameFile(cause1, error.getCausedBy().get(0)));
    assertTrue(Files.isSameFile(cause2, error.getCausedBy().get(1)));
}

From source file:br.univali.ps.ui.telas.TelaPrincipal.java

public AbaCodigoFonte obterAbaArquivo(File arquivo) {
    for (Aba aba : getPainelTabulado().getAbas(AbaCodigoFonte.class)) {
        AbaCodigoFonte abaCodigoFonte = (AbaCodigoFonte) aba;
        PortugolDocumento documento = abaCodigoFonte.getPortugolDocumento();
        if (documento.getFile() != null && arquivo.exists()) {
            try {
                Path caminhoArquivoAba = documento.getFile().toPath();
                Path caminhoArquivoAbrir = arquivo.toPath();

                if (Files.isSameFile(caminhoArquivoAba, caminhoArquivoAbrir)) {
                    return abaCodigoFonte;
                }/*from  w ww  .j av a 2s.  com*/
            } catch (IOException excecao) {
                LOGGER.log(Level.SEVERE,
                        String.format("Erro ao verificar se o arquivo '%s' j estava aberto em alguma aba",
                                arquivo.getAbsolutePath()),
                        excecao);
            }
        }
    }

    return null;
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java

private OwncloudLocalResourceExtension createOwncloudResourceOf(Path path) {
    Path rootPath = getRootLocationOfAuthenticatedUser();
    Path relativePath = rootPath.toAbsolutePath().relativize(path.toAbsolutePath());
    URI href = URI.create(UriComponentsBuilder.fromPath("/").path(relativePath.toString()).toUriString());
    String name = path.getFileName().toString();
    MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
    if (Files.isDirectory(path)) {
        href = URI.create(UriComponentsBuilder.fromUri(href).path("/").toUriString());
        mediaType = OwncloudUtils.getDirectoryMediaType();
    } else {//  w ww  .  ja v  a 2s  . com
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentType = fileNameMap.getContentTypeFor(path.getFileName().toString());
        if (StringUtils.isNotBlank(contentType)) {
            mediaType = MediaType.valueOf(contentType);
        }
    }
    try {
        LocalDateTime lastModifiedAt = LocalDateTime.ofInstant(Files.getLastModifiedTime(path).toInstant(),
                ZoneId.systemDefault());
        Optional<String> checksum = checksumService.getChecksum(path);
        if (Files.isSameFile(rootPath, path)) {
            name = "/";
            checksum = Optional.empty();
        }
        OwncloudLocalResourceExtension resource = OwncloudLocalResourceImpl.builder().href(href).name(name)
                .eTag(checksum.orElse(null)).mediaType(mediaType).lastModifiedAt(lastModifiedAt).build();
        if (Files.isDirectory(path)) {
            return resource;
        }

        return OwncloudLocalFileResourceImpl.fileBuilder().owncloudResource(resource)
                .contentLength(Files.size(path)).build();
    } catch (NoSuchFileException e) {
        throw new OwncloudResourceNotFoundException(href, getUsername());
    } catch (IOException e) {
        val logMessage = String.format("Cannot create OwncloudResource from Path %s", path);
        log.error(logMessage, e);
        throw new OwncloudLocalResourceException(logMessage, e);
    }
}

From source file:org.zaproxy.zap.extension.api.CoreAPI.java

@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {

    Session session = Model.getSingleton().getSession();

    if (ACTION_SHUTDOWN.equals(name)) {
        Thread thread = new Thread() {
            @Override/*w  ww  . ja  v a2 s .  c  o m*/
            public void run() {
                try {
                    // Give the API a chance to return
                    sleep(1000);
                } catch (InterruptedException e) {
                    // Ignore
                }
                Control.getSingleton().shutdown(
                        Model.getSingleton().getOptionsParam().getDatabaseParam().isCompactDatabase());
                logger.info(Constant.PROGRAM_TITLE + " terminated.");
                System.exit(0);
            }
        };
        thread.start();

    } else if (ACTION_SAVE_SESSION.equalsIgnoreCase(name)) { // Ignore case for backwards compatibility
        Path sessionPath = SessionUtils.getSessionPath(params.getString(PARAM_SESSION));
        String filename = sessionPath.toAbsolutePath().toString();

        final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);

        boolean sameSession = false;
        if (!session.isNewState()) {
            try {
                sameSession = Files.isSameFile(Paths.get(session.getFileName()), sessionPath);
            } catch (IOException e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }

        if (Files.exists(sessionPath) && (!overwrite || sameSession)) {
            throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
        }
        this.savingSession = true;
        try {
            Control.getSingleton().saveSession(filename, this);
        } catch (Exception e) {
            this.savingSession = false;
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
        // Wait for notification that its worked ok
        try {
            while (this.savingSession) {
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            // Probably not an error
            logger.debug(e.getMessage(), e);
        }
        logger.debug("Can now return after saving session");

    } else if (ACTION_SNAPSHOT_SESSION.equalsIgnoreCase(name)) { // Ignore case for backwards compatibility
        if (session.isNewState()) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST);
        }
        String fileName = session.getFileName();

        if (fileName.endsWith(".session")) {
            fileName = fileName.substring(0, fileName.length() - 8);
        }
        fileName += "-" + dateFormat.format(new Date()) + ".session";

        this.savingSession = true;
        try {
            Control.getSingleton().snapshotSession(fileName, this);
        } catch (Exception e) {
            this.savingSession = false;
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
        // Wait for notification that its worked ok
        try {
            while (this.savingSession) {
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            // Probably not an error
            logger.debug(e.getMessage(), e);
        }
        logger.debug("Can now return after saving session");

    } else if (ACTION_LOAD_SESSION.equalsIgnoreCase(name)) { // Ignore case for backwards compatibility
        Path sessionPath = SessionUtils.getSessionPath(params.getString(PARAM_SESSION));
        String filename = sessionPath.toAbsolutePath().toString();

        if (!Files.exists(sessionPath)) {
            throw new ApiException(ApiException.Type.DOES_NOT_EXIST, filename);
        }
        try {
            Control.getSingleton().runCommandLineOpenSession(filename);
        } catch (Exception e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }

    } else if (ACTION_NEW_SESSION.equalsIgnoreCase(name)) { // Ignore case for backwards compatibility
        String sessionName = null;
        try {
            sessionName = params.getString(PARAM_SESSION);
        } catch (Exception e1) {
            // Ignore
        }
        if (sessionName == null || sessionName.length() == 0) {
            // Create a new 'unnamed' session
            Control.getSingleton().discardSession();
            try {
                Control.getSingleton().createAndOpenUntitledDb();
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
            Control.getSingleton().newSession();
        } else {
            Path sessionPath = SessionUtils.getSessionPath(sessionName);
            String filename = sessionPath.toAbsolutePath().toString();

            final boolean overwrite = getParam(params, PARAM_OVERWRITE_SESSION, false);

            if (Files.exists(sessionPath) && !overwrite) {
                throw new ApiException(ApiException.Type.ALREADY_EXISTS, filename);
            }
            try {
                Control.getSingleton().runCommandLineNewSession(filename);
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
    } else if (ACTION_CLEAR_EXCLUDED_FROM_PROXY.equals(name)) {
        try {
            session.setExcludeFromProxyRegexs(new ArrayList<String>());
        } catch (DatabaseException e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
    } else if (ACTION_EXCLUDE_FROM_PROXY.equals(name)) {
        String regex = params.getString(PARAM_REGEX);
        try {
            session.addExcludeFromProxyRegex(regex);
        } catch (DatabaseException e) {
            logger.error(e.getMessage(), e);
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        } catch (PatternSyntaxException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REGEX);
        }
    } else if (ACTION_SET_HOME_DIRECTORY.equals(name)) {
        File f = new File(params.getString(PARAM_DIR));
        if (f.exists() && f.isDirectory()) {
            Model.getSingleton().getOptionsParam().setUserDirectory(f);
        } else {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_DIR);
        }
    } else if (ACTION_GENERATE_ROOT_CA.equals(name)) {
        ExtensionDynSSL extDyn = (ExtensionDynSSL) Control.getSingleton().getExtensionLoader()
                .getExtension(ExtensionDynSSL.EXTENSION_ID);
        if (extDyn != null) {
            try {
                extDyn.createNewRootCa();
            } catch (Exception e) {
                throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
            }
        }
    } else if (ACTION_SEND_REQUEST.equals(name)) {
        HttpMessage request;
        try {
            request = createRequest(params.getString(PARAM_REQUEST));
        } catch (HttpMalformedHeaderException e) {
            throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_REQUEST, e);
        }
        boolean followRedirects = getParam(params, PARAM_FOLLOW_REDIRECTS, false);
        final ApiResponseList resultList = new ApiResponseList(name);
        try {
            sendRequest(request, followRedirects, new Processor<HttpMessage>() {

                @Override
                public void process(HttpMessage msg) {
                    int id = msg.getHistoryRef() != null ? msg.getHistoryRef().getHistoryId() : -1;
                    resultList.addItem(ApiResponseConversionUtils.httpMessageToSet(id, msg));
                }
            });

            return resultList;
        } catch (Exception e) {
            throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
        }
    } else if (ACTION_DELETE_ALL_ALERTS.equals(name)) {
        final ExtensionAlert extAlert = (ExtensionAlert) Control.getSingleton().getExtensionLoader()
                .getExtension(ExtensionAlert.NAME);
        if (extAlert != null) {
            extAlert.deleteAllAlerts();
        } else {
            try {
                Model.getSingleton().getDb().getTableAlert().deleteAllAlerts();
            } catch (DatabaseException e) {
                logger.error(e.getMessage(), e);
            }

            SiteNode rootNode = (SiteNode) Model.getSingleton().getSession().getSiteTree().getRoot();
            rootNode.deleteAllAlerts();

            removeHistoryReferenceAlerts(rootNode);
        }
    } else if (ACTION_COLLECT_GARBAGE.equals(name)) {
        System.gc();
        return ApiResponseElement.OK;

    } else if (ACTION_CLEAR_STATS.equals(name)) {
        Stats.clear(this.getParam(params, PARAM_KEY_PREFIX, ""));
        return ApiResponseElement.OK;

    } else {
        throw new ApiException(ApiException.Type.BAD_ACTION);
    }
    return ApiResponseElement.OK;
}

From source file:business.services.FileService.java

public HttpEntity<InputStreamResource> downloadAccessLog(String filename,
        boolean writeContentDispositionHeader) {
    try {/*from ww w. j av  a2s  .c o  m*/
        FileSystem fileSystem = FileSystems.getDefault();
        Path path = fileSystem.getPath(accessLogsPath).normalize();
        filename = filename.replace(fileSystem.getSeparator(), "_");
        filename = URLEncoder.encode(filename, "utf-8");

        Path f = fileSystem.getPath(accessLogsPath, filename).normalize();
        // filter path names that point to places outside the logs path.
        // E.g., to prevent that in cases where clients use '../' in the filename
        // arbitrary locations are reachable.
        if (!Files.isSameFile(path, f.getParent())) {
            // Path f is not in the upload path. Maybe 'name' contains '..'?
            log.error("Invalid filename: " + filename);
            throw new FileDownloadError("Invalid file name");
        }
        if (!Files.isReadable(f)) {
            log.error("File does not exist: " + filename);
            throw new FileDownloadError("File does not exist");
        }

        InputStream input = new FileInputStream(f.toFile());
        InputStreamResource resource = new InputStreamResource(input);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        if (writeContentDispositionHeader) {
            headers.set("Content-Disposition", "attachment; filename=" + filename.replace(" ", "_"));
        }
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        log.error(e);
        throw new FileDownloadError();
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java

private boolean isRootDirectory(Path location) {
    if (!Files.isDirectory(location)) {
        return false;
    }/*  w w w. j  a v  a  2s.co  m*/
    Path rootLocation = getRootLocationOfAuthenticatedUser();
    try {
        return Files.isSameFile(location, rootLocation);
    } catch (IOException e) {
        val logMessage = String.format("Cannot determine the equality of path %s to the base Location %s",
                location, rootLocation);
        log.error(logMessage, e);
        throw new OwncloudLocalResourceException(logMessage, e);
    }
}

From source file:at.tfr.securefs.ui.CopyFilesServiceBean.java

private Path validateToPath(String toPathName, ProcessFilesData pfd) throws IOException {
    Path to = Paths.get(toPathName);
    if (Files.exists(to, LinkOption.NOFOLLOW_LINKS)) {
        if (Files.isSameFile(to, Paths.get(pfd.getFromRootPath()))) {
            throw new IOException("Path " + to + " may not be same as FromPath: " + pfd.getFromRootPath());
        }//from w  ww. ja  v  a 2s  . c  o  m
        if (!Files.isDirectory(to, LinkOption.NOFOLLOW_LINKS)) {
            throw new IOException("Path " + to + " is no directory");
        }
        if (!Files.isWritable(to)) {
            throw new IOException("Path " + to + " is not writable");
        }
        if (!Files.isExecutable(to)) {
            throw new IOException("Path " + to + " is not executable");
        }
        if (!pfd.isAllowOverwriteExisting()) {
            if (Files.newDirectoryStream(to).iterator().hasNext()) {
                throw new IOException("Path " + to + " is not empty, delete content copy.");
            }
        }
    }
    return to;
}

From source file:org.apache.storm.daemon.supervisor.AdvancedFSOps.java

/**
 * Create a symbolic link pointing at target
 * @param link the link to create//from  ww  w  .  ja  v a  2  s. c  om
 * @param target where it should point to
 * @throws IOException on any error.
 */
@Override
public void createSymlink(File link, File target) throws IOException {
    if (_symlinksDisabled) {
        throw new IOException("Symlinks have been disabled, this should not be called");
    }
    Path plink = link.toPath().toAbsolutePath();
    Path ptarget = target.toPath().toAbsolutePath();
    LOG.debug("Creating symlink [{}] to [{}]", plink, ptarget);
    if (Files.exists(plink)) {
        if (Files.isSameFile(plink, ptarget)) {
            //It already points where we want it to
            return;
        }
        FileUtils.forceDelete(link);
    }
    Files.createSymbolicLink(plink, ptarget);
}