View Javadoc
1   package com.guinetik.examples;
2   
3   import com.guinetik.rr.RocketRest;
4   import com.guinetik.rr.RocketRestConfig;
5   import com.guinetik.rr.RocketRestOptions;
6   import com.guinetik.rr.auth.AuthStrategy;
7   import com.guinetik.rr.auth.AuthStrategyFactory;
8   
9   import java.util.Scanner;
10  
11  /**
12   * Example demonstrating SAP IDP authentication and API usage.
13   * This example:
14   * 1. Prompts for SAP IDP credentials
15   * 2. Authenticates using IDP
16   * 3. Prints access token
17   * 4. Makes a test API call
18   */
19  public class SapIdpExample implements Example {
20  
21      private String clientId;
22      private String userId;
23      private String privateKey;
24      private String companyId;
25      private String grantType;
26      private String idpUrl;
27      private String tokenUrl;
28      private String baseUrl;
29      private String endpoint;
30  
31      static {
32          System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "DEBUG");
33      }
34  
35      public static void main(String[] args) {
36          SapIdpExample example = new SapIdpExample();
37  
38          // Read values from environment variables
39          example.clientId = System.getenv("SAP_CLIENT_ID");
40          example.userId = System.getenv("SAP_USER_ID");
41          example.privateKey = System.getenv("SAP_PRIVATE_KEY");
42          example.companyId = System.getenv("SAP_COMPANY_ID");
43          example.grantType = System.getenv("SAP_GRANT_TYPE");
44          example.idpUrl = System.getenv("SAP_IDP_URL");
45          example.tokenUrl = System.getenv("SAP_TOKEN_URL");
46          example.baseUrl = System.getenv("SAP_BASE_URL");
47  
48          example.run();
49      }
50      
51      @Override
52      public String getName() {
53          return "SAP IDP Authentication Example";
54      }
55  
56      @Override
57      public void run() {
58          System.out.println("\n=== SAP IDP Authentication Example ===");
59          System.out.println("This example demonstrates connecting to SAP's API using RocketRest with:");
60          System.out.println("1. OAuth2 SAML2 Bearer flow via SAP IDP");
61          System.out.println("2. Secure authentication to access SAP's SuccessFactors APIs");
62          System.out.println();
63          System.out.println("You can set these environment variables before running to skip manual input:");
64          System.out.println("- SAP_CLIENT_ID");
65          System.out.println("- SAP_USER_ID");
66          System.out.println("- SAP_PRIVATE_KEY");
67          System.out.println("- SAP_COMPANY_ID");
68          System.out.println("- SAP_GRANT_TYPE");
69          System.out.println("- SAP_IDP_URL");
70          System.out.println("- SAP_TOKEN_URL");
71          System.out.println("- SAP_BASE_URL");
72          System.out.println("\n-----------------------------------------\n");
73  
74          try (Scanner scanner = new Scanner(System.in)) {
75              // Get SAP IDP credentials
76              if( this.clientId == null || this.clientId.trim().isEmpty() ) {
77                  System.out.println("\nEnter SAP IDP credentials:");
78                  System.out.print("Client ID: ");
79                  this.clientId = scanner.nextLine();
80              }
81              
82              if( this.userId == null || this.userId.trim().isEmpty() ) {
83                  System.out.print("User ID: ");
84                  this.userId = scanner.nextLine();
85              }
86              
87              if( this.privateKey == null || this.privateKey.trim().isEmpty() ) {
88                  System.out.print("Private Key: ");
89                  this.privateKey = scanner.nextLine();
90              }
91              
92              if( this.companyId == null || this.companyId.trim().isEmpty() ) {
93                  System.out.print("Company ID (optional, press Enter to skip): ");
94                  this.companyId = scanner.nextLine();
95                  if (this.companyId.trim().isEmpty()) {
96                      this.companyId = null;
97                  }
98              }
99              
100             if( this.grantType == null || this.grantType.trim().isEmpty() ) {
101                 System.out.print("Grant Type: ");
102                 this.grantType = scanner.nextLine();
103             }
104             
105             if( this.idpUrl == null || this.idpUrl.trim().isEmpty() ) {
106                 System.out.print("IDP URL: ");
107                 this.idpUrl = scanner.nextLine();
108             }
109             
110             if( this.tokenUrl == null || this.tokenUrl.trim().isEmpty() ) {
111                 System.out.print("Token URL: ");
112                 this.tokenUrl = scanner.nextLine();
113             }
114             
115             if( this.baseUrl == null || this.baseUrl.trim().isEmpty() ) {
116                 System.out.print("SAP API Base URL: ");
117                 this.baseUrl = scanner.nextLine();
118             }
119             
120             System.out.print("API Endpoint (press Enter to use default '/User?$top=1&$format=json&$select=userId'): ");
121             this.endpoint = scanner.nextLine();
122             if (this.endpoint.trim().isEmpty()) {
123                 this.endpoint = "/User?$top=1&$format=json&$select=userId";
124             }
125 
126             // Create IDP auth strategy
127             AuthStrategy authStrategy = AuthStrategyFactory.createOAuth2Assertion(
128                 this.clientId,
129                     this.userId,
130                     this.privateKey,
131                     this.companyId,
132                     this.grantType,
133                     this.idpUrl,
134                     this.tokenUrl
135             );
136 
137             System.out.println("Refreshing SAP Token");
138             authStrategy.refreshCredentials();
139 
140             // Create RocketRest client
141             RocketRest client = new RocketRest(
142                 RocketRestConfig.builder(this.baseUrl)
143                         .defaultOptions(options -> {
144                             options.set(RocketRestOptions.RETRY_ENABLED, true);
145                             options.set(RocketRestOptions.MAX_RETRIES, 3);
146                             options.set(RocketRestOptions.LOG_REQUEST_BODY, true);
147                             options.set(RocketRestOptions.LOG_RESPONSE_BODY, true);
148                         })
149                     .tokenUrl(this.tokenUrl)
150                     .authStrategy(authStrategy)
151                     .tokenUrl(this.tokenUrl)
152                     .build()
153             );
154 
155             // Print access token
156             System.out.println("\nAccess Token:");
157             System.out.println(client.getAccessToken());
158 
159             // Print Expiration
160             System.out.println("\nExpiration:");
161             System.out.println(client.getTokenExpiryTime());
162 
163             // Make API call
164             System.out.println("\nMaking API call to: " + this.endpoint);
165             try {
166                 String response = client.get(this.endpoint, String.class);
167                 // Pretty print the response
168                 System.out.println("\nAPI Response:");
169                 System.out.println(response);
170             } catch (Exception e) {
171                 System.err.println("Error: " + e.getMessage());
172                 e.printStackTrace();
173             } finally {
174                 // Always shutdown the client to release resources
175                 client.shutdown();
176             }
177 
178         } catch (Exception e) {
179             System.err.println("Error: " + e.getMessage());
180             e.printStackTrace();
181         }
182     }
183 }