### User Model and Validation Example
Source: https://context7.com/richkmeli/jframework/llms.txt
Shows how to create and manage User objects, including setting email, password, and admin status. Email validation is automatically performed using regex upon instantiation.
```java
import it.richkmeli.jframework.auth.model.User;
import it.richkmeli.jframework.auth.model.exception.ModelException;
public class UserModelExample {
public static void main(String[] args) {
try {
// Create a regular user
User user = new User("john@example.com", "securePassword123");
System.out.println("User email: " + user.getEmail());
System.out.println("Is admin: " + user.getAdmin());
// Output: Is admin: false
// Create an admin user
User admin = new User("admin@example.com", "adminPass456", true);
System.out.println("Admin email: " + admin.getEmail());
System.out.println("Is admin: " + admin.getAdmin());
// Output: Is admin: true
// Update user properties
user.setAdmin(true);
user.setPassword("newSecurePassword");
// Validate user data (called automatically in constructor)
User.checkUserIntegrity("test@domain.com", "password123", false);
System.out.println("User integrity check passed");
} catch (ModelException e) {
System.err.println("Validation error: " + e.getMessage());
// Thrown if email format is invalid
}
}
}
```
--------------------------------
### Client-Server Encrypted Communication Example
Source: https://context7.com/richkmeli/jframework/llms.txt
Demonstrates end-to-end encrypted communication with automatic key exchange between a client and server. Requires setup of secure data files and secret keys for both parties.
```java
import it.richkmeli.jframework.crypto.Crypto;
import it.richkmeli.jframework.crypto.exception.CryptoException;
import java.io.File;
public class SecureCommunicationExample {
public static void main(String[] args) throws CryptoException {
// Server-side setup
File serverSecureData = new File("server_secure.dat");
String serverSecretKey = "serverKey123";
String clientID = "client001";
Crypto.Server server = new Crypto.Server();
// Client-side setup
File clientSecureData = new File("client_secure.dat");
String clientSecretKey = "clientKey456";
Crypto.Client client = new Crypto.Client();
// Initialize secure channel (exchange keys)
// Client sends initial payload to server
String clientInitPayload = "client_init_data";
String serverResponse = server.init(serverSecureData, serverSecretKey, clientID, clientInitPayload);
// Server response is used to complete client initialization
client.init(clientSecureData, clientSecretKey, serverResponse);
// Encrypted communication
String message = "Confidential business data";
String encryptedMessage = client.encrypt(message);
System.out.println("Client encrypted: " + encryptedMessage);
// Server decrypts
String decryptedMessage = server.decrypt(encryptedMessage);
System.out.println("Server decrypted: " + decryptedMessage);
// Output: Server decrypted: Confidential business data
// Cleanup
client.reset();
server.deleteClientData();
}
}
```
--------------------------------
### Perform HTTP Requests with OkHttp
Source: https://context7.com/richkmeli/jframework/llms.txt
Demonstrates configuring the Network client for authentication, user agents, and executing both asynchronous and synchronous GET/PUT requests.
```java
import it.richkmeli.jframework.network.tcp.client.okhttp.Network;
import it.richkmeli.jframework.network.tcp.client.okhttp.NetworkCallback;
import it.richkmeli.jframework.network.tcp.client.okhttp.NetworkException;
public class HttpClientExample {
public static void main(String[] args) throws NetworkException {
Network network = new Network();
// Configure server URL
network.setURL("https", "api.example.com", "443", "api/v1");
// Set authentication credentials (Basic Auth)
network.setCredentials("username", "password");
// Set custom user agent
network.setUserAgent("MyApp/1.0");
// Async GET request
String jsonParams = "{\"id\":\"123\",\"type\":\"user\"}";
network.getRequest("users", jsonParams, null, null, new NetworkCallback() {
@Override
public void onSuccess(String response) {
System.out.println("Response: " + response);
// Output: Response: {"status":"ok","message":{...}}
}
@Override
public void onFailure(Exception e) {
System.err.println("Request failed: " + e.getMessage());
}
});
// Sync GET request
String syncResponse = network.GetRequestSync("status");
System.out.println("Sync response: " + syncResponse);
// PUT request with JSON body
String putParams = "{\"name\":\"John\",\"email\":\"john@example.com\"}";
network.putRequest("users/123", putParams, null, new NetworkCallback() {
@Override
public void onSuccess(String response) {
System.out.println("Update successful: " + response);
}
@Override
public void onFailure(Exception e) {
System.err.println("Update failed: " + e.getMessage());
}
});
// Clear session cookies
network.deleteSession();
}
}
```
--------------------------------
### Configure and Use Logger
Source: https://context7.com/richkmeli/jframework/llms.txt
Demonstrates how to enable and use the Logger class for info, warning, error, and debug level messages. Includes logging with exceptions and checking log file dimensions. Configuration can be done via properties file or programmatically.
```properties
logger.enabled=true
logger.debug=true
logger.filename=/var/log/myapp/app.log
```
```java
import it.richkmeli.jframework.util.log.Logger;
public class LoggerExample {
public static void main(String[] args) {
// Enable logging programmatically (optional, uses config by default)
Logger.enabled = true;
Logger.debug = true;
// Info level logging
Logger.info("Application started successfully");
// Output: 2024-01-15 10:30:45.123, INFO LoggerExample : Application started successfully
// Warning level logging
Logger.warning("Configuration file not found, using defaults");
// Output: 2024-01-15 10:30:45.124, WARNING LoggerExample : Configuration file not found...
// Error level logging
Logger.error("Failed to connect to database");
// Output: 2024-01-15 10:30:45.125, ERROR LoggerExample : Failed to connect to database
// Error with exception
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
Logger.error("Calculation error", e);
// Output: 2024-01-15 10:30:45.126, ERROR LoggerExample : Calculation error || / by zero
}
// Debug level (only if debug=true)
Logger.debug("Variable x = 42, processing step 3");
// Output: 2024-01-15 10:30:45.127, DEBUG LoggerExample : Variable x = 42, processing step 3
// Check and clean log file if too large (>50MB)
Logger.checkLogFileDimension();
}
}
```
--------------------------------
### Configure Maven Settings for GitHub Packages
Source: https://github.com/richkmeli/jframework/blob/master/README.md
Add this configuration to your ~/.m2/settings.xml file to authenticate with GitHub Packages. Replace placeholders with your GitHub username and a Personal Access Token with 'read:packages' scope.
```xml
github
YOUR_GITHUB_USERNAME
YOUR_GITHUB_TOKEN
```
--------------------------------
### Manage User Sessions with AuthSession
Source: https://context7.com/richkmeli/jframework/llms.txt
Demonstrates initializing an authentication session and performing user management tasks like adding users, verifying credentials, and setting session state.
```java
import it.richkmeli.jframework.auth.web.util.AuthSession;
import it.richkmeli.jframework.auth.data.AuthDatabaseModel;
import it.richkmeli.jframework.auth.model.User;
public class AuthSessionExample {
public static void main(String[] args) throws Exception {
// Create auth database instance (your implementation)
AuthDatabaseModel authDB = new CustomAuthDatabase();
// Create session
AuthSession session = new AuthSession(authDB);
// Add users to database
session.getAuthDatabaseManager().addUser(
new User("admin@company.com", "adminPass123", true)
);
session.getAuthDatabaseManager().addUser(
new User("user@company.com", "userPass456", false)
);
// Check user existence
boolean exists = session.getAuthDatabaseManager().isUserPresent("admin@company.com");
System.out.println("Admin exists: " + exists);
// Output: Admin exists: true
// Verify password
boolean validPassword = session.getAuthDatabaseManager()
.checkPassword("admin@company.com", "adminPass123");
System.out.println("Password valid: " + validPassword);
// Check admin status
boolean isAdmin = session.getAuthDatabaseManager().isAdmin("admin@company.com");
System.out.println("Is admin: " + isAdmin);
// Output: Is admin: true
// Set session user after successful login
session.setUserID("admin@company.com");
session.setAdmin(true);
System.out.println("Logged in user: " + session.getUserID());
// Output: Logged in user: admin@company.com
}
}
```
--------------------------------
### Compile JFramework from Source
Source: https://github.com/richkmeli/jframework/blob/master/README.md
Build the JFramework project locally using Maven. This command compiles the code and packages the artifacts.
```bash
mvn package
```
--------------------------------
### Implement Custom Database Manager
Source: https://context7.com/richkmeli/jframework/llms.txt
Extend DatabaseManager to define schema and table configurations. Call init() in the constructor to initialize the connection and create tables.
```java
import it.richkmeli.jframework.orm.DatabaseManager;
import it.richkmeli.jframework.orm.DatabaseException;
import java.util.List;
public class ProductDatabaseManager extends DatabaseManager {
public ProductDatabaseManager() throws DatabaseException {
// Set schema and table configuration
schemaName = "myapp";
tableName = schemaName + ".products";
table = " (productId VARCHAR(50) PRIMARY KEY, name VARCHAR(255), " +
"description VARCHAR(1000), active BOOLEAN)";
// Initialize connection and create tables
init();
}
// Create
public boolean addProduct(Product product) throws DatabaseException {
return create(product);
}
// Read single
public Product getProduct(String productId) throws DatabaseException {
Product searchKey = new Product(productId, null, null, null);
return read(searchKey);
}
// Read all
public List getAllProducts() throws DatabaseException {
return readAll(Product.class);
}
// Update
public boolean updateProduct(Product product) throws DatabaseException {
return update(product);
}
// Delete
public boolean deleteProduct(String productId) throws DatabaseException {
Product searchKey = new Product(productId, null, null, null);
return delete(searchKey);
}
}
```
--------------------------------
### RSA Key Pair Generation and Encryption
Source: https://context7.com/richkmeli/jframework/llms.txt
Demonstrates generating 2048-bit RSA keys, performing encryption/decryption, and signing data using the BouncyCastle provider.
```java
import it.richkmeli.jframework.crypto.algorithm.RSA;
import java.security.*;
public class RSAExample {
public static void main(String[] args) throws Exception {
// Add BouncyCastle provider
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
// Generate RSA key pair (2048-bit)
KeyPair keyPair = RSA.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Save keys as Base64 strings
String publicKeyStr = RSA.savePublicKey(publicKey);
String privateKeyStr = RSA.savePrivateKey(privateKey);
System.out.println("Public Key: " + publicKeyStr.substring(0, 50) + "...");
// Load keys from strings
PublicKey loadedPublic = RSA.loadPublicKey(publicKeyStr);
PrivateKey loadedPrivate = RSA.loadPrivateKey(privateKeyStr);
// Encrypt and decrypt
byte[] plaintext = "Secret message".getBytes();
byte[] ciphertext = RSA.encrypt(plaintext, publicKey);
byte[] decrypted = RSA.decrypt(ciphertext, privateKey);
System.out.println("Decrypted: " + new String(decrypted));
// Output: Decrypted: Secret message
// Sign and verify
String signature = RSA.sign(plaintext, privateKey);
boolean verified = RSA.verify(plaintext, signature, publicKey);
System.out.println("Signature valid: " + verified);
// Output: Signature valid: true
}
}
```
--------------------------------
### Hash and Verify Passwords
Source: https://context7.com/richkmeli/jframework/llms.txt
Handles secure password hashing with optional salt. Use saltEnabled=false for database storage and saltEnabled=true for login verification.
```java
import it.richkmeli.jframework.crypto.Crypto;
public class PasswordExample {
public static void main(String[] args) {
String password = "userPassword123";
// Hash password for storage (no salt for consistent DB storage)
String hashedForStorage = Crypto.hashPassword(password, false);
System.out.println("Stored hash: " + hashedForStorage);
// Hash password during login (with salt for additional security)
String hashedForLogin = Crypto.hashPassword(password, true);
System.out.println("Login hash: " + hashedForLogin);
// Verify password: compare stored hash with login hash
boolean isValid = Crypto.verifyPassword(hashedForStorage, hashedForLogin);
System.out.println("Password valid: " + isValid);
// Output: Password valid: true
}
}
```
--------------------------------
### Implement AuthDatabaseModel Interface
Source: https://context7.com/richkmeli/jframework/llms.txt
Provides a template for creating a custom authentication database connector by implementing the required CRUD and verification methods.
```java
import it.richkmeli.jframework.auth.data.AuthDatabaseModel;
import it.richkmeli.jframework.auth.data.exception.AuthDatabaseException;
import it.richkmeli.jframework.auth.model.User;
import it.richkmeli.jframework.auth.model.exception.ModelException;
import java.util.List;
public class CustomAuthDatabase implements AuthDatabaseModel {
@Override
public List getAllUsers() throws AuthDatabaseException {
// Return all users from your database
return null; // Implement with actual DB query
}
@Override
public boolean addUser(User user) throws AuthDatabaseException {
// INSERT user into database
System.out.println("Adding user: " + user.getEmail());
return true;
}
@Override
public boolean removeUser(String email) throws AuthDatabaseException, ModelException {
// DELETE user from database
System.out.println("Removing user: " + email);
return true;
}
@Override
public boolean isUserPresent(String email) throws AuthDatabaseException, ModelException {
// Check if user exists
return false; // Implement with actual DB query
}
@Override
public boolean editPassword(String email, String pass) throws AuthDatabaseException, ModelException {
// UPDATE user password
return true;
}
@Override
public boolean editAdmin(String email, Boolean isAdmin) throws AuthDatabaseException, ModelException {
// UPDATE user admin status
return true;
}
@Override
public boolean checkPassword(String email, String pass) throws AuthDatabaseException, ModelException {
// Verify password matches stored hash
return true;
}
@Override
public boolean isAdmin(String email) throws AuthDatabaseException, ModelException {
// Check if user has admin privileges
return false;
}
}
```
--------------------------------
### Add JFramework Maven Repository
Source: https://github.com/richkmeli/jframework/blob/master/README.md
Include this repository configuration in your project's pom.xml to enable fetching JFramework artifacts from GitHub Packages.
```xml
github
https://maven.pkg.github.com/richkmeli/JFramework
```
--------------------------------
### Configure Maven Dependencies for JFramework
Source: https://context7.com/richkmeli/jframework/llms.txt
Add the GitHub repository and specific JFramework dependencies to your pom.xml file to include the full framework or individual modules.
```xml
github
https://maven.pkg.github.com/richkmeli/JFramework
it.richkmeli.jframework
jframework
1.2.18
it.richkmeli.jframework
crypto
1.2.18
it.richkmeli.jframework
auth
1.2.18
it.richkmeli.jframework
orm
1.2.18
it.richkmeli.jframework
network
1.2.18
```
--------------------------------
### Configure Database Manager Properties
Source: https://context7.com/richkmeli/jframework/llms.txt
Defines the database connection settings and driver classes for the ORM module within the configuration.properties file.
```properties
# configuration.properties
database=mysql
# MySQL configuration
database.mysql.username=root
database.mysql.password=secret
database.mysql.url=jdbc:mysql://localhost:3306/
database.mysql.dbtype=mysql
database.mysql.class=com.mysql.cj.jdbc.Driver
# Derby configuration (alternative)
database.derby.username=
database.derby.password=
database.derby.url=jdbc:derby:
database.derby.dbtype=derby
database.derby.class=org.apache.derby.jdbc.EmbeddedDriver
```
--------------------------------
### Include JFramework Dependency
Source: https://github.com/richkmeli/jframework/blob/master/README.md
Add this dependency to your project's pom.xml to include the comprehensive JFramework JAR. Ensure you are using a valid version.
```xml
it.richkmeli.jframework
jframework
1.2.18
```
--------------------------------
### File Management Operations
Source: https://context7.com/richkmeli/jframework/llms.txt
Demonstrates the FileManager class for saving and loading data to/from files. The class automatically creates files if they do not exist and supports loading data using both file paths and File objects. Handles cases where files do not exist by returning an empty string.
```java
import it.richkmeli.jframework.system.FileManager;
import java.io.File;
public class FileManagerExample {
public static void main(String[] args) {
String filePath = "/tmp/myapp/config.json";
// Save data to file (creates file if doesn't exist)
String jsonConfig = "{\"server\":\"localhost\",\"port\":8080,\"debug\":true}";
boolean saved = FileManager.saveDataToFile(filePath, jsonConfig);
if (saved) {
System.out.println("Configuration saved successfully");
} else {
System.err.println("Failed to save configuration");
}
// Load data from file
String loadedData = FileManager.loadDataFromFile(filePath);
if (loadedData != null) {
System.out.println("Loaded config: " + loadedData);
// Output: Loaded config: {"server":"localhost","port":8080,"debug":true}
} else {
System.err.println("Failed to load configuration");
}
// Load from File object
File configFile = new File(filePath);
String configData = FileManager.loadDataFromFile(configFile);
System.out.println("Config from File object: " + configData);
// If file doesn't exist, it will be created and empty string returned
String newFileData = FileManager.loadDataFromFile("/tmp/myapp/newfile.txt");
System.out.println("New file content: '" + newFileData + "'");
// Output: New file content: ''
}
}
```
--------------------------------
### Diffie-Hellman Key Exchange
Source: https://context7.com/richkmeli/jframework/llms.txt
Shows the multi-step process of generating shared secrets between two parties using Diffie-Hellman and AES.
```java
import it.richkmeli.jframework.crypto.algorithm.DiffieHellman;
import it.richkmeli.jframework.crypto.algorithm.AES;
import javax.crypto.SecretKey;
import java.math.BigInteger;
import java.security.KeyPair;
import java.util.List;
public class DHKeyExchangeExample {
public static void main(String[] args) throws Exception {
// Step 1: Party A generates prime and generator
List pg = DiffieHellman.dh0A_GeneratePrimeAndGenerator();
System.out.println("Prime (p) generated: " + pg.get(0).bitLength() + " bits");
// Step 2: Both parties generate their key pairs
KeyPair keyPairA = DiffieHellman.dh1_GenerateKeyPair(pg);
KeyPair keyPairB = DiffieHellman.dh1_GenerateKeyPair(pg);
// Step 3: Exchange public keys and calculate shared secret
// Party A calculates shared secret using B's public key
SecretKey sharedSecretA = DiffieHellman.dh3_CalculateSharedSecretKey(
pg, keyPairB.getPublic(), keyPairA.getPrivate(), AES.ALGORITHM);
// Party B calculates shared secret using A's public key
SecretKey sharedSecretB = DiffieHellman.dh3_CalculateSharedSecretKey(
pg, keyPairA.getPublic(), keyPairB.getPrivate(), AES.ALGORITHM);
// Both parties now have the same shared secret
String secretA = AES.saveSecretKey(sharedSecretA);
String secretB = AES.saveSecretKey(sharedSecretB);
System.out.println("Shared secrets match: " + secretA.equals(secretB));
// Output: Shared secrets match: true
}
}
```
--------------------------------
### Perform AES-256-CBC Encryption and Decryption
Source: https://context7.com/richkmeli/jframework/llms.txt
Uses a password-derived key for AES-256-CBC operations. The implementation automatically manages a 16-byte IV and returns Base64Url encoded strings.
```java
import it.richkmeli.jframework.crypto.Crypto;
import it.richkmeli.jframework.crypto.exception.CryptoException;
public class AESExample {
public static void main(String[] args) {
try {
String secretKey = "mySecurePassword123";
String plaintext = "Sensitive data to encrypt";
// Encrypt data using AES-256-CBC
String encrypted = Crypto.encryptAES(plaintext, secretKey);
System.out.println("Encrypted: " + encrypted);
// Output: Encrypted: SGVsbG8gV29ybGQhIQ... (Base64Url encoded)
// Decrypt data
String decrypted = Crypto.decryptAES(encrypted, secretKey);
System.out.println("Decrypted: " + decrypted);
// Output: Decrypted: Sensitive data to encrypt
} catch (CryptoException e) {
System.err.println("Encryption/Decryption failed: " + e.getMessage());
}
}
}
```
--------------------------------
### Scan Subnet for Active Hosts
Source: https://context7.com/richkmeli/jframework/llms.txt
Utilizes NetworkScanner to perform both asynchronous and synchronous host discovery on a specified subnet.
```java
import it.richkmeli.jframework.network.scan.NetworkScanner;
import java.net.InetAddress;
import java.util.List;
public class NetworkScanExample {
public static void main(String[] args) {
String subnet = "192.168.1"; // Scan 192.168.1.1 - 192.168.1.254
// Async scan (faster, uses threads)
System.out.println("Starting async network scan...");
List activeHosts = NetworkScanner.getActiveHosts(subnet);
System.out.println("Found " + activeHosts.size() + " active hosts:");
for (String host : activeHosts) {
System.out.println(" - " + host);
}
// Output:
// Found 5 active hosts:
// - router (192.168.1.1)
// - desktop-pc (192.168.1.10)
// - laptop (192.168.1.15)
// - ...
// Sync scan (slower but simpler)
System.out.println("\nStarting sync network scan...");
List syncHosts = NetworkScanner.getActiveHostsSync(subnet);
for (InetAddress addr : syncHosts) {
System.out.println(" - " + addr.getCanonicalHostName() +
" (" + addr.getHostAddress() + ")");
}
}
}
```
--------------------------------
### Perform CRUD Operations
Source: https://context7.com/richkmeli/jframework/llms.txt
Use the custom DatabaseManager to execute create, read, update, and delete operations. Wrap calls in try-catch blocks to handle DatabaseException.
```java
import it.richkmeli.jframework.orm.DatabaseException;
import java.util.List;
public class ORMExample {
public static void main(String[] args) {
try {
ProductDatabaseManager db = new ProductDatabaseManager();
// Create products
Product laptop = new Product("PROD001", "Laptop", "High-performance laptop", true);
Product phone = new Product("PROD002", "Smartphone", "Latest smartphone", true);
db.addProduct(laptop);
db.addProduct(phone);
System.out.println("Products created successfully");
// Read single product
Product retrieved = db.getProduct("PROD001");
System.out.println("Retrieved: " + retrieved.getName());
// Output: Retrieved: Laptop
// Read all products
List allProducts = db.getAllProducts();
System.out.println("Total products: " + allProducts.size());
// Output: Total products: 2
// Update product
Product updatedProduct = new Product("PROD001", null, "Updated description", null);
db.updateProduct(updatedProduct);
System.out.println("Product updated");
// Delete product
db.deleteProduct("PROD002");
System.out.println("Product deleted");
} catch (DatabaseException e) {
System.err.println("Database error: " + e.getMessage());
}
}
}
```
--------------------------------
### Generate SHA-256 Hashes
Source: https://context7.com/richkmeli/jframework/llms.txt
Provides SHA-256 hashing for strings and byte arrays. Output is returned as a hexadecimal string.
```java
import it.richkmeli.jframework.crypto.Crypto;
import it.richkmeli.jframework.crypto.algorithm.SHA256;
public class HashingExample {
public static void main(String[] args) {
// Simple string hashing via Crypto facade
String hash = Crypto.hash("password123");
System.out.println("Hash: " + hash);
// Output: Hash: ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
// Hash byte array directly
byte[] data = "Hello World".getBytes();
byte[] hashBytes = SHA256.hash(data);
String hashHex = SHA256.hashToString(data);
System.out.println("Hash (hex): " + hashHex);
// Output: Hash (hex): a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
}
}
```
--------------------------------
### Secure Data Storage
Source: https://context7.com/richkmeli/jframework/llms.txt
Utilizes SecureDataManager to perform encrypted key-value storage operations on a local file.
```java
import it.richkmeli.jframework.crypto.Crypto;
import java.io.File;
public class SecureStorageExample {
public static void main(String[] args) {
File secureFile = new File("secure_data.enc");
String secretKey = "myMasterKey123";
// Store encrypted data
Crypto.putData(secureFile, secretKey, "api_key", "sk-abc123xyz");
Crypto.putData(secureFile, secretKey, "database_password", "dbPass456");
// Retrieve encrypted data
String apiKey = Crypto.getData(secureFile, secretKey, "api_key");
String dbPassword = Crypto.getData(secureFile, secretKey, "database_password");
System.out.println("Retrieved API Key: " + apiKey);
// Output: Retrieved API Key: sk-abc123xyz
System.out.println("Retrieved DB Password: " + dbPassword);
// Output: Retrieved DB Password: dbPass456
}
}
```
--------------------------------
### Generate Random Strings
Source: https://context7.com/richkmeli/jframework/llms.txt
Utilizes RandomStringGenerator to create secure random strings of various types, including alphanumeric, numeric, lowercase, UTF-8, UTF-16, and ASCII. Specify the desired length and character set.
```java
import it.richkmeli.jframework.util.RandomStringGenerator;
public class RandomGeneratorExample {
public static void main(String[] args) {
// Generate alphanumeric string (a-z, A-Z, 0-9)
String alphanumeric = RandomStringGenerator.generateAlphanumericString(16);
System.out.println("API Key: " + alphanumeric);
// Output: API Key: Kj7mN2pQ9xR4tY6w
// Generate numeric string (0-9 only)
String numeric = RandomStringGenerator.generateNumericString(6);
System.out.println("OTP Code: " + numeric);
// Output: OTP Code: 847293
// Generate bounded string with custom character range
// ASCII 97-122 = lowercase letters (a-z)
String lowercase = RandomStringGenerator.generateBoundedString(10, 97, 122);
System.out.println("Lowercase: " + lowercase);
// Output: Lowercase: qwertasdfg
// Generate UTF-8 string
String utf8 = RandomStringGenerator.generateUtf8String(8);
System.out.println("UTF-8: " + utf8);
// Generate UTF-16 string
String utf16 = RandomStringGenerator.generateUtf16String(8);
System.out.println("UTF-16: " + utf16);
// Generate ASCII string
String ascii = RandomStringGenerator.generateASCIItring(8);
System.out.println("ASCII: " + ascii);
}
}
```
--------------------------------
### Define Entity with @Id Annotation
Source: https://context7.com/richkmeli/jframework/llms.txt
Mark primary key fields with the @Id annotation. Ensure all fields have corresponding getters, setters, and a full constructor for ORM reflection.
```java
import it.richkmeli.jframework.orm.annotation.Id;
public class Product {
@Id
private String productId;
private String name;
private String description;
private Boolean active;
// Constructor with all fields (required for ORM reflection)
public Product(String productId, String name, String description, Boolean active) {
this.productId = productId;
this.name = name;
this.description = description;
this.active = active;
}
// Getters and setters (required for ORM)
public String getProductId() { return productId; }
public void setProductId(String productId) { this.productId = productId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Boolean getActive() { return active; }
public void setActive(Boolean active) { this.active = active; }
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.