> For the complete documentation index, see [llms.txt](https://docs.licensespring.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.licensespring.com/sdks/java-sdk/java-modules/java-license-client.md).

# Java License Client

License Client is the basic module in LicenseSpring implementation. For most use cases it's the only module required for a successful LicenseSpring implementation.

To include License Client to your Maven/Gradle project use this snippet:

{% tabs %}
{% tab title="Maven" %}

```xml
     <dependencies>
       <dependency>
            <groupId>com.licensespring</groupId>
            <artifactId>licensespring-license-client</artifactId>
            <version>2.16.1</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>jdk-java</id>
            <url>https://licensespring-maven.s3.eu-central-1.amazonaws.com/</url>
        </repository>
    </repositories>
```

{% endtab %}

{% tab title="Gradle" %}

```java
repositories {
    mavenLocal()
    maven {
        url = 'https://licensespring-maven.s3.eu-central-1.amazonaws.com/'
    }
}

dependencies {
    implementation 'com.licensespring:licensespring-license-client:2.16.1'
}
```

{% endtab %}
{% endtabs %}

*Javadoc, Jar and OSGi bundle downloads can be found* [**here.**](/sdks/java-sdk/downloads-and-javadoc.md)

### Initializing the License Client

All of the methods are accessed via the `LicenseManager` singleton. This means you initialize the SDK once and then use it throughout your application. Once initialized, the SDK contacts the LicenseSpring server to check for an existing license for the current computer/product combination. If a valid license is found, it becomes immediately available as a License object.

To initialize the SDK, you must supply authentication credentials and product information. You can choose one of two authentication methods:

**1. API Key Authentication:**

* **apiKey:** Your company API key
* **sharedKey:** A company-specific encryption key used when signing requests

**2. OAuth Authorization:**

* **clientId:** Your client identifier
* **clientSecret:** Your client secret

In addition to the authentication credentials, you must provide the **productCode**, an alphanumeric code identifying the specific product. The `apiKey` and `sharedKey` are available in the LicenseSpring Platform under "Settings -> Settings -> Keys." For [**OAuth Authorization**](/license-api/license-api-authorization/oauth-authorization.md), your `clientId` and `clientSecret` are available here: [**OAuth Configuration**](/vendor-platform/settings/oauth-configuration.md) . The `productCode` is defined when creating the product and ties the license to that specific product.

**Optional** Configuration parameters for initializing the License Client SDK:

* `licenseFilePath` determines where the license file will be stored on user's computer. By default, it is set to current working directory of the application with the filename `license.key`
* `offlineMode` enables offline mode. In this mode no requests are sent to LicenseSpring servers. Default is false.
* `enablePeriodicCheck` indicates if the Consumption APIs should be invoked periodically. Use with `Consumption` type licenses - when caching license state is required.
* `checkPeriod` period of invocation of the `checkLicense` method. Defaults to 1 hour if `Duration` object is not provided. Enabled by the `enablePeriodicCheck` flag.
* `requestLogging` request logging for debug purposes, default is no request logging.
* `appName` name of the application using the SDK.
* `appVersion` manually set the version of the application that's using the SDK.
* `identityProvider` set a custom `IdentityProvider` which generates unique keys for a particular device. Default implementation is based on Motherboard/CPU/Disk. See [**Java Hardware (Device) IDs**](/sdks/java-sdk/java-hardware-device-ids.md) for more information.
* `cacheHardwareId` set to true to allow caching of hardware IDs. Default is false
* `gracePeriodDays` period of days in which user can check `License` locally if API license check fails, this can either be a connection error or internal server error. Maximum of 30 days.
* `ignoreServerExceptions` similar to `gracePeriodDays`, SDK will check `License` locally if API license check fails, but with no time limit
* `enableNegativeConsumptions` enables the option to send negative consumptions, default is false.
* `proxyPort` and `proxyHost` used to setup a forward proxy, see more in [**Java Advanced Usage**](/sdks/java-sdk/java-advanced-usage.md).
* `requestTimeout` set the timeout of requests make to API (in seconds), default is 10 seconds
* `storeMachineInfo` - false by default. This toggles the collection of additional machine data, which includes:
  * `hostname`
  * `ipAddress`
  * `macAddress`
  * `vmInfo`
  * `osInfo`
* `infoToStore` - specify what information to store, ignored if `storeMachineInfo` is false, defaults to ALL if left empty.
* `airGappedPublicKey` - public key generated in the platform for air-gapped `Licences`

```java
// configuration with only required parameters
// NOTE building a LicenseSpringConfiguration without required parameters will throw a LicenseSpringConfigurationException
LicenseSpringConfiguration configuration = LicenseSpringConfiguration.builder()
                        .apiKey("api_key")
                        .sharedKey("shared_key")
                        .productCode("product_code")
                        .build();
                        
// OAuth minimum parameters
LicenseSpringConfiguration configuration = LicenseSpringConfiguration.builder()
                        .clientId("client_id")
                        .clientSecret("client_secret")
                        .productCode("product_code")
                        .build();                       

// configuration with more parameters
LicenseSpringConfiguration configuration = LicenseSpringConfiguration.builder()
                .apiKey("api_key")
                .productCode("product_code")
                .sharedKey("shared-key")
                .licenseFilePath("custom/path")
                .enablePeriodicCheck(true)
                .checkPeriod(Duration.ofHours(3))
                .requestLogging(Logger.Level.FULL)
                .appName("MyApplication")
                .appVersion("1.1.0")
                .cacheHardwareID(true)
                .gracePeriodDays(3)
                .enableNegativeConsumptions(true)
                .requestTimeout(60L)
                .storeMachineInfo(true)
                .infoToStore(InfoToStore.IP_ADDRESS)
                .build();
```

### LicenseManager

After setting up the SDK, there are a number of methods and objects available to the app developer. `LicenseManager` is a singleton that needs to be initialized once per runtime but can be retrieved using the `getInstance` method unlimited number of times.

```java
LicenseManager licenseManager = LicenseManager.getInstance();

// initialize the manager once per runtime with the configuration
// from the example above as a parameter

try {
	licenseManager.initialize(configuration);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// or

try {
	if (!licenseManager.isInitialized()) {
  	   licenseManager.initialize(configuration);
    }

} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### getCurrent()

In case no active license is available from the `LicenseRepository`, the return value will be null.

```java
License currentLicense = licenseManager.getCurrent();

if (currentLicense == null) {
  	// this means there are no active licenses on this device
	// actions taken in this if block depend on your needs
  	// you can provide the user a new license (if user is a new user)
  	// you can reactivate the license
  	// you can prompt the user to pay to get a new license (if for example, his subscription ended and his previous license expired)
  	// if the user is a first time user of your product you might wanna provide him a trial license if your product has a trial period
  	// to figure out what you want to do here see other methods from the LicenseManager that are at your disposal and you might get a grasp of what your use case would be
  
} else {
  	// this means there is an active license for your product on the device
  	// you can continue with your application flow
}
```

### getTrialLicense(String email)

You can generate a trial key directly from the app using the SDK, which will automatically associate this license key with the provided email. You can later use this data from the LicenseSpring platform to send out email campaigns targeting trial users for example.

{% hint style="info" %}
After you generate a trial key - the `UnactivatedTrialLicense` object will be returned, you still need to activate it using a call to `licenseManager.activateLicense()`
{% endhint %}

```java
try {
    UnactivatedTrialLicense trial = licenseManager.getTrialLicense("someemail@gmail.com");
    License license = licenseManager.activateLicense(trial.createIdentity());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
    return;
}

// if there weren't any exceptions 
// the LicenseManager will save the license 
// locally on the device using the LicenseRepository save() method
```

### getTrialLicense(Customer customer)

You can generate a trial key directly from the app using the SDK, which will automatically associate this license key with the provided customer. `Customer` object can be built using the builder, only email is required.

```java
// customer with only required field
Customer customer = Customer.builder()
        .email("someemail@gmail.com")
        .build();

// more verbose customer object
Customer customer = Customer.builder()
        .firstName("John")
        .lastName("Doe")
        .companyName("Company")
        .email("someemail@gmail.com")
        .phone("000-111-000")
        .reference("reference1212")
        .build();

try {
    UnactivatedTrialLicense trial = licenseManager.getTrialLicense(customer);
    License license = licenseManager.activateLicense(trial.createIdentity());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
    return;
}
```

### activateLicense(ActivationLicense identity)

Attempts to activate the product using provided `ActivationIdentity`. Returns the `License` object that has been activated.

```java
// keybased
ActivationLicense keyBased = ActivationLicense.fromKey("license-key");
try {
	License activated = licenseManager.activateLicense(keyBased);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// OR username/pass based - Note that this is the only API which requires the password.
// LicenseSpring will never store user passwords via the SDK.
ActivationLicense userBased = ActivationLicense.fromUsername("username", "password");

try {
	License activated = licenseManager.activateLicense(userBased);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### deactivateLicense(LicenseIdentity identity)

`License` is deactivated using a method on the `LicenseManager`. You need to supply the current license identity.

```java
// key based
try {
	boolean isDeactivated = licenseManager.deactivateLicense(LicenseIdentity.fromKey("sample-key"));
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based
try {
	boolean isDeactivated = licenseManager.deactivateLicense(ActivationLicense.fromUsername("username", "password"));
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### checkLicense(License license)

Checks the license on the LS servers and syncs any consumptions made.

```java
try {
  	License updatedLicense = licenseManager.checkLicense(licenseManager.getCurrent());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### getInstallationFile(LicenseIdentity identity)

Returns the latest valid installation file, if installation files are defined in the LicenseSpring platform. For more details please see [**Product Versioning**](/product-configuration/product-versioning.md).

```java
// key based
try {
	InstallationFile installationFile = licenseManager.getInstallationFile(LicenseIdentity.fromKey("sample-key"));
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based
try {
	InstallationFile installationFile = licenseManager.getInstallationFile(ActivationLicense.fromUsername("username", "password"));
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### getVersions(LicenseIdentity identity)

Returns all the available versions for the product configured via configuration settings.

```java
try {
	String[] versions = licenseManager.getVersions(LicenseIdentity.fromKey("sample-key"));
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### trackVariables(LicenseIdentity identity, Map\<String, String> variables)

Tracks device based variables for end uses. Can use the Variable builder as a utility.

```java
tr// KEY BASED
// build your own Map
try {
	licenseManager.trackVariables(LicenseIdentity.fromKey("sample-key"), new HashMap<>());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// use utility class to add some variables and track them
DeviceVariables deviceVars = DeviceVariables.builder()
     	.variable("one", "some value")
    	.variable("another_var", "other_value")
    	.build();

try {
	licenseManager.trackVariables(LicenseIdentity.fromKey("sample-key"), deviceVars.getVariables());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// USER BASED
// build your own Map
try {
	licenseManager.trackVariables(ActivationLicense.fromUsername("username", "password"), new HashMap<>());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// use utility class to add some variables and track them
DeviceVariables deviceVars = DeviceVariables.builder()
        .variable("one", "some value")
        .variable("another_var", "other_value")
        .build();

try {
	licenseManager.trackVariables(ActivationLicense.fromUsername("username", "password"), deviceVars.getVariables());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### getProductDetails()

Gets product details from LicenseSpring servers.

```shell
try {
    Product product = licenseManager.getProductDetails();

    log.info(product.getProductName());
    log.info(product.getShortCode());
    log.info(product.isAllowTrial());
    log.info(product.getTrialDays());
    log.info(product.getAuthorizationMethod());
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### offlineActivationFile(LicenseIdentity identity, String destination)

Generates an offline activation file which can be uploaded to LicenseSpring platform and activate the license. Default location for saving the file is Desktop, or if it can't be found, user home, this only applies if destination string is null. Default name of the file is "ls\_activation.req". For more information, see [**Offline License Activation**](/license-entitlements/license-activation-types/offline-license-activation.md).

```java
tr// KEY BASED
// build your own Map
try {
	licenseManager.trackVariables(LicenseIdentity.fromKey("sample-key"), new HashMap<>());
// key based with default file location 
try {
	licenseManager.offlineActivationFile(LicenseIdentity.fromKey("key"), null);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// key based with custom file path
try {
	licenseManager.offlineActivationFile(LicenseIdentity.fromKey("key"), "/home/user/Downloads/offline/");
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based with default file location 
try {
	licenseManager.offlineActivationFile(ActivationLicense.fromUsername("username", "password"), null);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based with custom file path
try {
	licenseManager.offlineActivationFile(ActivationLicense.fromUsername("username", "password"), "/home/user/Downloads/offline/");
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### offlineDeactivationFile(LicenseIdentity identity, String destination)

Generates an offline deactivation file which can be uploaded to LicenseSpring platform and deactivate the license. Default location for saving the file is `Desktop`, or if it can't be found, user home, this only applies if destination string is null. Default file name is `ls_deactivation.req`.

```java
// key based with default file location 
try {
	licenseManager.offlineDeactivationFile(LicenseIdentity.fromKey("key"), null);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// key based with custom file path
try {
	licenseManager.offlineDeactivationFile(LicenseIdentity.fromKey("key"), "/home/user/Downloads/deactivate/");
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based with default file location 
try {
	licenseManager.offlineDeactivationFile(ActivationLicense.fromUsername("username", "password"), null);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based with custom file path
try {
	licenseManager.offlineDeactivationFile(ActivationLicense.fromUsername("username", "password"), "/home/user/Downloads/deactivate/");
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
```

### activateOfflineResponse(LicenseIdentity identity, String filePath)

Activates the license from a file that was generated on the LicenseSpring platform. If the `filePath` is null, SDK will look for the file `ls_activation.lic` in `Desktop`, or in user home.

```java
// key based with default file location 
try {
	License license = licenseManager.activateOfflineResponse(LicenseIdentity.fromKey("key"), null);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// key based with custom file path
try {
	License license = licenseManager.activateOfflineResponse(LicenseIdentity.fromKey("key"), "/home/user/Downloads/");
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based with default file location 
License license = licenseManager.activateOfflineResponse(ActivationLicense.fromUsername("username", "password"), null);
try {

} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}

// user based with custom file path
License license = licenseManager.activateOfflineResponse(ActivationLicense.fromUsername("username", "password"), "/home/user/Downloads/");
try {

} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### clearLocalStorage()

Clears all local license data.

```shell
try {
	licenseManager.clearLocalStorage();
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### setOfflineMode(boolean offlineMode)

Changes the offline mode while the app is running. While offline, no requests to LS servers are made.

```java
try {
	licenseManager.setOfflineMode(true);
} catch (LicenseSpringException e) {
    log.error(e.getCause().getMessage());
}
```

### getAirGapActivationCode

Gets the activation code use for air gapped license

Needs the `LicenseSpringConfiguration` field: `airGappedPublicKey` to work with Air Gap Licences

```java
AirGappedActivation activation = licenseManager.getAirGapActivationCode(
	LicenseIdentity.fromKey("sample-key"), "initializationCodeFromPlatform"
);

log.info(activation.getActivationCode());
log.info(activation.getHardwareId());
log.info(activation.getLicenseKey());
```

### verifyAirGapConfirmationCode

Verifies the confirmation code for air gapped license

Needs the `LicenseSpringConfiguration` field: `airGappedPublicKey` to work with Air Gap Licences

```java
boolean verified = licenseManager.verifyAirGapConfirmationCode(
	LicenseIdentity.fromKey("sample-key"), 
  	"policyIdFromPlatform",
    "confirmationCodeFromPlatform"
);

log.info(verified);
```

### activateAirGapResponse

Activates the air gapped license from the license policy file

Needs the `LicenseSpringConfiguration` field: `airGappedPublicKey` to work with Air Gap Licences

```java
License license = licenseManager.activateAirGapResponse(
	LicenseIdentity.fromKey("sample-key"), 
  	"pathToPolicyFile",
    "policyId"
);

log.info(license.getHardwareId());
log.info(license.getIdentity().getLicenseKey());
```

### getAirGapDeactivationCode

Gets the deactivation code use for air gapped license

Needs the `LicenseSpringConfiguration` field: `airGappedPublicKey` to work with Air Gap Licences

```java
AirGappedDeactivation deactivation = licenseManager.getAirGapDeactivationCode(
	LicenseIdentity.fromKey("sample-key"), "initializationCodeFromPlatform"
);

log.info(deactivation.getDeactivationCode());
log.info(deactivation.getHardwareId());
log.info(deactivation.getLicenseKey());
```

### deactivateAirGapResponse

Deactivates the air gapped license from the license policy file and deleted the local license file

Needs the `LicenseSpringConfiguration` field: `airGappedPublicKey` to work with Air Gap Licences

```java
boolean deactivated = licenseManager.deactivateAirGapLicense(
	LicenseIdentity.fromKey("sample-key"), 
  	"pathToPolicyFile",
    "policyId"
);

assertTrue(deactivated);

License license = licenseManager.getCurrent();

assertNull(license);
```

### getSsoUrl

Gets the ssoUrl needed to activate the license using SSO - for more info, see [**Single Sign-On URL**](/license-api/single-sign-on-url.md)

*\* Note 1 - the activation code is short lived and converts into a user-based license after activation - DO NOT USE the ActivationLicense object used to activate the license, rather use the license.getIdentity after activation*

*\* Note 2 - the generated credentials are one-time use, generating new ones will disable previous*

```java
SSOUrl ssoURL = licenseManager.getSsoUrl(customerAccountCode, SSOResponseType.CODE);

//Follow the url to get the "code" or "id_token", this example is with "code"

String customerAccountCode = "yourCustomerAccountCodeWithSsoConfigured";
String code = "codeFromTheResponse";

//the ActivationLicense won't work after doing the activation
//use license.getIdentity() for usage in other methods after activation
ActivationLicense activationLicense = ActivationLicense.fromSsoCode(code, customerAccountCode);

License license = licenseManager.activateLicense(activationLicense);
License checkedLicense = licenseManager.checkLicense(license);
boolean deactivated = licenseManager.deactivateLicense(license.getIdentity());
```

### changeOauthClientSecret

Changes the OAuth Client Secret used for auth -> in case you have a rotating secret

```java
licenseManager.changeOAuthClientSecret("otherClientSecret");
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.licensespring.com/sdks/java-sdk/java-modules/java-license-client.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
