Example usage for java.nio.file Path toAbsolutePath

List of usage examples for java.nio.file Path toAbsolutePath

Introduction

In this page you can find the example usage for java.nio.file Path toAbsolutePath.

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:org.tinymediamanager.core.tvshow.TvShowRenamer.java

/**
 * renames the TvSHow root folder and updates all mediaFiles
 * /*from w  w w  . j a  v  a2  s  . c o  m*/
 * @param show
 *          the show
 */
public static void renameTvShowRoot(TvShow show) {
    LOGGER.debug("TV show year: " + show.getYear());
    LOGGER.debug("TV show path: " + show.getPath());
    String newPathname = generateTvShowDir(SETTINGS.getRenamerTvShowFoldername(), show);
    String oldPathname = show.getPath();

    if (!newPathname.isEmpty()) {
        // newPathname = show.getDataSource() + File.separator + newPathname;
        Path srcDir = Paths.get(oldPathname);
        Path destDir = Paths.get(newPathname);
        // move directory if needed
        // if (!srcDir.equals(destDir)) {
        if (!srcDir.toAbsolutePath().toString().equals(destDir.toAbsolutePath().toString())) {
            try {
                // FileUtils.moveDirectory(srcDir, destDir);
                // create parent if needed
                if (!Files.exists(destDir.getParent())) {
                    Files.createDirectory(destDir.getParent());
                }
                boolean ok = Utils.moveDirectorySafe(srcDir, destDir);
                if (ok) {
                    show.updateMediaFilePath(srcDir, destDir); // TvShow MFs
                    show.setPath(newPathname);
                    for (TvShowEpisode episode : new ArrayList<>(show.getEpisodes())) {
                        episode.replacePathForRenamedFolder(srcDir, destDir);
                        episode.updateMediaFilePath(srcDir, destDir);
                    }
                    show.saveToDb();
                }
            } catch (Exception e) {
                LOGGER.error("error moving folder: ", e.getMessage());
                MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, srcDir,
                        "message.renamer.failedrename", new String[] { ":", e.getLocalizedMessage() }));
            }
        }
    }
}

From source file:org.apache.openaz.xacml.rest.XACMLPdpLoader.java

/**
 * Iterates the policies defined in the props object to ensure they are loaded locally. Policies are
 * searched for in the following order: - see if the current properties has a "&lt;PolicyID&gt;.file"
 * entry and that file exists in the local directory - if not, see if the file exists in the local
 * directory; if so create a ".file" property for it. - if not, get the "&lt;PolicyID&gt;.url" property
 * and try to GET the policy from that location (and set the ".file" property) If the ".file" property is
 * created, then true is returned to tell the caller that the props object changed.
 *
 * @param props//  w  ww  .  ja  v  a  2 s .  c om
 * @return true/false if anything was changed in the props object
 * @throws PAPException
 */
