1. import java.time.Duration;
  2. import java.time.Instant;
  3. import java.util.Random;
  4. public class TokenPerformanceTest {
  5. private static final int NUM_ITERATIONS = 1000; // Number of authentication attempts
  6. private static final String TEST_ENDPOINT = "https://example.com/api/protected"; // Replace with your test endpoint
  7. public static void main(String[] args) throws Exception {
  8. // Simulate token retrieval (replace with your actual token retrieval logic)
  9. String token = retrieveToken();
  10. // Start timing
  11. Instant startTime = Instant.now();
  12. // Perform authentication attempts
  13. for (int i = 0; i < NUM_ITERATIONS; i++) {
  14. try {
  15. authenticate(token); // Replace with your authentication function
  16. } catch (Exception e) {
  17. System.err.println("Authentication failed: " + e.getMessage()); // Log errors
  18. e.printStackTrace();
  19. }
  20. }
  21. // Stop timing
  22. Instant endTime = Instant.now();
  23. // Calculate duration
  24. Duration duration = Duration.between(startTime, endTime);
  25. // Log results
  26. logPerformance(token, duration.toMillis());
  27. }
  28. // Simulate token retrieval (replace with your actual logic)
  29. private static String retrieveToken() {
  30. // In a real scenario, this would involve fetching a token from an authentication server
  31. // For testing, we'll just generate a random token.
  32. return generateRandomToken();
  33. }
  34. // Generates a random token (for testing purposes)
  35. private static String generateRandomToken() {
  36. Random random = new Random();
  37. return "token-" + random.nextInt(1000000); //Example token
  38. }
  39. // Simulate authentication (replace with your actual authentication logic)
  40. private static void authenticate(String token) throws Exception {
  41. // In a real scenario, this would involve sending the token to the authentication server
  42. // and receiving a response.
  43. // For testing, we'll just simulate a successful authentication.
  44. // Replace this with your actual authentication call.
  45. System.out.println("Authenticating with token: " + token);
  46. //Simulate network latency
  47. try {
  48. Thread.sleep(1);
  49. } catch (InterruptedException e) {
  50. Thread.currentThread().interrupt();
  51. }
  52. }
  53. // Logs performance results
  54. private static void logPerformance(String token, long durationMillis) {
  55. System.out.println("------------------------------------");
  56. System.out.println("Token: " + token);
  57. System.out.println("Number of iterations: " + NUM_ITERATIONS);
  58. System.out.println("Total time: " + durationMillis + " ms");
  59. System.out.println("Average time per iteration: " + (double) durationMillis / NUM_ITERATIONS + " ms");
  60. System.out.println("------------------------------------");
  61. }
  62. }

Add your comment