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:info.pancancer.arch3.containerProvisioner.ContainerProvisionerThreads.java

/**
 * run the reaper/*from ww  w  . j av a2  s  . c o  m*/
 *
 * @param settings
 * @param ipAddress
 *            specify an ip address (otherwise cleanup only failed deployments)
 * @throws JsonIOException
 * @throws IOException
 */
private static void runReaper(HierarchicalINIConfiguration settings, String ipAddress, String vmName)
        throws IOException {
    String param = settings.getString(Constants.PROVISION_YOUXIA_REAPER);
    CommandLine parse = CommandLine.parse("dummy " + (param == null ? "" : param));
    List<String> arguments = new ArrayList<>();
    arguments.addAll(Arrays.asList(parse.getArguments()));

    arguments.add("--kill-list");
    // create a json file with the one targetted ip address
    Gson gson = new Gson();
    // we can't use the full set of database records because unlike Amazon, OpenStack reuses private ip addresses (very quickly too)
    // String[] successfulVMAddresses = db.getSuccessfulVMAddresses();
    String[] successfulVMAddresses = new String[] {};
    if (ipAddress != null) {
        successfulVMAddresses = new String[] { ipAddress, vmName };
    }
    LOG.info("Kill list contains: " + Arrays.asList(successfulVMAddresses));
    Path createTempFile = Files.createTempFile("target", "json");
    try (BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(createTempFile.toFile()), StandardCharsets.UTF_8))) {
        gson.toJson(successfulVMAddresses, bw);
    }
    arguments.add(createTempFile.toAbsolutePath().toString());

    String[] toArray = arguments.toArray(new String[arguments.size()]);
    LOG.info("Running youxia reaper with following parameters:" + Arrays.toString(toArray));
    // need to make sure reaper and deployer do not overlap

    try {
        Reaper.main(toArray);
    } catch (Exception e) {
        LOG.error("Youxia reaper threw the following exception", e);
    }
}

From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java

/**
 * Initializes the workspace by performing a checkout in a specified
 * directory.//from   w w w  . ja  v  a  2 s  .  c om
 *
 * @param connectionData
 *            holds login information an remote location of the svn
 *            repository
 * @param targetDirectory
 *            the local directory in which the checkout will be placed
 * @return true if checkout was successful, false otherwise
 * @throws SubmissionFetchingException
 *             if the fetching fails
 */
private static boolean initializeDataSource(Connection connectionData, Path targetDirectory)
        throws SubmissionFetchingException {
    // nuke previous contents, so we can be sure that we have a clean
    // state.
    try {
        FileUtils.deleteDirectory(targetDirectory.toFile());
        Files.createDirectories(targetDirectory);
    } catch (IOException e) {
        LOGGER.severe("Could not clean data source: " + targetDirectory.toAbsolutePath().toString() + " -> "
                + e.getMessage());
        return false;
    }

    if (!checkConnectionToRemoteSVN(connectionData.getLocation())) {
        return false;
    }

    // now tell svn to checkout.
    try {
        List<String> svnCommand = new LinkedList<>();
        svnCommand.add("svn");
        svnCommand.add("checkout");
        svnCommand.add(connectionData.getLocation());

        SVNResultData svnResult = runSVNCommand(connectionData, svnCommand, targetDirectory);

        if (svnResult != null) {
            LOGGER.info("Successful SVN pull from " + connectionData.getLocation());
        }

        // Any SVN return value != 0 implies an error and the fetch wasn't
        // clean. Hence we bundle the output into the exception and throw.
        if (svnResult.getReturnValue() != 0) {
            String svnOutForException = "";
            for (String message : svnResult.getSvnOutputLines()) {
                svnOutForException = svnOutForException.concat(message + "\n");
            }
            throw new SubmissionFetchingException(svnOutForException);
        }
    } catch (IOException e) {
        LOGGER.warning("unable to check out repository: " + connectionData.getLocation());
        return false;
    }

    LOGGER.config("Checked out, moving internal repository path to " + targetDirectory.toString());

    return true;
}

From source file:fr.duminy.jbackup.core.ConfigurationManagerTest.java

