Skip to content

Repository files navigation

LicenseChain Java SDK

LicenseJavaMaven Central

Official Java SDK for LicenseChain - Secure license management for Java applications.

🚀 Features

  • 🔐 Secure Authentication - User registration, login, and session management
  • 📜 License Management - Create, validate, update, and revoke licenses
  • 🛡️ Hardware ID Validation - Prevent license sharing and unauthorized access
  • 🔔 Webhook Support - Real-time license events and notifications
  • 📊 Analytics Integration - Track license usage and performance metrics
  • ⚡ High Performance - Optimized for production workloads
  • 🔄 Async Operations - Non-blocking HTTP requests and data processing
  • 🛠️ Easy Integration - Simple API with comprehensive documentation

📦 Installation

Method 1: Maven (Recommended)

Add to your pom.xml:

<dependency>
<groupId>com.licensechain</groupId>
<artifactId>licensechain-sdk</artifactId>
<version>1.0.0</version>
</dependency>

Method 2: Gradle

Add to your build.gradle:

implementation 'com.licensechain:licensechain-sdk:1.0.0'

Method 3: Manual Installation

  1. Download the latest JAR from GitHub Releases
  2. Add the JAR to your classpath
  3. Install required dependencies

🚀 Quick Start

Basic Setup

importcom.licensechain.LicenseChainClient;
importcom.licensechain.LicenseChainConfig;
importcom.licensechain.LicenseChainException;
publicclassBasicExample {
publicstaticvoidmain(String[] args) {
// Initialize the clientLicenseChainConfigconfig = newLicenseChainConfig.Builder()
.apiKey("your-api-key")
.appName("your-app-name")
.version("1.0.0")
.build();
LicenseChainClientclient = newLicenseChainClient(config);
// Connect to LicenseChaintry {
client.connect();
System.out.println("Connected to LicenseChain successfully!");
} catch (LicenseChainExceptione) {
System.err.println("Failed to connect: " + e.getMessage());
return;
}
}
}

User Authentication

// Register a new usertry {
Useruser = client.register("username", "password", "email@example.com");
System.out.println("User registered successfully!");
System.out.println("User ID: " + user.getId());
} catch (LicenseChainExceptione) {
System.err.println("Registration failed: " + e.getMessage());
}
// Login existing usertry {
Useruser = client.login("username", "password");
System.out.println("User logged in successfully!");
System.out.println("Session ID: " + user.getSessionId());
} catch (LicenseChainExceptione) {
System.err.println("Login failed: " + e.getMessage());
}

License Management

// Validate a licensetry {
Licenselicense = client.validateLicense("LICENSE-KEY-HERE");
System.out.println("License is valid!");
System.out.println("License Key: " + license.getKey());
System.out.println("Status: " + license.getStatus());
System.out.println("Expires: " + license.getExpires());
System.out.println("Features: " + String.join(", ", license.getFeatures()));
System.out.println("User: " + license.getUser());
} catch (LicenseChainExceptione) {
System.err.println("License validation failed: " + e.getMessage());
}
// Get user's licensestry {
List<License> licenses = client.getUserLicenses();
System.out.println("Found " + licenses.size() + " licenses:");
for (inti = 0; i < licenses.size(); i++) {
Licenselicense = licenses.get(i);
System.out.println(" " + (i + 1) + ". " + license.getKey() + " - " + license.getStatus() + " (Expires: " + license.getExpires() + ")");
}
} catch (LicenseChainExceptione) {
System.err.println("Failed to get licenses: " + e.getMessage());
}

Hardware ID Validation

// Get hardware ID (automatically generated)StringhardwareId = client.getHardwareId();
System.out.println("Hardware ID: " + hardwareId);
// Validate hardware ID with licensetry {
booleanisValid = client.validateHardwareId("LICENSE-KEY-HERE", hardwareId);
if (isValid) {
System.out.println("Hardware ID is valid for this license!");
} else {
System.out.println("Hardware ID is not valid for this license.");
}
} catch (LicenseChainExceptione) {
System.err.println("Hardware ID validation failed: " + e.getMessage());
}

