Class ResourceInstaller
http, https, and file locations are accepted.
A checksum is required for http and https sources and optional for file sources.
It is verified against the downloaded bytes before anything is unpacked: a
64-character hex digest selects SHA-256, a 128-character one SHA-512.
The content format is detected from the bytes, not from the name: gzip-compressed
tar archives and zip archives are unpacked with their relative structure. Invalid,
escaping, and duplicate file paths are rejected. Plain gzip files are decompressed,
and other content is stored as a file under the source name. One name rule overrides
byte detection: a *.bin source is always stored packed because an OpenNLP
model file is itself a zip archive that its consumers load packed.
Each installation is bounded by ResourceInstaller.Limits: http and https fetches use
connection and read timeouts, follow at most a fixed number of redirects, reject
redirects that leave the http and https schemes or downgrade https to http, and
abort once the download or the expanded content crosses its size limit or the
archive crosses its entry limit. Compressed content, gzip and zip alike, may
expand to at most ResourceInstaller.Limits.maxExpansionRatio() times its compressed size,
with a floor of 1048576L bytes for small sources. The defaults in
ResourceInstaller.Limits.DEFAULT apply when no limits are given, and ResourceInstaller.Limits.builder()
starts from them.
Installation is staged: content is unpacked into a hidden staging directory on the same filesystem and moved into the target only after the download was verified and every entry unpacked cleanly. A fetch, verification, or unpacking failure promotes no files into the target directory. Promotion does not replace a file that already exists in the target and detects the collision before moving anything, so refreshing a resource means removing its old files first. Work files left in the target by an installation that was killed are removed at the start of the next installation into that target, so concurrent installations into one target directory are not supported.
- Since:
- 3.0.0
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final classA unit budget, counting bytes or archive entries:ResourceInstaller.Budget.spend(long)accumulates spent units and fails once the limit is crossed.private static final classCharges every byte read or skipped from an expanded stream against a shared budget.static final recordSafety limits and network behavior for one installation.static interfaceWrites content into the staging directory ofinstallSelected(Path, StagingStep, Function). -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final charThe path separator used on Windows.(package private) static final intThe buffer size, in bytes, for streaming copies and digests in this package.private static final Stringprivate static final Stringprivate static final Stringprivate static final intprivate static final intprivate static final Stringprivate static final intprivate static final intprivate static final intprivate static final Stringprivate static final longThe expanded size every compressed source may reach regardless of the ratio.private static final StringOpenNLP model files are packed zip archives; install them packed.private static final charThe NUL character, which no file system accepts in a name.private static final StringThe path segment that names the parent directory.private static final Stringprivate static final Stringprivate static final Stringprivate static final charThe path separator used on all platforms.private static final Stringprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final intprivate static final Stringprivate static final int -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivatePrevents construction of this utility class. -
Method Summary
Modifier and TypeMethodDescriptionprivate static voidconsumeBounded(InputStream in, ResourceInstaller.Budget budget) Reads and discards an entry while charging each byte against the expansion limit.private static booleancontainsPathCharacter(String name) Checks a name for a path separator or a NUL character.private static voidcopy(InputStream in, Path file) Copies the stream into the file.private static voidcopyBounded(InputStream in, Path file, ResourceInstaller.Budget budget) Copies the stream into the file, charging every byte against the budget before it is written, so an oversized transfer aborts within one buffer of its limit.(package private) static PathcreateDownloadFile(Path targetDirectory) Creates the file the download is written to.private static voiddeleteRecursively(Path root) Removes the given directory tree, deepest entries first.private static Pathdestination(Path target, Path relative) Resolves one staged file's destination beneath the target, creating the directories leading to it one at a time.private static Pathdestination(Path target, Path relative, boolean create) Walks the directories leading to one staged file's destination without descending through a symbolic link that is already there.private static voiddownload(URI source, Path file, ResourceInstaller.Limits limits) Fetches the source into the given file, bounded by the download limit.private static voiddownloadHttp(URI source, Path file, ResourceInstaller.Limits limits, ResourceInstaller.Budget budget) Fetches an http or https source with connection and read timeouts, following at most the allowed number of redirects under the redirect policy, checking any declared content length against the download limit before reading the body, and bounding the transferred bytes against the same limit.private static booleanendsWithIgnoreCase(String name, String suffix) Compares a name's ending with a suffix, ignoring letter case.private static voidensureVacant(Path target, Path relative) Checks that one staged file's destination is free to receive it, without creating anything.private static ResourceInstaller.BudgetexpansionBudget(long compressedSize, ResourceInstaller.Limits limits, ResourceInstaller.Budget budget) Bounds expansion by the ratio as well as the absolute limit, so a small source cannot expand to the whole absolute limit.private static booleanhasMagic(byte[] actual, int... expected) Checks whether the bytes at the start of a resource match the given signature.static PathUnpacks a resource without checksum verification, underResourceInstaller.Limits.DEFAULT.static PathFetches, verifies, and unpacks a resource underResourceInstaller.Limits.DEFAULT.(package private) static Pathinstall(URI source, Path targetDirectory, String checksum, String name, ResourceInstaller.Limits limits) Validates the request, downloads and verifies the resource, and installs it from a staging directory.static Pathinstall(URI source, Path targetDirectory, String checksum, ResourceInstaller.Limits limits) Fetches, verifies, and unpacks a resource under the givenResourceInstaller.Limits.static intinstallSelected(Path targetDirectory, ResourceInstaller.StagingStep step, Function<Path, Path> selector) Installs a selection of the files that a caller-supplied step writes into a staging directory.private static intinstallStaged(Path target, ResourceInstaller.StagingStep step, Function<Path, Path> selector) Runs a staging step in a hidden staging directory beneath the target and promotes the selected files into the target only after the step completed.private static booleanClassifies a scheme as one the http fetch path handles.private static booleanisRedirect(int status) Classifies a response status as a redirect the installer follows.private static booleanisWorkFile(Path entry) Classifies a target directory entry as a work file of this class.listZipOnNonDefaultFileSystem(Path archive) private static longlittleEndianInt(byte[] bytes, int offset) Reads an unsigned 32-bit little-endian value.private static intlittleEndianShort(byte[] bytes, int offset) Reads an unsigned 16-bit little-endian value.private static PathResolves afilelocation to a path on the default filesystem.(package private) static voidmoveIntoPlace(Path file, Path destination) Moves one staged file to its destination without replacing an existing file.private static PathnewArchiveFile(Path staging, String entryName) Resolves a file entry beneath the staging directory and creates its parent directories.private static intMoves the selected staged regular files to their destinations beneath the target without replacing anything that already exists there.private static voidremoveIfEmpty(Path targetDirectory, Exception failure) Removes a target directory this installation created when the failed installation left nothing in it, so a failed first attempt leaves the filesystem as it was.private static voidremoveStaleWorkFiles(Path targetDirectory) Removes download files and staging directories that an earlier installation left in the target because its process ended before cleanup.private static voidrequireInsideTarget(Path relative) Checks that a selected destination stays beneath the target: it must be relative without a root, non-empty, and normalized without a leading.., so it has no.or..segments.(package private) static URIresolveRedirect(URI from, String location) Resolves a redirect location against the redirected request and enforces the redirect policy: the target must be an http or https location, and an https request must not be redirected to plain http.private static PathResolves an archive entry inside the staging directory, rejecting escaping paths.private static StringsourceName(URI source) Derives a file name from the source URI for non-archive content.private static inttimeoutMillis(Duration timeout) Converts a timeout to the millisecond form the connection setters take.private static voidunpack(Path downloaded, String name, Path staging, ResourceInstaller.Limits limits) Detects the content format from its leading bytes and unpacks accordingly, bounding the total expanded bytes against the expansion limit.private static voidunpackGzip(InputStream raw, String name, Path staging, ResourceInstaller.Budget budget, ResourceInstaller.Budget entryBudget) Unpacks gzip content: a tar archive inside when present, a plain file otherwise.private static voidunpackTar(InputStream decompressed, Path staging, ResourceInstaller.Budget entryBudget) Unpacks every regular tar entry to its relative location beneath the staging directory.unpackZip(InputStream raw, Path staging, ResourceInstaller.Budget budget, ResourceInstaller.Budget entryBudget) Unpacks every regular zip entry to its relative location beneath the staging directory.private static StringvalidateChecksum(String checksum) Validates the checksum argument and normalizes it for comparison.private static voidValidates an empty zip archive from its end-of-central-directory record.private static voidvalidateSource(URI source) Rejects a source the installer will not fetch.(package private) static StringvalidateSourceName(String name) Rejects names that are empty, path-like, or contain a NUL character.private static voidvalidateZip(Path archive, Set<String> unpacked) Checks that a zip archive contains a valid central directory listing the same files the local headers delivered, before staged content is promoted.private static voidComputes the file's digest and compares it with the expected hex digest, ignoring hex letter case.
-
Field Details
-
GZIP_SUFFIX
- See Also:
-
MODEL_SUFFIX
OpenNLP model files are packed zip archives; install them packed.- See Also:
-
DEFAULT_RESOURCE_NAME
- See Also:
-
STAGING_PREFIX
- See Also:
-
DOWNLOAD_PREFIX
- See Also:
-
DOWNLOAD_SUFFIX
- See Also:
-
PARENT_DIRECTORY
The path segment that names the parent directory.- See Also:
-
SLASH
private static final char SLASHThe path separator used on all platforms.- See Also:
-
BACKSLASH
private static final char BACKSLASHThe path separator used on Windows.- See Also:
-
NUL
private static final char NULThe NUL character, which no file system accepts in a name.- See Also:
-
BUFFER_SIZE
static final int BUFFER_SIZEThe buffer size, in bytes, for streaming copies and digests in this package.- See Also:
-
MAGIC_LENGTH
private static final int MAGIC_LENGTH- See Also:
-
GZIP_MAGIC_FIRST
private static final int GZIP_MAGIC_FIRST- See Also:
-
GZIP_MAGIC_SECOND
private static final int GZIP_MAGIC_SECOND- See Also:
-
ZIP_MAGIC_FIRST
private static final int ZIP_MAGIC_FIRST- See Also:
-
ZIP_MAGIC_SECOND
private static final int ZIP_MAGIC_SECOND- See Also:
-
ZIP_LOCAL_HEADER_THIRD
private static final int ZIP_LOCAL_HEADER_THIRD- See Also:
-
ZIP_LOCAL_HEADER_FOURTH
private static final int ZIP_LOCAL_HEADER_FOURTH- See Also:
-
ZIP_END_HEADER_THIRD
private static final int ZIP_END_HEADER_THIRD- See Also:
-
ZIP_END_HEADER_FOURTH
private static final int ZIP_END_HEADER_FOURTH- See Also:
-
ZIP_END_HEADER_LENGTH
private static final int ZIP_END_HEADER_LENGTH- See Also:
-
ZIP_DISK_OFFSET
private static final int ZIP_DISK_OFFSET- See Also:
-
ZIP_CENTRAL_DISK_OFFSET
private static final int ZIP_CENTRAL_DISK_OFFSET- See Also:
-
ZIP_DISK_ENTRIES_OFFSET
private static final int ZIP_DISK_ENTRIES_OFFSET- See Also:
-
ZIP_TOTAL_ENTRIES_OFFSET
private static final int ZIP_TOTAL_ENTRIES_OFFSET- See Also:
-
ZIP_CENTRAL_SIZE_OFFSET
private static final int ZIP_CENTRAL_SIZE_OFFSET- See Also:
-
ZIP_CENTRAL_OFFSET_OFFSET
private static final int ZIP_CENTRAL_OFFSET_OFFSET- See Also:
-
ZIP_COMMENT_LENGTH_OFFSET
private static final int ZIP_COMMENT_LENGTH_OFFSET- See Also:
-
MIN_EXPANSION_BYTES
private static final long MIN_EXPANSION_BYTESThe expanded size every compressed source may reach regardless of the ratio.- See Also:
-
HTTP_TEMPORARY_REDIRECT
private static final int HTTP_TEMPORARY_REDIRECT- See Also:
-
HTTP_PERMANENT_REDIRECT
private static final int HTTP_PERMANENT_REDIRECT- See Also:
-
SCHEME_HTTP
- See Also:
-
SCHEME_HTTPS
- See Also:
-
SCHEME_FILE
- See Also:
-
MALFORMED_ZIP_ERROR
- See Also:
-
ZIP_MISMATCH_ERROR
- See Also:
-
-
Constructor Details
-
ResourceInstaller
private ResourceInstaller()Prevents construction of this utility class.
-
-
Method Details
-
install
Unpacks a resource without checksum verification, underResourceInstaller.Limits.DEFAULT. This overload treats the source as trusted caller input and performs no cryptographic integrity verification, so it accepts onlyfilesources; an http or https source must go through an overload that takes its checksum.- Parameters:
source- The resource location, afileURI. Notnull.targetDirectory- The directory to install into; created when absent. Must not benull.- Returns:
- The target directory. Not
null. - Throws:
IOException- Thrown if fetching or unpacking fails.IllegalArgumentException- Thrown ifsourceortargetDirectoryisnull,sourcecontains a scheme other thanfile, or its last path segment is not a valid local file name.
-
install
Fetches, verifies, and unpacks a resource underResourceInstaller.Limits.DEFAULT.- Parameters:
source- The resource location, anhttp,https, orfileURI. Notnull.targetDirectory- The directory to install into; created when absent. Must not benull.checksum- The expected digest of the downloaded bytes as a hex string, compared case-insensitively and ignoring leading and trailing whitespace: 64 characters select SHA-256, 128 characters SHA-512. Required for an http or https source; passnullto skip verification for afilesource.- Returns:
- The target directory. Not
null. - Throws:
IOException- Thrown if fetching fails, the checksum does not match, or unpacking fails.IllegalArgumentException- Thrown ifsourceortargetDirectoryisnull,sourcecontains a scheme other thanhttp,https, orfile,checksumis not a 64-character or 128-character hex string, an http or https source contains no checksum, or the source does not provide a valid local file name.
-
install
public static Path install(URI source, Path targetDirectory, String checksum, ResourceInstaller.Limits limits) throws IOException Fetches, verifies, and unpacks a resource under the givenResourceInstaller.Limits.- Parameters:
source- The resource location, anhttp,https, orfileURI. Notnull.targetDirectory- The directory to install into; created when absent. Must not benull.checksum- The expected digest of the downloaded bytes as a hex string, compared case-insensitively and ignoring leading and trailing whitespace: 64 characters select SHA-256, 128 characters SHA-512. Required for an http or https source; passnullto skip verification for afilesource.limits- The timeouts, redirect allowance, and size and entry limits to enforce. Notnull.- Returns:
- The target directory. Not
null. - Throws:
IOException- Thrown if fetching fails, a limit is exceeded, the checksum does not match, or unpacking fails.IllegalArgumentException- Thrown ifsource,targetDirectory, orlimitsisnull,sourcecontains a scheme other thanhttp,https, orfile,checksumis not a 64-character or 128-character hex string, an http or https source contains no checksum, or the source does not provide a valid local file name.
-
install
static Path install(URI source, Path targetDirectory, String checksum, String name, ResourceInstaller.Limits limits) throws IOException Validates the request, downloads and verifies the resource, and installs it from a staging directory.- Parameters:
source- The resource location.targetDirectory- The directory to install into.checksum- The expected digest, ornullfor a file source.name- The preferred name for non-archive content, ornullto use the source name.limits- The limits to enforce.- Returns:
- The target directory. Not
null. - Throws:
IOException- Thrown if fetching, verification, or installation fails.IllegalArgumentException- Thrown if an argument is invalid.
-
installSelected
@Internal public static int installSelected(Path targetDirectory, ResourceInstaller.StagingStep step, Function<Path, Path> selector) throws IOExceptionInstalls a selection of the files that a caller-supplied step writes into a staging directory. The step runs against an empty hidden staging directory beneath the target, typically by callinginstall(URI, Path, String)with the staging directory as its target. The selector then maps each staged regular file, by its path relative to the staging directory, to its path relative to the target, or tonullto leave it out. The selected files are promoted under the same rules asinstall(URI, Path, String): nothing is promoted when the step fails, and an existing destination aborts the promotion before the first move.- Parameters:
targetDirectory- The directory to install into; created when absent. Must not benull.step- Writes the content into the staging directory. Must not benull.selector- Maps a staged file's relative path to its relative destination beneath the target, or tonullto skip the file. A destination must be relative and normalized. Must not benull.- Returns:
- The number of files installed.
- Throws:
IOException- Thrown if the step fails, a destination is absolute or not normalized, two staged files map to the same destination, a destination already exists, or moving fails.IllegalArgumentException- Thrown if a parameter isnull.
-
removeStaleWorkFiles
Removes download files and staging directories that an earlier installation left in the target because its process ended before cleanup. Only entries with the hidden work-file prefixes are touched.- Parameters:
targetDirectory- The directory to install into.- Throws:
IOException- Thrown if listing or deleting fails.
-
isWorkFile
Classifies a target directory entry as a work file of this class.- Parameters:
entry- The entry to inspect.- Returns:
trueif the entry name carries a work-file prefix.
-
removeIfEmpty
Removes a target directory this installation created when the failed installation left nothing in it, so a failed first attempt leaves the filesystem as it was.- Parameters:
targetDirectory- The directory this installation created.failure- The failure being reported; a cleanup error is added to it.
-
createDownloadFile
Creates the file the download is written to. It is placed on the target's filesystem, not in the system temporary directory, so a large download cannot exhaust the system temporary directory while the target has room. Its hidden prefix distinguishes it from installed content.- Parameters:
targetDirectory- The directory to install into. Must already exist.- Returns:
- The newly created, empty download file. Not
null. - Throws:
IOException- Thrown if the file cannot be created.
-
validateChecksum
Validates the checksum argument and normalizes it for comparison.- Parameters:
checksum- The digest as given by the caller, ornullto skip.- Returns:
- The stripped digest, or
nullwhen verification is skipped. - Throws:
IllegalArgumentException- Thrown if the digest is not a 64-character or 128-character hex string.
-
download
private static void download(URI source, Path file, ResourceInstaller.Limits limits) throws IOException Fetches the source into the given file, bounded by the download limit. Http and https locations are fetched with timeouts and the redirect policy; afilelocation is read directly. The scheme was accepted byvalidateSource(URI)at the public boundary.- Parameters:
source- The resource location.file- The file receiving the downloaded bytes.limits- The limits to enforce.- Throws:
IOException- Thrown if fetching fails or a limit is exceeded.
-
validateSource
Rejects a source the installer will not fetch. Onlyhttp,https, andfileare accepted: any other scheme would be passed to any URL handler the runtime happens to have installed, outside the connection timeout, read timeout, and redirect policy this class enforces.- Parameters:
source- The resource location as given by the caller.- Throws:
IllegalArgumentException- Thrown if the scheme is absent or unsupported.
-
isHttp
Classifies a scheme as one the http fetch path handles.- Parameters:
scheme- The URI scheme, ornullwhen the location has none.- Returns:
trueforhttpandhttps, ignoring case.
-
localFile
Resolves afilelocation to a path on the default filesystem.- Parameters:
source- Thefilelocation, already validated as such.- Returns:
- The local path. Not
null. - Throws:
IOException- Thrown if the location does not name a file this runtime can open, such as afileURI naming a remote host.
-
downloadHttp
private static void downloadHttp(URI source, Path file, ResourceInstaller.Limits limits, ResourceInstaller.Budget budget) throws IOException Fetches an http or https source with connection and read timeouts, following at most the allowed number of redirects under the redirect policy, checking any declared content length against the download limit before reading the body, and bounding the transferred bytes against the same limit.- Parameters:
source- The resource location as requested by the caller.file- The file receiving the downloaded bytes.limits- The limits to enforce.budget- The download budget shared with the caller.- Throws:
IOException- Thrown if fetching fails, the server answers with a status other than 200, the redirect policy is violated, or a limit is exceeded.
-
isRedirect
private static boolean isRedirect(int status) Classifies a response status as a redirect the installer follows.- Parameters:
status- The HTTP response status.- Returns:
trueif the status is one of the redirect statuses 301, 302, 303, 307, or 308.
-
resolveRedirect
Resolves a redirect location against the redirected request and enforces the redirect policy: the target must be an http or https location, and an https request must not be redirected to plain http.- Parameters:
from- The location that returned the redirect.location- The Location header value, absolute or relative, ornullwhen the header is absent.- Returns:
- The resolved redirect target. Not
null. - Throws:
IOException- Thrown if the location is absent or malformed, leaves the http and https schemes, or downgrades https to http.
-
timeoutMillis
Converts a timeout to the millisecond form the connection setters take. A positive timeout shorter than a millisecond becomes one millisecond becausezero disables the timeout. A timeout too large for the int range is capped.- Parameters:
timeout- The timeout as a duration. Must be positive.- Returns:
- The timeout in milliseconds, at least
1and at mostInteger.MAX_VALUE.
-
verify
Computes the file's digest and compares it with the expected hex digest, ignoring hex letter case. The digest length selects the algorithm: 64 characters SHA-256, 128 characters SHA-512.- Parameters:
file- The file to digest.expected- The expected hex digest, already trimmed.- Throws:
IOException- Thrown if the file cannot be read or the digests differ.
-
installStaged
private static int installStaged(Path target, ResourceInstaller.StagingStep step, Function<Path, Path> selector) throws IOExceptionRuns a staging step in a hidden staging directory beneath the target and promotes the selected files into the target only after the step completed. The staging directory lives on the target's filesystem so promotion is a sequence of renames, and it is removed whether the installation succeeds or fails.- Parameters:
target- The directory to install into.step- Writes the content into the staging directory.selector- Maps a staged file's relative path to its relative destination, or tonullto skip it.- Returns:
- The number of files promoted.
- Throws:
IOException- Thrown if the step fails, a limit is exceeded, or promotion or staging cleanup fails.
-
promote
private static int promote(Path staging, Path target, Function<Path, Path> selector) throws IOExceptionMoves the selected staged regular files to their destinations beneath the target without replacing anything that already exists there. All destinations are checked before the first move, so a collision leaves the target without a mix of old and new files, and the move itself refuses an existing destination as well.- Parameters:
staging- The staging directory holding the fully unpacked content.target- The directory to install into.selector- Maps a staged file's relative path to its relative destination, or tonullto skip it.- Returns:
- The number of files moved.
- Throws:
IOException- Thrown if a destination leaves the target, two files map to the same destination, a destination already exists, a move fails, or a directory on the way to a destination is an existing symbolic link.
-
requireInsideTarget
Checks that a selected destination stays beneath the target: it must be relative without a root, non-empty, and normalized without a leading.., so it has no.or..segments. A root without a drive, such as\xon Windows, is not absolute but still resolves outside the target.- Parameters:
relative- The file's destination path relative to the target.- Throws:
IOException- Thrown if the destination is absolute, has a root, is empty, or is not normalized.
-
moveIntoPlace
Moves one staged file to its destination without replacing an existing file. The move is not requested atomically: on POSIX filesystems an atomic move renames over an existing destination, which would void the vacancy check.- Parameters:
file- The staged file.destination- The destination beneath the target.- Throws:
IOException- Thrown if the destination exists or the move fails.
-
ensureVacant
Checks that one staged file's destination is free to receive it, without creating anything. A missing directory on the way proves the destination vacant.- Parameters:
target- The directory to install into.relative- The file's destination path relative to the target.- Throws:
IOException- Thrown if the destination already exists, or a directory on the way is a symbolic link or exists as something other than a directory.
-
destination
Resolves one staged file's destination beneath the target, creating the directories leading to it one at a time.- Parameters:
target- The directory to install into.relative- The file's destination path relative to the target.- Returns:
- The destination path beneath the target. Not
null. - Throws:
IOException- Thrown if a directory on the way is a symbolic link or exists as something other than a directory, or if a directory cannot be created.
-
destination
Walks the directories leading to one staged file's destination without descending through a symbolic link that is already there. An entry name that stays inside the staging directory can still land outside the target if a directory below the target is a link to somewhere else.This covers links present when the installation runs. It is not a defense against a link created concurrently, between the check here and the move that follows.
- Parameters:
target- The directory to install into.relative- The file's destination path relative to the target.create- Whether to create a missing directory on the way; whenfalse, a missing directory ends the walk.- Returns:
- The destination path beneath the target, or
nullwhen a directory on the way is missing andcreateisfalse. - Throws:
IOException- Thrown if a directory on the way is a symbolic link or exists as something other than a directory, or if a directory cannot be created.
-
deleteRecursively
Removes the given directory tree, deepest entries first.- Parameters:
root- The directory to remove.- Throws:
IOException- Thrown if a deletion fails.
-
unpack
private static void unpack(Path downloaded, String name, Path staging, ResourceInstaller.Limits limits) throws IOException Detects the content format from its leading bytes and unpacks accordingly, bounding the total expanded bytes against the expansion limit. One exception: a source named*.bin, in any letter case, is stored verbatim even when its bytes are a zip archive. OpenNLP model consumers load the packed zip artifact. Unpacking it would place the internal entries (manifest.properties,*.model) in the target instead of the model.- Parameters:
downloaded- The fetched file.name- The file name derived from the source location.staging- The staging directory to unpack into.limits- The limits to enforce.- Throws:
IOException- Thrown if reading or unpacking fails or the expansion limit is exceeded.
-
expansionBudget
private static ResourceInstaller.Budget expansionBudget(long compressedSize, ResourceInstaller.Limits limits, ResourceInstaller.Budget budget) Bounds expansion by the ratio as well as the absolute limit, so a small source cannot expand to the whole absolute limit. Deflate reaches roughly 1000 to 1, so the absolute limit alone lets a few megabytes fill the target filesystem.- Parameters:
compressedSize- The size of the compressed source in bytes.limits- The limits holding the accepted expansion ratio.budget- The expansion budget under the absolute limit.- Returns:
- The tighter of the two budgets. Not
null.
-
endsWithIgnoreCase
Compares a name's ending with a suffix, ignoring letter case.- Parameters:
name- The file name.suffix- The suffix to look for.- Returns:
trueif the name ends with the suffix in any letter case.
-
hasMagic
private static boolean hasMagic(byte[] actual, int... expected) Checks whether the bytes at the start of a resource match the given signature.- Parameters:
actual- The bytes read from the resource.expected- The unsigned byte values in the signature.- Returns:
truewhen the resource begins with the expected values.
-
validateZip
Checks that a zip archive contains a valid central directory listing the same files the local headers delivered, before staged content is promoted. The two listings can disagree in a crafted archive, and the local headers are what was unpacked.- Parameters:
archive- The downloaded archive.unpacked- The names of the file entries read from the local headers.- Throws:
IOException- Thrown if the archive is malformed, the listings differ, or the archive cannot be read.
-
listZipOnNonDefaultFileSystem
Lists the file entries of an archive stored by a file-system provider that cannot supply aFiletoZipFile.- Parameters:
archive- The downloaded archive.- Returns:
- The file entry names from the central directory. Not
null. - Throws:
IOException- Thrown if the archive is malformed or cannot be read.
-
validateEmptyZip
Validates an empty zip archive from its end-of-central-directory record. An empty archive has no local entry headers forZipInputStreamto validate.- Parameters:
raw- The zip content, positioned at its first byte.- Throws:
IOException- Thrown if the record is truncated, declares entries or central directory data, or has bytes beyond its declared comment.
-
littleEndianShort
private static int littleEndianShort(byte[] bytes, int offset) Reads an unsigned 16-bit little-endian value.- Parameters:
bytes- The source bytes.offset- The first byte to read.- Returns:
- The decoded value.
-
littleEndianInt
private static long littleEndianInt(byte[] bytes, int offset) Reads an unsigned 32-bit little-endian value.- Parameters:
bytes- The source bytes.offset- The first byte to read.- Returns:
- The decoded value.
-
unpackGzip
private static void unpackGzip(InputStream raw, String name, Path staging, ResourceInstaller.Budget budget, ResourceInstaller.Budget entryBudget) throws IOException Unpacks gzip content: a tar archive inside when present, a plain file otherwise. A plain file omits the.gzsuffix of its source name, in any letter case. If the source name is only that suffix, the installed file is named "resource".- Parameters:
raw- The gzip-compressed content.name- The file name derived from the source location.staging- The staging directory to unpack into.budget- The expansion budget.entryBudget- The entry-count budget.- Throws:
IOException- Thrown if decompressing or unpacking fails or a limit is exceeded.
-
unpackTar
private static void unpackTar(InputStream decompressed, Path staging, ResourceInstaller.Budget entryBudget) throws IOException Unpacks every regular tar entry to its relative location beneath the staging directory.- Parameters:
decompressed- The uncompressed tar content.staging- The staging directory to unpack into.entryBudget- The archive-header limit.- Throws:
IOException- Thrown if the archive is malformed, an entry escapes the staging directory, or the entry limit is exceeded.
-
unpackZip
private static Set<String> unpackZip(InputStream raw, Path staging, ResourceInstaller.Budget budget, ResourceInstaller.Budget entryBudget) throws IOException Unpacks every regular zip entry to its relative location beneath the staging directory.- Parameters:
raw- The zip content.staging- The staging directory to unpack into.budget- The expansion budget.entryBudget- The entry-count budget, charged for every entry including directories.- Returns:
- The names of the file entries unpacked. Not
null. - Throws:
IOException- Thrown if the archive is malformed, an entry escapes the staging directory, or a limit is exceeded.
-
newArchiveFile
Resolves a file entry beneath the staging directory and creates its parent directories. A second entry that normalizes to the same path is rejected.- Parameters:
staging- The staging directory.entryName- The path stored in the archive.- Returns:
- The new file path. Not
null. - Throws:
IOException- Thrown if the path escapes the staging directory, duplicates another file entry, or its parent directories cannot be created.
-
copyBounded
private static void copyBounded(InputStream in, Path file, ResourceInstaller.Budget budget) throws IOException Copies the stream into the file, charging every byte against the budget before it is written, so an oversized transfer aborts within one buffer of its limit.- Parameters:
in- The content to copy.file- The file to write.budget- The byte budget to charge.- Throws:
IOException- Thrown if reading or writing fails or the budget is exceeded.
-
consumeBounded
private static void consumeBounded(InputStream in, ResourceInstaller.Budget budget) throws IOException Reads and discards an entry while charging each byte against the expansion limit.- Parameters:
in- The entry content.budget- The byte budget to charge.- Throws:
IOException- Thrown if reading fails or the budget is exceeded.
-
copy
Copies the stream into the file. The input stream must already enforce any byte limit.- Parameters:
in- The content to copy.file- The file to write.- Throws:
IOException- Thrown if reading or writing fails.
-
safeChild
Resolves an archive entry inside the staging directory, rejecting escaping paths.- Parameters:
staging- The staging directory to unpack into.entryName- The entry name as stored in the archive.- Returns:
- The resolved path beneath the staging directory. Not
null. - Throws:
IOException- Thrown if the entry resolves outside the staging directory.
-
sourceName
Derives a file name from the source URI for non-archive content.- Parameters:
source- The resource location.- Returns:
- The last path segment, or
resourceif the location has none.
-
validateSourceName
Rejects names that are empty, path-like, or contain a NUL character.- Parameters:
name- The candidate local file name.- Returns:
- The validated name.
- Throws:
IllegalArgumentException- Thrown ifnameis not a file name.
-
containsPathCharacter
Checks a name for a path separator or a NUL character.- Parameters:
name- The candidate local file name.- Returns:
trueifnamecontains a slash, a backslash, or NUL.
-