001/*
002 * The contents of this file are subject to the terms of the Common Development and
003 * Distribution License (the License). You may not use this file except in compliance with the
004 * License.
005 *
006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
007 * specific language governing permission and limitations under the License.
008 *
009 * When distributing Covered Software, include this CDDL Header Notice in each file and include
010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
011 * Header, with the fields enclosed by brackets [] replaced by your own identifying
012 * information: "Portions copyright [year] [name of copyright owner]".
013 *
014 * Copyright 2018 Wren Security. All rights reserved.
015 */
016package org.forgerock.util.test;
017
018import java.io.File;
019import java.nio.file.Path;
020import java.nio.file.Paths;
021
022/**
023 * Utility methods for retrieving test resource files from the Maven project path.
024 */
025public final class MavenResourceUtil {
026    /**
027     * Private constructor for singleton static class.
028     */
029    private MavenResourceUtil() { }
030
031    /**
032     * Get a file representation of the specified relative file resource path.
033     *
034     * @param relativePath
035     *   The path to the file resource, relative to the root of the current project being compiled
036     *   (i.e. relative to the {@code basedir} system property.
037     *
038     * @return
039     *   An absolute {@code File} reference that can be used to access the resource, regardless of
040     *   the current working directory.
041     */
042    public static File getFileForPath(final String relativePath) {
043        return getPath(relativePath).toFile();
044    }
045
046    /**
047     * Get the appropriate path to the file having the specified relative path.
048     *
049     * @param relativePath
050     *   The path to the file resource, relative to the root of the current project being compiled
051     *   (i.e. relative to the {@code basedir} system property.
052     *
053     * @return
054     *   An absolute {@code Path} that can be used to reference the resource, regardless of the
055     *   current working directory.
056     */
057    public static Path getPath(final String relativePath) {
058        String baseDir = System.getProperty("basedir");
059
060        if (baseDir == null) {
061            // Fall back to current working directory; to support tests run directly
062            // (e.g. through an IDE)
063            baseDir = System.getProperty("user.dir");
064        }
065
066        return Paths.get(baseDir, relativePath).toAbsolutePath();
067    }
068}