org.conqat.lib.commons.resources.Resource Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-lib-commons Show documentation
Show all versions of teamscale-lib-commons Show documentation
Provides common utility functions
/*
* Copyright (c) CQSE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.conqat.lib.commons.resources;
import static org.conqat.lib.commons.filesystem.FileSystemUtils.ensureParentDirectoryExists;
import static org.conqat.lib.commons.filesystem.FileSystemUtils.readStreamUTF8;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.compress.utils.SeekableInMemoryByteChannel;
import org.conqat.lib.commons.filesystem.FileSystemUtils;
import org.conqat.lib.commons.string.StringUtils;
/**
* Represents a java resource which is identified by a {@link #contextClass} and a {@link #path}.
* The resource will be loaded using the same class loader that was used to load the
* {@link #contextClass}. The path consists of the class' package name plus the {@link #path}. A
* resource object is always guaranteed to exist meaning that instantiation of a non-existent
* resource will fail.
*/
public class Resource implements Comparable {
/** Character that separates a resource' basename from the extension. */
private static final char RESOURCE_EXTENSION_SEPARATOR = '.';
/**
* The context class. The resource is expected below the class's package name and will be loaded
* using the same class loader that was used to load the class.
*/
private final Class contextClass;
/**
* A path including the resource name and extension relative to the package name of the
* #contextClass. The path is separated by forward slashes on all operating systems. The path must
* not navigate up with "..".
*/
private final String path;
/** The resolved url of the resource. */
private final URL url;
/**
* Creates an instance of a resource. If the resource does not exist and AssertionError is thrown.
* Check with {@link #exists(Class, String)} before creating an instance in case it might be
* missing.
*/
public static Resource of(Class contextClass, String path) {
return asOptional(contextClass, path)
.orElseThrow(() -> new AssertionError(getAbsolutePath(contextClass, path) + " does not exist!"));
}
/**
* Creates an instance of a resource using the given url.
*/
public static Resource of(Class contextClass, String path, URL resourceUrl) {
return new Resource(contextClass, path, resourceUrl);
}
/**
* Creates an instance of a resource. Returns empty if the resource does not exist.
*/
public static Optional asOptional(Class contextClass, String path) {
URL resourceUrl = contextClass.getResource(path);
if (resourceUrl == null) {
return Optional.empty();
}
return Optional.of(new Resource(contextClass, path, resourceUrl));
}
/**
* Returns the resource's absolute path including the {@link #contextClass}' package name.
*/
public static String getAbsolutePath(Class contextClass, String path) {
if (path.startsWith(String.valueOf(FileSystemUtils.UNIX_SEPARATOR))) {
// Strip leading slash
return path.substring(1);
}
return ResourceUtils.getPackageResourcePath(contextClass) + FileSystemUtils.UNIX_SEPARATOR + path;
}
/**
* Returns true is the resource exists.
*/
public static boolean exists(Class contextClass, String path) {
return contextClass.getResource(path) != null;
}
private Resource(Class contextClass, String path, URL url) {
this.path = path;
this.contextClass = contextClass;
this.url = url;
}
/** Returns the name of the resource including the extension. */
public String getName() {
return FileSystemUtils.getLastPathSegment(getPath());
}
/** Returns the resource's base name without extension. */
public String getBaseName() {
return StringUtils.removeLastPart(getName(), RESOURCE_EXTENSION_SEPARATOR);
}
/** Returns the resource's extension. */
public String getExtension() {
return StringUtils.getLastPart(getName(), RESOURCE_EXTENSION_SEPARATOR);
}
/**
* Returns true is the resource's extension matches one of the given extensions. In contrast to
* {@link #getExtension()} this method supports also extensions that contain dots.
*/
public boolean hasExtension(String... extensions) {
return Arrays.stream(extensions)
.anyMatch(extension -> getName().endsWith(RESOURCE_EXTENSION_SEPARATOR + extension));
}
/** Returns the resource's context class. */
public Class getContextClass() {
return contextClass;
}
/**
* Returns the resource's path relative to the {@link #contextClass} including the resource's name.
*/
public String getPath() {
return path;
}
/** Returns the resource's url. */
public URL getUrl() {
return url;
}
/**
* Returns the resource's parent path. This is the {@link #getPath()} without the resource's name.
*/
public String getParentPath() {
return StringUtils.stripSuffix(getPath(), getName());
}
/**
* Returns the resource's absolute path including the {@link #contextClass}' package name.
*/
public String getAbsolutePath() {
return getAbsolutePath(contextClass, path);
}
/**
* Returns only a single path segment of the resource's path. If the index is negative the path
* segments are counted from the end of the path. E.g. for "base/sub/name.txt" 0=base, -1=name.txt,
* -2=1=sub.
*/
public String getPathSegmentAt(int index) {
String[] pathSegments = FileSystemUtils.getPathSegments(path);
if (index < 0) {
return pathSegments[pathSegments.length + index];
}
return pathSegments[index];
}
/**
* Get resource as stream. The caller has to take care for closing the stream.
*/
public InputStream getAsStream() {
try {
return url.openStream();
} catch (IOException e) {
throw ResourceException.newLoadFailed(this, e);
}
}
/**
* Returns the resource as a raw byte array.
*/
public byte[] getAsByteArray() {
try (InputStream inputStream = getAsStream()) {
return FileSystemUtils.readStreamBinary(inputStream);
} catch (IOException e) {
throw ResourceException.newLoadFailed(this, e);
}
}
/**
* @return The resource as readable {@link SeekableByteChannel}. Whether
* {@link SeekableByteChannel#write(ByteBuffer) writing} is supported is undefined, so it
* should not be used.
*/
public SeekableByteChannel getAsChannel() {
try {
return Files.newByteChannel(Paths.get(url.toURI()), StandardOpenOption.READ);
} catch (Exception e) {
return new SeekableInMemoryByteChannel(getAsByteArray());
}
}
/**
* Get resource as string (assuming UTF-8 encoding) without normalized line separators.
*/
public String getContentAsRawString() {
try (InputStream inputStream = getAsStream()) {
return readStreamUTF8(inputStream);
} catch (IOException e) {
throw ResourceException.newLoadFailed(this, e);
}
}
/**
* Get resource as string (assuming UTF-8 encoding) with normalized line separators.
*/
public String getContent() {
return StringUtils.normalizeLineSeparatorsPlatformIndependent(getContentAsRawString());
}
/**
* Returns the content of the resource split into lines.
*/
public List getLines() {
return StringUtils.splitLinesAsList(getContentAsRawString());
}
/**
* Creates a temporary copy of the resource in the systems default temp file location. The file will
* be marked for deletion when the JVM shuts down.
*/
public File getAsTmpFile() throws IOException {
File tempFile = File.createTempFile("test-data-", getName());
copyTo(tempFile);
tempFile.deleteOnExit();
return tempFile;
}
/**
* Copies the resource to the given file. Parent directories are created if they do not exist yet.
* If the file itself already exists it wil be overridden.
*/
public File copyTo(File file) throws IOException {
ensureParentDirectoryExists(file);
try (FileOutputStream output = new FileOutputStream(file); InputStream input = getAsStream()) {
FileSystemUtils.copy(input, output);
}
return file;
}
/**
* Unzips the resource into the given folder under a folder with the same name as the resource's
* base name.
*/
public void unzipTo(File tempDir) throws IOException {
try (InputStream inputStream = getAsStream()) {
FileSystemUtils.unzip(inputStream, tempDir);
}
}
@Override
public int compareTo(Resource other) {
return getAbsolutePath().compareTo(other.getAbsolutePath());
}
@Override
public String toString() {
return getName();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Resource resource = (Resource) o;
return getAbsolutePath().equals(resource.getAbsolutePath()) && url.equals(resource.url);
}
@Override
public int hashCode() {
return Objects.hash(getAbsolutePath(), url);
}
}