public static BackupConfiguration createConfiguration(String configName, Path targetDirectory) {
    final BackupConfiguration config = new BackupConfiguration();

    config.setName(configName);//w w w  . j ava2 s  .c  om
    config.setArchiveFactory(ZipArchiveFactory.INSTANCE);
    Path targetPath = (targetDirectory == null) ? Paths.get(TARGET_DIRECTORY)
            : targetDirectory.toAbsolutePath();
    config.setTargetDirectory(targetPath.toString());
    config.addSource(Paths.get("aSource").toAbsolutePath(), "aDirFilter", "aFileFilter");
    config.addSource(Paths.get("aSource2").toAbsolutePath());
    config.addSource(Paths.get("anotherSource").toAbsolutePath(), "anotherDirFilter", "anotherFileFilter");

    return config;
}

From source file:com.sludev.mssqlapplylog.MSSQLHelper.java

/**
 * Restore a Backup Log using a backup file on the file-system.
 * /*from www. j  a  v  a2s.  c om*/
 * @param logPath
 * @param sqlProcessUser Optionally, give this user file-system permissions.  So SQL Server can RESTORE.
 * @param sqlDb The name of the database to restore.
 * @param conn  Open connection
 * @throws SQLException 
 */
public static void restoreLog(final Path logPath, final String sqlProcessUser, final String sqlDb,
        final Connection conn) throws SQLException {
    LOGGER.info(String.format("\nStarting Log restore of '%s'...", logPath));

    StopWatch sw = new StopWatch();

    sw.start();

    if (StringUtils.isNoneBlank(sqlProcessUser)) {
        try {
            FSHelper.addRestorePermissions(sqlProcessUser, logPath);
        } catch (IOException ex) {
            LOGGER.debug(String.format("Error adding read permission for user '%s' to '%s'", sqlProcessUser,
                    logPath), ex);
        }
    }

    String strDevice = logPath.toAbsolutePath().toString();

    String query = String.format("RESTORE LOG %s FROM DISK='%s' WITH NORECOVERY", sqlDb, strDevice);

    Statement stmt = null;

    stmt = conn.createStatement();

    try {
        boolean sqlRes = stmt.execute(query);
    } catch (SQLException ex) {
        LOGGER.error(String.format("Error executing...\n'%s'", query), ex);

        throw ex;
    }

    sw.stop();

    LOGGER.debug(String.format("Query...\n'%s'\nTook %s", query, sw.toString()));
}

From source file:org.sakuli.datamodel.helper.TestSuiteHelper.java

/**
 * read out the 'testsuite.suite' file and create the corresponding test cases objects.
 *
 * @param properties loaded {@link TestSuiteProperties} of a {@link TestSuite}.
 * @return a map of {@link TestCase}s with her {@link TestCase#id} as key.
 * @throws FileNotFoundException if files are not reachable
 *//* w w w. j  a v  a  2s  .co  m*/
public static HashMap<String, TestCase> loadTestCases(TestSuiteProperties properties) throws IOException {
    Path testSuiteFile = properties.getTestSuiteSuiteFile();
    Path testSuiteFolder = properties.getTestSuiteFolder();

    HashMap<String, TestCase> tcMap = new HashMap<>();

    if (!Files.exists(testSuiteFile)) {
        throw new FileNotFoundException(
                "Can not find specified " + TestSuiteProperties.TEST_SUITE_SUITE_FILE_NAME + " file at \""
                        + testSuiteFolder.toString() + "\"");
    }

    String testSuiteString = prepareTestSuiteFile(testSuiteFile);
    logger.info("\n--- TestSuite initialization: read test suite information of file \""
            + testSuiteFile.toAbsolutePath().toString() + "\" ----\n" + testSuiteString
            + "\n --- End of File \"" + testSuiteFile.toAbsolutePath().toString() + "\" ---");

    //handle each line of the .suite file
    String regExLineSep = System.getProperty("line.separator") + "|\n";
    for (String line : testSuiteString.split(regExLineSep)) {
        if (!line.startsWith("//") && !(line.isEmpty())) {
            //get the start URL from suite
            String startURL = line.substring(line.lastIndexOf(' ') + 1);

            //extract tc file name name and generate new test case
            String tcFileName = line.substring(0, line.lastIndexOf(' ')); // get tc file name
            Path tcFile = Paths.get(testSuiteFolder.toAbsolutePath().toString() + File.separator
                    + tcFileName.replace("/", File.separator));
            if (Files.exists(tcFile)) {
                TestCase tc = new TestCase(TestCaseHelper.convertFolderPathToName(tcFileName),
                        TestCaseHelper.convertTestCaseFileToID(tcFileName));
                tc.setStartUrl(startURL);
                tc.setTcFile(tcFile);
                tc.setSteps(TestCaseStepHelper.readCachedStepDefinitions(tcFile));
                //set the Map with the test case id as key
                tcMap.put(tc.getId(), tc);
            } else {
                throw new FileNotFoundException("test case path \"" + tcFile.toAbsolutePath().toString()
                        + "\" doesn't exists - check your \"" + TestSuiteProperties.TEST_SUITE_SUITE_FILE_NAME
                        + "\" file");
            }
        }
    }
    return tcMap;
}