public static synchronized boolean cachePolicies(Properties props) throws PAPException {
    boolean changed = false;
    String[] lists = new String[2];
    lists[0] = props.getProperty(XACMLProperties.PROP_ROOTPOLICIES);
    lists[1] = props.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES);
    for (String list : lists) {
        //
        // Check for a null or empty parameter
        //
        if (list == null || list.length() == 0) {
            continue;
        }
        Iterable<String> policies = Splitter.on(',').trimResults().omitEmptyStrings().split(list);
        for (String policy : policies) {
            boolean policyExists = false;

            // First look for ".file" property and verify the file exists
            String propLocation = props.getProperty(policy + StdPolicyFinderFactory.PROP_FILE);
            if (propLocation != null) {
                //
                // Does it exist?
                //
                policyExists = Files.exists(Paths.get(propLocation));
                if (!policyExists) {
                    logger.warn("Policy file " + policy + " expected at " + propLocation + " does NOT exist.");
                }
            }

            // If ".file" property does not exist, try looking for the local file anyway
            // (it might exist without having a ".file" property set for it)
            if (!policyExists) {
                //
                // Now construct the output file name
                //
                Path outFile = Paths.get(getPDPConfig().toAbsolutePath().toString(), policy);
                //
                // Double check to see if we pulled it at some point
                //
                policyExists = Files.exists(outFile);
                if (policyExists) {
                    //
                    // Set the property so the PDP engine doesn't have
                    // to pull it from the URL but rather the FILE.
                    //
                    logger.info("Policy does exist: " + outFile.toAbsolutePath().toString());
                    props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE,
                            outFile.toAbsolutePath().toString());
                    //
                    // Indicate that there were changes made to the properties
                    //
                    changed = true;
                } else {

                    // File does not exist locally, so we need to get it from the location given in the
                    // ".url" property (which MUST exist)

                    //
                    // There better be a URL to retrieve it
                    //
                    propLocation = props.getProperty(policy + StdPolicyFinderFactory.PROP_URL);
                    if (propLocation != null) {
                        //
                        // Get it
                        //
                        URL url = null;
                        try {
                            //
                            // Create the URL
                            //
                            url = new URL(propLocation);
                            logger.info("Pulling " + url.toString());
                            //
                            // Open the connection
                            //
                            URLConnection urlConnection = url.openConnection();
                            urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID,
                                    XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID));
                            //
                            // Copy it to disk
                            //
                            try (InputStream is = urlConnection.getInputStream();
                                    OutputStream os = new FileOutputStream(outFile.toFile())) {
                                IOUtils.copy(is, os);
                            }
                            //
                            // Now save it in the properties as a .file
                            //
                            logger.info("Pulled policy: " + outFile.toAbsolutePath().toString());
                            props.setProperty(policy + StdPolicyFinderFactory.PROP_FILE,
                                    outFile.toAbsolutePath().toString());
                            //
                            // Indicate that there were changes made to the properties
                            //
                            changed = true;
                        } catch (Exception e) {
                            if (e instanceof MalformedURLException) {
                                logger.error("Policy '" + policy + "' had bad URL in new configuration, URL='"
                                        + propLocation + "'");
                            } else {
                                logger.error("Error while retrieving policy " + policy + " from URL "
                                        + url.toString() + ", e=" + e);
                            }
                        }
                    } else {
                        logger.error("Policy " + policy + " does NOT exist and does NOT have a URL");
                    }
                }
            }
        }
    }
    return changed;
}

From source file:org.apache.storm.daemon.logviewer.utils.LogFileDownloader.java

/**
 * Checks authorization for the log file and download.
 *
 * @param fileName file to download//from w  ww .j a v a 2 s  . c  o m
 * @param user username
 * @param isDaemon true if the file is a daemon log, false if the file is an worker log
 * @return a Response which lets browsers download that file.
 */
public Response downloadFile(String fileName, String user, boolean isDaemon) throws IOException {
    Path rootDir = isDaemon ? daemonLogRoot : logRoot;
    Path rawFile = rootDir.resolve(fileName);
    Path file = rawFile.toAbsolutePath().normalize();
    if (!file.startsWith(rootDir) || !rawFile.normalize().toString().equals(rawFile.toString())) {
        //Ensure filename doesn't contain ../ parts 
        return LogviewerResponseBuilder.buildResponsePageNotFound();
    }
    if (isDaemon && Paths.get(fileName).getNameCount() != 1) {
        //Prevent daemon log reads from pathing into worker logs
        return LogviewerResponseBuilder.buildResponsePageNotFound();
    }

    if (file.toFile().exists()) {
        if (isDaemon || resourceAuthorizer.isUserAllowedToAccessFile(user, fileName)) {
            fileDownloadSizeDistMb.update(Math.round((double) file.toFile().length() / FileUtils.ONE_MB));
            return LogviewerResponseBuilder.buildDownloadFile(file.toFile(), numFileDownloadExceptions);
        } else {
            return LogviewerResponseBuilder.buildResponseUnauthorizedUser(user);
        }
    } else {
        return LogviewerResponseBuilder.buildResponsePageNotFound();
    }
}

From source file:misc.FileHandler.java

/**
 * Returns a temporary file path that is on the same file store as the given
 * file. The temporary file is created without content, if the given file's
 * file store is identical to the system's default temporary directory file
 * store.//from www. j a v a  2s .  c o m
 * 
 * @param target
 *            the file which determines the file store.
 * @return the path of the temporary file or <code>null</code>, if an error
 *         occurred.
 */
