Class IP2LocationService.Builder

java.lang.Object
co.mindus.ip2location.IP2LocationService.Builder
Enclosing class:
IP2LocationService

public static class IP2LocationService.Builder extends Object
Builder for creating IP2LocationService instances.

Required Settings

Optional Settings

MethodDefaultDescription
database(Database)DB11Database type
includeIPv6(boolean)falseEnable IPv6 lookups
directory(Path)temp/ip2locationStorage directory
logger(IEventLogger)Silent (IEventLogger.nullLogger())Event logger
checkIntervalMs(long)6 hoursUpdate check interval
useMemoryMappedFile(boolean)falseMemory-mapped mode
threadFactory(IThreadFactory)Virtual threadsThread creation
attemptRecovery()falseClear directory on startup
enabled(boolean)trueEnable/disable service

Build Methods

Author:
Christopher Mindus
See Also:
  • Constructor Details

    • Builder

      public Builder()
      Creates a new Builder with default settings.
  • Method Details

    • downloadToken

      public IP2LocationService.Builder downloadToken(String token)
      Sets the download token for IP2Location API authentication.

      Get your token by signing up at lite.ip2location.com and navigating to the download area.

      Parameters:
      token - The download token (required)
      Returns:
      This builder for chaining
    • database

      public IP2LocationService.Builder database(Database database)
      Sets the database type to use.

      All database types support both IPv4 and IPv6 lookups. The IPv6 database is automatically downloaded when includeIPv6(boolean) is enabled.

      Parameters:
      database - The database type (default: DB11)
      Returns:
      This builder for chaining
    • includeIPv6

      public IP2LocationService.Builder includeIPv6(boolean include)
      Sets whether to enable IPv6 lookups.

      When enabled:

      • Both IPv4 and IPv6 database files are downloaded (in parallel)
      • IPv4 lookups use the smaller IPv4-only database
      • IPv6 lookups use the IPv6 database

      When disabled (default):

      Parameters:
      include - true to enable IPv6 support (default: false)
      Returns:
      This builder for chaining
    • directory

      public IP2LocationService.Builder directory(Path directory)
      Sets the directory for storing database files.

      The directory will be created if it doesn't exist.

      Parameters:
      directory - Path to the storage directory
      Returns:
      This builder for chaining
    • logger

      public IP2LocationService.Builder logger(IEventLogger logger)
      Sets the event logger for operational messages.
      Parameters:
      logger - The event logger implementation
      Returns:
      This builder for chaining
      See Also:
    • checkIntervalMs

      public IP2LocationService.Builder checkIntervalMs(long intervalMs)
      Sets the interval between automatic update checks.
      Parameters:
      intervalMs - Interval in milliseconds (default: 6 hours, minimum: 1 minute)
      Returns:
      This builder for chaining
      Throws:
      IllegalArgumentException - if interval is less than 1 minute
    • useMemoryMappedFile

      public IP2LocationService.Builder useMemoryMappedFile(boolean useMemoryMapped)
      Sets whether to use memory-mapped files for database access.

      Memory-Mapped Mode (true)

      • Uses less JVM heap memory
      • OS manages page caching efficiently
      • May have slightly faster random access
      • Recommended for production servers

      Standard Mode (false, default)

      • More predictable memory behavior
      • Better for containerized environments
      • Easier to monitor memory usage
      Parameters:
      useMemoryMapped - true for memory-mapped (default: false)
      Returns:
      This builder for chaining
    • threadFactory

      public IP2LocationService.Builder threadFactory(IThreadFactory factory)
      Sets the thread factory for creating background threads.

      Use this to integrate with your application's thread management or to use virtual threads in Java 21+.

      Parameters:
      factory - The thread factory (default: virtual threads, IThreadFactory.virtualFactory(); null restores that default)
      Returns:
      This builder for chaining
      See Also:
    • attemptRecovery

      public IP2LocationService.Builder attemptRecovery()
      Enables recovery mode to clear the directory before initialization.

      When enabled, all existing database files, state files, and temporary files are deleted from the configured directory before initialization. This forces a fresh download of the databases.

      Use this when:

      • The database files may be corrupted
      • The state file may be corrupted or inconsistent
      • You want to force a complete refresh
      • Previous initialization attempts failed

      Example

      // Normal startup failed, try recovery
      IP2LocationService service = new IP2LocationService.Builder()
          .downloadToken("YOUR_TOKEN")
          .database(Database.DB11)
          .directory(Paths.get("/var/lib/ip2location"))
          .attemptRecovery()
          .build();
      
      Returns:
      This builder for chaining
    • enabled

      public IP2LocationService.Builder enabled(boolean enabled)
      Sets whether the service is enabled.

      When disabled:

      • No databases are downloaded or loaded
      • No scheduler is started for automatic updates
      • Lookups return STATUS_SERVICE_DISABLED
      • The service consumes minimal resources

      This is useful for:

      • Disabling geolocation in certain environments (dev, test)
      • Feature flags to turn off geolocation without code changes
      • Graceful degradation when IP2Location is not needed

      Example

      boolean useGeoLocation = Boolean.parseBoolean(
          System.getProperty("app.geolocation.enabled", "true"));
      
      IP2LocationService service = new IP2LocationService.Builder()
          .downloadToken("YOUR_TOKEN")
          .enabled(useGeoLocation)  // Can be disabled via system property
          .build();
      
      Parameters:
      enabled - true to enable the service (default), false to disable
      Returns:
      This builder for chaining
    • getDirectory

      public Path getDirectory()
      Returns the configured directory path.

      Used internally by IP2LocationManager for directory comparison.

      Returns:
      The configured directory path
    • build

      public IP2LocationService build()
      Builds and initializes the service synchronously.

      This method blocks until:

      • Existing databases are loaded, OR
      • New databases are downloaded (if stale or missing), OR
      • Initialization fails with an error

      If attemptRecovery() was called, the directory is cleared first.

      After this method returns, IP2LocationService.isReady() will return true if at least one database was loaded successfully.

      Returns:
      A fully initialized IP2LocationService
      Throws:
      IllegalStateException - if downloadToken is not set
    • buildAsync

      public IP2LocationService buildAsync()
      Builds the service with asynchronous initialization.

      Returns immediately with a service instance. Initialization runs in a background thread. Use IP2LocationService.awaitReady(long, TimeUnit) to wait for completion, or IP2LocationService.isReady() to check status.

      If attemptRecovery() was called, the directory is cleared first (during the async initialization).

      Returns:
      An IP2LocationService (may not be ready yet)
      Throws:
      IllegalStateException - if downloadToken is not set
    • buildAsync

      public IP2LocationService buildAsync(IInitializationCallback callback)
      Builds the service with asynchronous initialization and callback.

      Returns immediately. The callback is invoked when initialization completes (successfully or with an error).

      If attemptRecovery() was called, the directory is cleared first (during the async initialization, before the callback is invoked).

      Parameters:
      callback - Callback for initialization result (may be null)
      Returns:
      An IP2LocationService (may not be ready yet)
      Throws:
      IllegalStateException - if downloadToken is not set