From source file:controllers.ImageBrowser.java

@Util
public static ImagePlus getImage(Path path) {
    User user = Security.getUser();

    boolean hasAccess = PermissionService.userCanAccessPath(user, path);
    if (!hasAccess)
        forbidden();/*from   w  w w.  java2s  .com*/

    Opener opener = new Opener();
    ImagePlus ip = opener.openImage(path.toAbsolutePath().toString());
    return ip;
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Utility method to covert a javascript <code>File</code> reference into a lowercased uri type path relative to the script directory root.
 *///from   w w w .j  a v a 2 s  . c  om
private static String FileToUriKey(Path rootPath, Path f) {
    assert f.toAbsolutePath().startsWith(rootPath);
    String uriKey = rootPath.toAbsolutePath().relativize(f.toAbsolutePath()).toString().toLowerCase();
    assert uriKey.endsWith(".js");
    boolean isForDirectory = uriKey.endsWith("?.js");
    uriKey = "/" + uriKey.substring(0, uriKey.length() - (isForDirectory ? 4 : 3));
    if (isForDirectory && (!uriKey.endsWith("/")))
        uriKey = uriKey + "/";
    return uriKey;
}

From source file:com.exalttech.trex.util.Util.java

/**
 * Return absolute application path//from  w w  w . ja v  a  2 s. c  o m
 *
 * @return
 */
public static String getAbsoluteApplicationPath() {
    Path currentRelativePath = Paths.get("");
    String applicationPath = currentRelativePath.toAbsolutePath().toString();
    LOG.info("Current relative path is: " + applicationPath);
    return applicationPath;
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Create an access point for a version, for a file. Don't duplicate it,
 * if it already exists.//w  w w  . j ava2 s .  c o  m
 * @param version The version for which the access point is to be created.
 * @param format The format of the access point. If null, attempt
 * to deduce a format from the filename.
 * @param targetPath The path to the existing file.
 */
public static void createFileAccessPoint(final Version version, final String format, final Path targetPath) {
    String targetPathString;
    try {
        targetPathString = targetPath.toRealPath().toString();
    } catch (IOException e) {
        LOGGER.error("createFileAccessPoint failed calling " + "toRealPath() on file: " + targetPath.toString(),
                e);
        // Try toAbsolutePath() instead.
        targetPathString = targetPath.toAbsolutePath().toString();
    }
    List<AccessPoint> aps = getAccessPointsForVersionAndType(version, AccessPoint.FILE_TYPE);
    for (AccessPoint ap : aps) {
        if (targetPathString.equals(getToolkitPath(ap))) {
            // Already exists. Check the format.
            if (format != null && !format.equals(getFormat(ap))) {
                // Format changed.
                updateFormat(ap, format);
            }
            return;
        }
    }
    // No existing access point for this file, so create a new one.
    AccessPoint ap = new AccessPoint();
    ap.setVersionId(version.getId());
    ap.setType(AccessPoint.FILE_TYPE);
    JsonObjectBuilder jobPortal = Json.createObjectBuilder();
    JsonObjectBuilder jobToolkit = Json.createObjectBuilder();
    jobToolkit.add("path", targetPathString);
    // toolkitData is now done.
    ap.setToolkitData(jobToolkit.build().toString());
    ap.setPortalData("");
    // Persist what we have ...
    AccessPointUtils.saveAccessPoint(ap);
    // ... so that now we can get access to the
    // ID of the persisted object with ap.getId().
    String baseFilename = targetPath.getFileName().toString();
    jobPortal.add("uri", downloadPrefixProperty + ap.getId() + "/" + baseFilename);
    // Now work on the format. The following is messy. It's really very
    // much for the best if the portal provides the format.
    String deducedFormat;
    if (format == null) {
        // The format was not provided to us, so try to deduce it.
        // First, try the extension.
        String extension = FilenameUtils.getExtension(baseFilename);
        deducedFormat = EXTENSION_TO_FILE_FORMAT_MAP.get(extension);
        if (deducedFormat == null) {
            // No luck with the extension, so try probing.
            try {
                String mimeType = Files.probeContentType(targetPath);
                if (mimeType == null) {
                    // Give up.
                    deducedFormat = "Unknown";
                } else {
                    deducedFormat = MIMETYPE_TO_FILE_FORMAT_MAP.get(mimeType);
                    if (deducedFormat == null) {
                        // Give up.
                        deducedFormat = "Unknown";
                    }
                }
            } catch (IOException e) {
                LOGGER.error("createFileAccessPoint failed to get " + "MIME type of file: " + targetPathString,
                        e);
                // Give up.
                deducedFormat = "Unknown";
            }
        }
    } else {
        // The format was provided to us, so use that. Much easier.
        deducedFormat = format;
    }
    jobPortal.add("format", deducedFormat);
    // portalData is now complete.
    ap.setPortalData(jobPortal.build().toString());
    AccessPointUtils.updateAccessPoint(ap);
}

From source file:org.apache.taverna.robundle.Bundles.java

protected static void safeMoveOrCopy(Path source, Path destination, boolean move) throws IOException {
    // First just try to do an atomic move with overwrite
    try {/*from   w  ww. j a  v a  2  s .  c  o  m*/
        if (move && source.getFileSystem().provider().equals(destination.getFileSystem().provider())) {
            move(source, destination, ATOMIC_MOVE, REPLACE_EXISTING);
            return;
        }
    } catch (AtomicMoveNotSupportedException ex) {
        // Do the fallback by temporary files below
    }

    destination = destination.toAbsolutePath();

    String tmpName = destination.getFileName().toString();
    Path tmpDestination = createTempFile(destination.getParent(), tmpName, ".tmp");
    Path backup = null;
    try {
        if (move) {
            /*
             * This might do a copy if filestores differ .. hence to avoid
             * an incomplete (and partially overwritten) destination, we do
             * it first to a temporary file
             */
            move(source, tmpDestination, REPLACE_EXISTING);
        } else {
            copy(source, tmpDestination, REPLACE_EXISTING);
        }

        if (exists(destination)) {
            if (isDirectory(destination))
                // ensure it is empty
                try (DirectoryStream<Path> ds = newDirectoryStream(destination)) {
                    if (ds.iterator().hasNext())
                        throw new DirectoryNotEmptyException(destination.toString());
                }
            // Keep the files for roll-back in case it goes bad
            backup = createTempFile(destination.getParent(), tmpName, ".orig");
            move(destination, backup, REPLACE_EXISTING);
        }
        // OK ; let's swap over
        try {
            // prefer ATOMIC_MOVE
            move(tmpDestination, destination, REPLACE_EXISTING, ATOMIC_MOVE);
        } catch (AtomicMoveNotSupportedException ex) {
            /*
             * possibly a network file system as src/dest should be in same
             * folder
             */
            move(tmpDestination, destination, REPLACE_EXISTING);
        } finally {
            if (!exists(destination) && backup != null)
                // Restore the backup
                move(backup, destination);
        }
        // It went well, tidy up
        if (backup != null)
            deleteIfExists(backup);
    } finally {
        deleteIfExists(tmpDestination);
    }
}