Webhook Integration

// Set up webhook handlerclient.setWebhookHandler((eventName, data) -> {
System.out.println("Webhook received: " + eventName);
switch (eventName) {
case"license.created":
System.out.println("New license created: " + data.get("licenseKey"));
break;
case"license.updated":
System.out.println("License updated: " + data.get("licenseKey"));
break;
case"license.revoked":
System.out.println("License revoked: " + data.get("licenseKey"));
break;
}
});
// Start webhook listenerclient.startWebhookListener();

📚 API Endpoints

Use the canonical API base URL https://api.licensechain.app/v1. The SDK also accepts the root host and normalizes requests to the same API version.

Base URL

  • Production: https://api.licensechain.app/v1
  • Development: https://api.licensechain.app/v1

Available Endpoints

MethodEndpointDescription
GET/v1/healthHealth check
POST/v1/auth/loginUser login
POST/v1/auth/registerUser registration
GET/v1/appsList applications
POST/v1/appsCreate application
GET/v1/licensesList licenses
POST/v1/licenses/verifyVerify license
GET/v1/webhooksList webhooks
POST/v1/webhooksCreate webhook
GET/v1/analyticsGet analytics

Note: The SDK accepts either the root host or the canonical /v1 base and normalizes endpoint requests automatically.

📚 API Reference

LicenseChainClient

Constructor

LicenseChainConfigconfig = newLicenseChainConfig.Builder()
.apiKey("your-api-key")
.appName("your-app-name")
.version("1.0.0")
.baseUrl("https://api.licensechain.app/v1") // Optional
.build();
LicenseChainClientclient = newLicenseChainClient(config);

Methods

Connection Management
// Connect to LicenseChainclient.connect();
// Disconnect from LicenseChainclient.disconnect();
// Check connection statusbooleanisConnected = client.isConnected();
User Authentication
// Register a new userUseruser = client.register(username, password, email);
// Login existing userUseruser = client.login(username, password);
// Logout current userclient.logout();
// Get current user infoUseruser = client.getCurrentUser();
License Management
// Validate a licenseLicenselicense = client.validateLicense(licenseKey);
// Get user's licensesList<License> licenses = client.getUserLicenses();
// Create a new licenseLicenselicense = client.createLicense(userId, features, expires);
// Update a licenseLicenselicense = client.updateLicense(licenseKey, updates);
// Revoke a licenseclient.revokeLicense(licenseKey);
// Extend a licenseLicenselicense = client.extendLicense(licenseKey, days);
Hardware ID Management
// Get hardware IDStringhardwareId = client.getHardwareId();
// Validate hardware IDbooleanisValid = client.validateHardwareId(licenseKey, hardwareId);
// Bind hardware ID to licenseclient.bindHardwareId(licenseKey, hardwareId);
Webhook Management
// Set webhook handlerclient.setWebhookHandler(handler);
// Start webhook listenerclient.startWebhookListener();
// Stop webhook listenerclient.stopWebhookListener();
Analytics
// Track eventclient.trackEvent(eventName, properties);
// Get analytics dataAnalyticsanalytics = client.getAnalytics(timeRange);

🔧 Configuration

Properties File

Add to your application.properties:

# Requiredlicensechain.api.key=your-api-key
licensechain.app.name=your-app-name
licensechain.app.version=1.0.0
# Optionallicensechain.base.url=https://api.licensechain.app/v1
licensechain.timeout=30
licensechain.retries=3
licensechain.debug=false

Spring Boot Integration

@ConfigurationpublicclassLicenseChainConfig {
@Value("${licensechain.api.key}")
privateStringapiKey;
@Value("${licensechain.app.name}")
privateStringappName;
@Value("${licensechain.app.version}")
privateStringversion;
@BeanpublicLicenseChainClientlicenseChainClient() {
LicenseChainConfigconfig = newLicenseChainConfig.Builder()
.apiKey(apiKey)
.appName(appName)
.version(version)
.build();
returnnewLicenseChainClient(config);
}
}

Environment Variables

Set these in your environment or through your build process:

# Requiredexport LICENSECHAIN_API_KEY=your-api-key
export LICENSECHAIN_APP_NAME=your-app-name
export LICENSECHAIN_APP_VERSION=1.0.0
# Optionalexport LICENSECHAIN_BASE_URL=https://api.licensechain.app/v1
export LICENSECHAIN_DEBUG=true

🛡️ Security Features

Hardware ID Protection

The SDK automatically generates and manages hardware IDs to prevent license sharing:

// Hardware ID is automatically generated and storedStringhardwareId = client.getHardwareId();
// Validate against licensebooleanisValid = client.validateHardwareId(licenseKey, hardwareId);

Secure Communication

  • All API requests use HTTPS
  • API keys are securely stored and transmitted
  • Session tokens are automatically managed
  • Webhook signatures are verified

License Validation

  • Real-time license validation
  • Hardware ID binding
  • Expiration checking
  • Feature-based access control

📊 Analytics and Monitoring

Event Tracking

// Track custom eventsMap<String, Object> properties = newHashMap<>();
properties.put("level", 1);
properties.put("playerCount", 10);
client.trackEvent("app.started", properties);
// Track license eventsMap<String, Object> licenseProperties = newHashMap<>();
licenseProperties.put("licenseKey", "LICENSE-KEY");
licenseProperties.put("features", "premium,unlimited");
client.trackEvent("license.validated", licenseProperties);

Performance Monitoring

// Get performance metricsPerformanceMetricsmetrics = client.getPerformanceMetrics();
System.out.println("API Response Time: " + metrics.getAverageResponseTime() + "ms");
System.out.println("Success Rate: " + String.format("%.2f%%", metrics.getSuccessRate() * 100));
System.out.println("Error Count: " + metrics.getErrorCount());

🔄 Error Handling

Custom Exception Types

try {
Licenselicense = client.validateLicense("invalid-key");
} catch (InvalidLicenseExceptione) {
System.err.println("License key is invalid");
} catch (ExpiredLicenseExceptione) {
System.err.println("License has expired");
} catch (NetworkExceptione) {
System.err.println("Network connection failed");
} catch (LicenseChainExceptione) {
System.err.println("LicenseChain error: " + e.getMessage());
}

Retry Logic

// Automatic retry for network errorsLicenseChainConfigconfig = newLicenseChainConfig.Builder()
.apiKey("your-api-key")
.appName("your-app-name")
.version("1.0.0")
.retries(3) // Retry up to 3 times
.timeout(30000) // Wait 30 seconds for each request
.build();

🧪 Testing

Unit Tests

# Run tests
mvn test# Run tests with coverage
mvn test jacoco:report
# Run specific test
mvn test -Dtest=LicenseChainClientTest

Integration Tests

# Test with real API
mvn test -Dtest=*IntegrationTest

📝 Examples

See the examples/ directory for complete examples:

  • BasicUsageExample.java - Basic SDK usage
  • AdvancedFeaturesExample.java - Advanced features and configuration
  • WebhookIntegrationExample.java - Webhook handling
  • examples/jwks_only/JwksOnly.java — RS256 license_token via JWKS only (see examples/jwks_only/README.md; JWKS_EXAMPLE_PRIORITY)

🤝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

  1. Clone the repository
  2. Install Java 11 or later
  3. Install Maven 3.6 or later
  4. Build: mvn clean compile
  5. Test: mvn test

📄 License

This project is licensed under the Elastic License 2.0 (ELv2) — see the LICENSE file for details.

🆘 Support

🔗 Related Projects


Made with ❤️ for the Java community

LicenseChain API (v1)

This SDK targets the LicenseChain HTTP API v1 implemented by the LicenseChain API service.

  • Production base URL:https://api.licensechain.app/v1
  • API reference:docs.licensechain.app
  • Baseline REST mapping (documented for integrators):
    • GET /health
    • POST /auth/register
    • POST /licenses/verify
    • PATCH /licenses/:id/revoke
    • PATCH /licenses/:id/activate
    • PATCH /licenses/:id/extend
    • GET /analytics/stats

About

Official Java SDK for LicenseChain — license validation and management

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages