import java.time.Duration;
import java.time.Instant;
import java.util.Random;
public class TokenPerformanceTest {
private static final int NUM_ITERATIONS = 1000; // Number of authentication attempts
private static final String TEST_ENDPOINT = "https://example.com/api/protected"; // Replace with your test endpoint
public static void main(String[] args) throws Exception {
// Simulate token retrieval (replace with your actual token retrieval logic)
String token = retrieveToken();
// Start timing
Instant startTime = Instant.now();
// Perform authentication attempts
for (int i = 0; i < NUM_ITERATIONS; i++) {
try {
authenticate(token); // Replace with your authentication function
} catch (Exception e) {
System.err.println("Authentication failed: " + e.getMessage()); // Log errors
e.printStackTrace();
}
}
// Stop timing
Instant endTime = Instant.now();
// Calculate duration
Duration duration = Duration.between(startTime, endTime);
// Log results
logPerformance(token, duration.toMillis());
}
// Simulate token retrieval (replace with your actual logic)
private static String retrieveToken() {
// In a real scenario, this would involve fetching a token from an authentication server
// For testing, we'll just generate a random token.
return generateRandomToken();
}
// Generates a random token (for testing purposes)
private static String generateRandomToken() {
Random random = new Random();
return "token-" + random.nextInt(1000000); //Example token
}
// Simulate authentication (replace with your actual authentication logic)
private static void authenticate(String token) throws Exception {
// In a real scenario, this would involve sending the token to the authentication server
// and receiving a response.
// For testing, we'll just simulate a successful authentication.
// Replace this with your actual authentication call.
System.out.println("Authenticating with token: " + token);
//Simulate network latency
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// Logs performance results
private static void logPerformance(String token, long durationMillis) {
System.out.println("------------------------------------");
System.out.println("Token: " + token);
System.out.println("Number of iterations: " + NUM_ITERATIONS);
System.out.println("Total time: " + durationMillis + " ms");
System.out.println("Average time per iteration: " + (double) durationMillis / NUM_ITERATIONS + " ms");
System.out.println("------------------------------------");
}
}
Add your comment