public static Path getTempFile(Path target) {
    Path tempFile = null;
    boolean success = false;

    target = target.normalize();

    try {
        Path targetDirectory = target.toAbsolutePath().getParent();
        tempFile = Files.createTempFile(target.getFileName().toString(), TEMP_FILE_SUFFIX);

        if (!Files.getFileStore(tempFile).equals(Files.getFileStore(targetDirectory))) {
            // the temporary file should be in the target directory.
            Files.delete(tempFile);
            tempFile = Paths.get(targetDirectory.toString(), tempFile.getFileName().toString());
            success = true;
        } else {
            success = true;
        }
    } catch (IOException e) {
        Logger.logError(e);
    } finally {
        if (!success && (tempFile != null)) {
            try {
                Files.deleteIfExists(tempFile);
            } catch (IOException innerE) {
                Logger.logError(innerE);
            }
        }
    }

    return success ? tempFile : null;
}

From source file:org.apache.openaz.xacml.admin.XacmlAdminUI.java

/**
 * Initializes a user's git repository.// w ww .  j a  v  a 2s.c om
 * 
 * 
 * @param workspacePath
 * @param userId
 * @param email
 * @return
 * @throws IOException
 * @throws InvalidRemoteException
 * @throws TransportException
 * @throws GitAPIException
 */
private static Path initializeUserRepository(Path workspacePath, String userId, URI email)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    Path gitPath = null;
    //
    // Initialize the User's Git repository
    //
    if (Files.notExists(workspacePath)) {
        logger.info("Creating user workspace: " + workspacePath.toAbsolutePath().toString());
        //
        // Create our user's directory
        //
        Files.createDirectory(workspacePath);
    }
    gitPath = Paths.get(workspacePath.toString(), XacmlAdminUI.repositoryPath.getFileName().toString());
    if (Files.notExists(gitPath)) {
        //
        // It doesn't exist yet, so Clone it and check it out
        //
        logger.info("Cloning user git directory: " + gitPath.toAbsolutePath().toString());
        Git.cloneRepository().setURI(XacmlAdminUI.repositoryPath.toUri().toString())
                .setDirectory(gitPath.toFile()).setNoCheckout(false).call();
        //
        // Set userid
        //
        Git git = Git.open(gitPath.toFile());
        StoredConfig config = git.getRepository().getConfig();
        config.setString("user", null, "name", userId);
        if (email != null && email.getPath() != null) {
            config.setString("user", null, "email", email.toString());
        }
        config.save();
    }
    return gitPath;
}

From source file:org.ballerinalang.stdlib.internal.file.GetExtension.java

/**
 * {@inheritDoc}// www . ja va  2  s. c  om
 */
@Override
public void execute(Context context) {
    BMap<String, BValue> pathStruct = (BMap<String, BValue>) context.getRefArgument(0);
    Path path = (Path) pathStruct.getNativeData(Constants.PATH_DEFINITION_NAME);
    String extension = FilenameUtils.getExtension(path.toAbsolutePath().toString());
    context.setReturnValues(new BString(extension == null ? "" : extension));
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

private static File createOrFail(Path parent, String subdirectory, Set<PosixFilePermission> permissions)
        throws IOException, WfmProcessingException {
    Path child = parent.resolve(subdirectory);
    if (!Files.exists(child)) {
        child = Files.createDirectories(child, PosixFilePermissions.asFileAttribute(permissions));
    }//from  w  w w .  java2 s  .c  om

    if (!Files.exists(child) || !Files.isDirectory(child)) {
        throw new WfmProcessingException(String
                .format("Failed to create the path '%s'. It does not exist or it is not a directory.", child));
    }

    return child.toAbsolutePath().toFile();
}

From source file:com.olacabs.fabric.compute.builder.impl.HttpJarDownloader.java

public HttpJarDownloader() throws Exception {
    FileAttribute<Set<PosixFilePermission>> perms = PosixFilePermissions
            .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x"));
    Path createdPath = Files.createTempDirectory(null, perms);
    this.tmpDirectory = createdPath.toAbsolutePath().toString();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(20);/*from  w w w  .  j  a va  2s .  c  om*/

    httpClient = HttpClients.custom().setConnectionManager(cm).build();
}

From source file:io.spikex.core.integration.MainTest.java

@Test
public void testClustered() throws InterruptedException, IOException {
    Path homePath = Paths.get("build/resources/test/node2");
    System.setProperty("spikex.home", homePath.toAbsolutePath().toString());
    new Main().start(new String[0]);
}

From source file:org.apache.beam.sdk.io.LocalResourceId.java

private LocalResourceId(Path path, boolean isDirectory) {
    this.pathString = path.toAbsolutePath().normalize().toString() + (isDirectory ? File.separatorChar : "");
    this.isDirectory = isDirectory;
}