Class ResourceInstaller

java.lang.Object
opennlp.tools.util.ResourceInstaller

public final class ResourceInstaller extends Object
Fetches a third-party resource, such as a training corpus, a dictionary archive, or a lexicon, into a local directory. The caller supplies the location and thereby accepts that resource's license; no locations are built in and no data is bundled. Only 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:
  • Field Details

  • Constructor Details

    • ResourceInstaller

      private ResourceInstaller()
      Prevents construction of this utility class.
  • Method Details

    • install

      public static Path install(URI source, Path targetDirectory) throws IOException
      Unpacks a resource without checksum verification, under ResourceInstaller.Limits.DEFAULT. This overload treats the source as trusted caller input and performs no cryptographic integrity verification, so it accepts only file sources; an http or https source must go through an overload that takes its checksum.
      Parameters:
      source - The resource location, a file URI. Not null.
      targetDirectory - The directory to install into; created when absent. Must not be null.
      Returns:
      The target directory. Not null.
      Throws:
      IOException - Thrown if fetching or unpacking fails.
      IllegalArgumentException - Thrown if source or targetDirectory is null, source contains a scheme other than file, or its last path segment is not a valid local file name.
    • install

      public static Path install(URI source, Path targetDirectory, String checksum) throws IOException
      Fetches, verifies, and unpacks a resource under ResourceInstaller.Limits.DEFAULT.
      Parameters:
      source - The resource location, an http, https, or file URI. Not null.
      targetDirectory - The directory to install into; created when absent. Must not be null.
      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; pass null to skip verification for a file source.
      Returns:
      The target directory. Not null.
      Throws:
      IOException - Thrown if fetching fails, the checksum does not match, or unpacking fails.
      IllegalArgumentException - Thrown if source or targetDirectory is null, source contains a scheme other than http, https, or file, checksum is 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 given ResourceInstaller.Limits.
      Parameters:
      source - The resource location, an http, https, or file URI. Not null.
      targetDirectory - The directory to install into; created when absent. Must not be null.
      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; pass null to skip verification for a file source.
      limits - The timeouts, redirect allowance, and size and entry limits to enforce. Not null.
      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 if source, targetDirectory, or limits is null, source contains a scheme other than http, https, or file, checksum is 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, or null for a file source.
      name - The preferred name for non-archive content, or null to 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 IOException
      Installs 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 calling install(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 to null to leave it out. The selected files are promoted under the same rules as install(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 be null.
      step - Writes the content into the staging directory. Must not be null.
      selector - Maps a staged file's relative path to its relative destination beneath the target, or to null to skip the file. A destination must be relative and normalized. Must not be null.
      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 is null.
    • removeStaleWorkFiles

      private static void removeStaleWorkFiles(Path targetDirectory) throws IOException
      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

      private static boolean isWorkFile(Path entry)
      Classifies a target directory entry as a work file of this class.
      Parameters:
      entry - The entry to inspect.
      Returns:
      true if the entry name carries a work-file prefix.
    • removeIfEmpty

      private static void removeIfEmpty(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.
      Parameters:
      targetDirectory - The directory this installation created.
      failure - The failure being reported; a cleanup error is added to it.
    • createDownloadFile

      static Path createDownloadFile(Path targetDirectory) throws IOException
      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

      private static String validateChecksum(String checksum)
      Validates the checksum argument and normalizes it for comparison.
      Parameters:
      checksum - The digest as given by the caller, or null to skip.
      Returns:
      The stripped digest, or null when 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; a file location is read directly. The scheme was accepted by validateSource(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

      private static void validateSource(URI source)
      Rejects a source the installer will not fetch. Only http, https, and file are 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

      private static boolean isHttp(String scheme)
      Classifies a scheme as one the http fetch path handles.
      Parameters:
      scheme - The URI scheme, or null when the location has none.
      Returns:
      true for http and https, ignoring case.
    • localFile

      private static Path localFile(URI source) throws IOException
      Resolves a file location to a path on the default filesystem.
      Parameters:
      source - The file location, 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 a file URI 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:
      true if the status is one of the redirect statuses 301, 302, 303, 307, or 308.
    • resolveRedirect

      static URI resolveRedirect(URI from, String location) throws IOException
      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, or null when 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

      private static int timeoutMillis(Duration timeout)
      Converts a timeout to the millisecond form the connection setters take. A positive timeout shorter than a millisecond becomes one millisecond because zero 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 1 and at most Integer.MAX_VALUE.
    • verify

      private static void verify(Path file, String expected) throws IOException
      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 IOException
      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. 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 to null to 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 IOException
      Moves 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 to null to 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

      private static void requireInsideTarget(Path relative) throws IOException
      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 \x on 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

      static void moveIntoPlace(Path file, Path destination) throws IOException
      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

      private static void ensureVacant(Path target, Path relative) throws IOException
      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

      private static Path destination(Path target, Path relative) throws IOException
      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

      private static Path destination(Path target, Path relative, boolean create) throws IOException
      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; when false, a missing directory ends the walk.
      Returns:
      The destination path beneath the target, or null when a directory on the way is missing and create is false.
      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

      private static void deleteRecursively(Path root) throws IOException
      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

      private static boolean endsWithIgnoreCase(String name, String suffix)
      Compares a name's ending with a suffix, ignoring letter case.
      Parameters:
      name - The file name.
      suffix - The suffix to look for.
      Returns:
      true if 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:
      true when the resource begins with the expected values.
    • validateZip

      private static void validateZip(Path archive, Set<String> unpacked) throws IOException
      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

      private static Set<String> listZipOnNonDefaultFileSystem(Path archive) throws IOException
      Lists the file entries of an archive stored by a file-system provider that cannot supply a File to ZipFile.
      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

      private static void validateEmptyZip(InputStream raw) throws IOException
      Validates an empty zip archive from its end-of-central-directory record. An empty archive has no local entry headers for ZipInputStream to 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 .gz suffix 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

      private static Path newArchiveFile(Path staging, String entryName) throws IOException
      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

      private static void copy(InputStream in, Path file) throws IOException
      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

      private static Path safeChild(Path staging, String entryName) throws IOException
      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

      private static String sourceName(URI source)
      Derives a file name from the source URI for non-archive content.
      Parameters:
      source - The resource location.
      Returns:
      The last path segment, or resource if the location has none.
    • validateSourceName

      static String validateSourceName(String name)
      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 if name is not a file name.
    • containsPathCharacter

      private static boolean containsPathCharacter(String name)
      Checks a name for a path separator or a NUL character.
      Parameters:
      name - The candidate local file name.
      Returns:
      true if name contains a slash, a backslash, or NUL.