diff options
author | Instrumental <jonathan.gathman@att.com> | 2018-09-07 12:21:34 -0500 |
---|---|---|
committer | Instrumental <jonathan.gathman@att.com> | 2018-09-07 12:22:50 -0500 |
commit | 4b5a7d721d994a49057e9bfb403c7bff1b376660 (patch) | |
tree | a36d03227b63a3e60346d6c3ca87b061087dae85 /cadi/oauth-enduser/src/test | |
parent | 824dc7b5fc0e1ccdf7f460479aff344727f0f01e (diff) |
Mass removal of all Tabs (Style Warnings)
Issue-ID: AAF-473
Change-Id: Iaf0ef8120882937959bb0065f2f6ba74a021940f
Signed-off-by: Instrumental <jonathan.gathman@att.com>
Diffstat (limited to 'cadi/oauth-enduser/src/test')
3 files changed, 509 insertions, 509 deletions
diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java index ae9c93ed..154ba1b7 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java @@ -50,187 +50,187 @@ import aafoauth.v2_0.Token; public class OAuthExample { - private static TokenClientFactory tcf; - private static PropAccess access; + private static TokenClientFactory tcf; + private static PropAccess access; - public final static void main(final String args[]) { - // These Objects are expected to be Long-Lived... Construct once - - // Property Access - // This method will allow you to set "cadi_prop_files" (or any other property) on Command line - access = new PropAccess(args); - - // access = PropAccess(); - // Note: This style will load "cadi_prop_files" from VM Args - - // Token aware Client Factory - try { - tcf = TokenClientFactory.instance(access); - } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { - access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); - System.exit(1); - } - - - // Obtain Endpoints for OAuth2 from Properties. Expected is "cadi.properties" file, pointed to by "cadi_prop_files" - String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,Defaults.OAUTH2_TOKEN_URL); // Default to AAF - String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,Defaults.OAUTH2_INTROSPECT_URL); // Default to AAF); - // Get Hello Service - final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL,Defaults.HELLO_URL); + public final static void main(final String args[]) { + // These Objects are expected to be Long-Lived... Construct once + + // Property Access + // This method will allow you to set "cadi_prop_files" (or any other property) on Command line + access = new PropAccess(args); + + // access = PropAccess(); + // Note: This style will load "cadi_prop_files" from VM Args + + // Token aware Client Factory + try { + tcf = TokenClientFactory.instance(access); + } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { + access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); + System.exit(1); + } + + + // Obtain Endpoints for OAuth2 from Properties. Expected is "cadi.properties" file, pointed to by "cadi_prop_files" + String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,Defaults.OAUTH2_TOKEN_URL); // Default to AAF + String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,Defaults.OAUTH2_INTROSPECT_URL); // Default to AAF); + // Get Hello Service + final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL,Defaults.HELLO_URL); - final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); - - try { - ////////////////////////////////////////////////////////////////////// - // Scenario 1: - // Get and use an OAuth Client, which understands Token Management - ////////////////////////////////////////////////////////////////////// - // Create a Token Client, that gets its tokens from expected OAuth Server - // In this example, it is AAF, but it can be the Alternate OAuth + final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); + + try { + ////////////////////////////////////////////////////////////////////// + // Scenario 1: + // Get and use an OAuth Client, which understands Token Management + ////////////////////////////////////////////////////////////////////// + // Create a Token Client, that gets its tokens from expected OAuth Server + // In this example, it is AAF, but it can be the Alternate OAuth - TokenClient tc = tcf.newClient(tokenServiceURL); // can set your own timeout here (url, timeoutMilliseconds) - // Set your Application (MicroService, whatever) Credentials here - // These are how your Application is known, particularly to the OAuth Server. - // If AAF Token server, then its just the same as your other AAF MechID creds - // If it is the Alternate OAUTH, you'll need THOSE credentials. See that tool's Onboarding procedures. - String client_id = access.getProperty(Config.AAF_APPID); - if(client_id==null) { - // For AAF, client_id CAN be Certificate. This is not necessarily true elsewhere - client_id = access.getProperty(Config.CADI_ALIAS); - } - String client_secret = access.getProperty(Config.AAF_APPPASS); - tc.client_creds(client_id, client_secret); - - // If you are working with Credentials the End User, set username/password as appropriate to the OAuth Server - // tc.password(end_user_id, end_user_password); - // IMPORTANT: - // if you are setting client Credentials, you MAY NOT reuse this Client mid-transaction. You CAN reuse after setting - // tc.clearEndUser(); - // You may want to see "Pooled Client" example, using special CADI utility + TokenClient tc = tcf.newClient(tokenServiceURL); // can set your own timeout here (url, timeoutMilliseconds) + // Set your Application (MicroService, whatever) Credentials here + // These are how your Application is known, particularly to the OAuth Server. + // If AAF Token server, then its just the same as your other AAF MechID creds + // If it is the Alternate OAUTH, you'll need THOSE credentials. See that tool's Onboarding procedures. + String client_id = access.getProperty(Config.AAF_APPID); + if(client_id==null) { + // For AAF, client_id CAN be Certificate. This is not necessarily true elsewhere + client_id = access.getProperty(Config.CADI_ALIAS); + } + String client_secret = access.getProperty(Config.AAF_APPPASS); + tc.client_creds(client_id, client_secret); + + // If you are working with Credentials the End User, set username/password as appropriate to the OAuth Server + // tc.password(end_user_id, end_user_password); + // IMPORTANT: + // if you are setting client Credentials, you MAY NOT reuse this Client mid-transaction. You CAN reuse after setting + // tc.clearEndUser(); + // You may want to see "Pooled Client" example, using special CADI utility - // With AAF, the Scopes you put in are the AAF Namespaces you want access to. Your Token will contain the - // AAF Permissions of the Namespaces (you can put in more than one), the user name (or client_id if no user_name), - // is allowed to see. - - // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID) - String ns = FQI.reverseDomain(client_id); - System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",client_id, ns); + // With AAF, the Scopes you put in are the AAF Namespaces you want access to. Your Token will contain the + // AAF Permissions of the Namespaces (you can put in more than one), the user name (or client_id if no user_name), + // is allowed to see. + + // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID) + String ns = FQI.reverseDomain(client_id); + System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",client_id, ns); - // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in - // Note: getToken checks if Token is expired, if so, then refreshes before handing back. - Result<TimedToken> rtt = tc.getToken(ns,"org.onap.test"); - - // Note: you can clear a Token's Disk/Memory presence by - // 1) removing the Token from the "token/outgoing" directory on the O/S - // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set - // tc.clearToken("org.onap.aaf","org.onap.test"); - - // Result Object can be queried for success - if(rtt.isOK()) { - TimedToken token = rtt.value; - print(token); // Take a look at what's in a Token - - // Use this Token in your client calls with "Tokenized Client" (TzClient) - // These should NOT be used cross thread. - TzClient helloClient = tcf.newTzClient(endServicesURL); - helloClient.setToken(client_id, token); - - // This client call style, "best" call with "Retryable" inner class covers finding an available Service - // (when Multi-services exist) for the best service, based (currently) on distance. - // - // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method - // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" - String rv = helloClient.best(new Retryable<String>() { - @Override - public String code(Rcli<?> client) throws CadiException, ConnectException, APIException { - Future<String> future = client.read("hello","text/plain"); - // The "future" calling method allows you to do other processing, such as call more than one backend - // client before picking up the result - // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then - if(future.get(CALL_TIMEOUT)) { - // Client Returned expected value - return future.value; - } else { - throw new APIException(future.code() + future.body()); - } - } - }); - - // You want to do something with returned value. Here, we say "hello" - System.out.printf("\nPositive Response from Hello: %s\n",rv); - - - ////////////////////////////////////////////////////////////////////// - // Scenario 2: - // As a Service, read Introspection information as proof of Authenticated Authorization - ////////////////////////////////////////////////////////////////////// - // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( - // i.e. if(isUserInRole("ns.perm|instance|action")) {... - // - // Here, however, is a way to introspect via Java - // - // now, call Introspect (making sure right URLs are set in properties) - // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) - TokenClient tci = tcf.newClient(tokenIntrospectURL); - tci.client_creds(client_id, client_secret); - Result<Introspect> is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { - // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure - print(is.value); // do something with Introspect Object - } else { - access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", - token.getAccessToken(),rtt.code,rtt.error); - } - } else { - access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); - } - - } catch (CadiException | LocatorException | APIException | IOException e) { - e.printStackTrace(); - } - } - - ///////////////////////////////////////////////////////////// - // Examples of Object Access - ///////////////////////////////////////////////////////////// - private static void print(Token t) { - GregorianCalendar exp_date = new GregorianCalendar(); - exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); - System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", - t.getAccessToken(), - t.getTokenType(), - t.getExpiresIn(), - Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), - t.getScope(), - t.getRefreshToken()); - } - - private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { - System.out.println("Empty Introspect"); - return; - } - Date exp = new Date(ti.getExp()*1000); // seconds - System.out.printf("Introspect\n" - + "\tAccessToken:\t%s\n" - + "\tClient-id:\t%s\n" - + "\tClient Type:\t%s\n" - + "\tActive: \t%s\n" - + "\tUserName:\t%s\n" - + "\tExpires: \t%d (%s)\n" - + "\tScope:\t\t%s\n" - + "\tContent:\t%s\n", - ti.getAccessToken(), - ti.getClientId(), - ti.getClientType(), - ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), - ti.getUsername(), - ti.getExp(), - Chrono.timeStamp(exp), - ti.getScope(), - ti.getContent()==null?"":ti.getContent()); - - System.out.println(); - } + // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in + // Note: getToken checks if Token is expired, if so, then refreshes before handing back. + Result<TimedToken> rtt = tc.getToken(ns,"org.onap.test"); + + // Note: you can clear a Token's Disk/Memory presence by + // 1) removing the Token from the "token/outgoing" directory on the O/S + // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set + // tc.clearToken("org.onap.aaf","org.onap.test"); + + // Result Object can be queried for success + if(rtt.isOK()) { + TimedToken token = rtt.value; + print(token); // Take a look at what's in a Token + + // Use this Token in your client calls with "Tokenized Client" (TzClient) + // These should NOT be used cross thread. + TzClient helloClient = tcf.newTzClient(endServicesURL); + helloClient.setToken(client_id, token); + + // This client call style, "best" call with "Retryable" inner class covers finding an available Service + // (when Multi-services exist) for the best service, based (currently) on distance. + // + // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method + // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" + String rv = helloClient.best(new Retryable<String>() { + @Override + public String code(Rcli<?> client) throws CadiException, ConnectException, APIException { + Future<String> future = client.read("hello","text/plain"); + // The "future" calling method allows you to do other processing, such as call more than one backend + // client before picking up the result + // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then + if(future.get(CALL_TIMEOUT)) { + // Client Returned expected value + return future.value; + } else { + throw new APIException(future.code() + future.body()); + } + } + }); + + // You want to do something with returned value. Here, we say "hello" + System.out.printf("\nPositive Response from Hello: %s\n",rv); + + + ////////////////////////////////////////////////////////////////////// + // Scenario 2: + // As a Service, read Introspection information as proof of Authenticated Authorization + ////////////////////////////////////////////////////////////////////// + // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( + // i.e. if(isUserInRole("ns.perm|instance|action")) {... + // + // Here, however, is a way to introspect via Java + // + // now, call Introspect (making sure right URLs are set in properties) + // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) + TokenClient tci = tcf.newClient(tokenIntrospectURL); + tci.client_creds(client_id, client_secret); + Result<Introspect> is = tci.introspect(token.getAccessToken()); + if(is.isOK()) { + // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure + print(is.value); // do something with Introspect Object + } else { + access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", + token.getAccessToken(),rtt.code,rtt.error); + } + } else { + access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); + } + + } catch (CadiException | LocatorException | APIException | IOException e) { + e.printStackTrace(); + } + } + + ///////////////////////////////////////////////////////////// + // Examples of Object Access + ///////////////////////////////////////////////////////////// + private static void print(Token t) { + GregorianCalendar exp_date = new GregorianCalendar(); + exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); + System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", + t.getAccessToken(), + t.getTokenType(), + t.getExpiresIn(), + Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), + t.getScope(), + t.getRefreshToken()); + } + + private static void print(Introspect ti) { + if(ti==null || ti.getClientId()==null) { + System.out.println("Empty Introspect"); + return; + } + Date exp = new Date(ti.getExp()*1000); // seconds + System.out.printf("Introspect\n" + + "\tAccessToken:\t%s\n" + + "\tClient-id:\t%s\n" + + "\tClient Type:\t%s\n" + + "\tActive: \t%s\n" + + "\tUserName:\t%s\n" + + "\tExpires: \t%d (%s)\n" + + "\tScope:\t\t%s\n" + + "\tContent:\t%s\n", + ti.getAccessToken(), + ti.getClientId(), + ti.getClientType(), + ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), + ti.getUsername(), + ti.getExp(), + Chrono.timeStamp(exp), + ti.getScope(), + ti.getContent()==null?"":ti.getContent()); + + System.out.println(); + } } diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java index c82a7c5d..657a9b78 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java @@ -50,161 +50,161 @@ import aafoauth.v2_0.Token; public class OnapClientExample { - private static TokenClientFactory tcf; - private static PropAccess access; + private static TokenClientFactory tcf; + private static PropAccess access; - public final static void main(final String args[]) { - // These Objects are expected to be Long-Lived... Construct once - - // Property Access - // This method will allow you to set "cadi_prop_files" (or any other property) on Command line - access = new PropAccess(args); - - // access = PropAccess(); - // Note: This style will load "cadi_prop_files" from VM Args - - // Token aware Client Factory - try { - tcf = TokenClientFactory.instance(access); - } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { - access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); - System.exit(1); - } - - final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); - - try { - ////////////////////////////////////////////////////////////////////// - // Scenario 1: - // Get and use an OAuth Client, which understands Token Management - ////////////////////////////////////////////////////////////////////// - // Create a Token Client, that gets its tokens from expected OAuth Server - // In this example, it is AAF, but it can be the Alternate OAuth + public final static void main(final String args[]) { + // These Objects are expected to be Long-Lived... Construct once + + // Property Access + // This method will allow you to set "cadi_prop_files" (or any other property) on Command line + access = new PropAccess(args); + + // access = PropAccess(); + // Note: This style will load "cadi_prop_files" from VM Args + + // Token aware Client Factory + try { + tcf = TokenClientFactory.instance(access); + } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { + access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); + System.exit(1); + } + + final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); + + try { + ////////////////////////////////////////////////////////////////////// + // Scenario 1: + // Get and use an OAuth Client, which understands Token Management + ////////////////////////////////////////////////////////////////////// + // Create a Token Client, that gets its tokens from expected OAuth Server + // In this example, it is AAF, but it can be the Alternate OAuth - TokenClient tc = tcf.newClient(Config.AAF_OAUTH2_TOKEN_URL); // can set your own timeout here (url, timeoutMilliseconds) - - // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID) - String ns = FQI.reverseDomain(tc.client_id()); - System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",tc.client_id(), ns); + TokenClient tc = tcf.newClient(Config.AAF_OAUTH2_TOKEN_URL); // can set your own timeout here (url, timeoutMilliseconds) + + // Here's a trick to get the namespace out of a Fully Qualified AAF Identity (your MechID) + String ns = FQI.reverseDomain(tc.client_id()); + System.out.printf("\nNote: The AAF Namespace of FQI (Fully Qualified Identity) %s is %s\n\n",tc.client_id(), ns); - // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in - // Note: getToken checks if Token is expired, if so, then refreshes before handing back. - Result<TimedToken> rtt = tc.getToken(ns,"org.onap.test"); // get multiple scopes - - // Note: you can clear a Token's Disk/Memory presence by - // 1) removing the Token from the "token/outgoing" directory on the O/S - // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set - // tc.clearToken("org.onap.aaf","org.onap.test"); - - // Result Object can be queried for success - if(rtt.isOK()) { - TimedToken token = rtt.value; - print(token); // Take a look at what's in a Token - - // Use this Token in your client calls with "Tokenized Client" (TzClient) - // These should NOT be used cross thread. - // Get Hello Service URL... roll your own in your own world. - final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL,Defaults.HELLO_URL); + // Now, we can get a Token. Note: for "scope", use AAF Namespaces to get AAF Permissions embedded in + // Note: getToken checks if Token is expired, if so, then refreshes before handing back. + Result<TimedToken> rtt = tc.getToken(ns,"org.onap.test"); // get multiple scopes + + // Note: you can clear a Token's Disk/Memory presence by + // 1) removing the Token from the "token/outgoing" directory on the O/S + // 2) programmatically by calling "clearToken" with exact params as "getToken", when it has the same credentials set + // tc.clearToken("org.onap.aaf","org.onap.test"); + + // Result Object can be queried for success + if(rtt.isOK()) { + TimedToken token = rtt.value; + print(token); // Take a look at what's in a Token + + // Use this Token in your client calls with "Tokenized Client" (TzClient) + // These should NOT be used cross thread. + // Get Hello Service URL... roll your own in your own world. + final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL,Defaults.HELLO_URL); - TzClient helloClient = tcf.newTzClient(endServicesURL); - helloClient.setToken(tc.client_id(), token); - - // This client call style, "best" call with "Retryable" inner class covers finding an available Service - // (when Multi-services exist) for the best service, based (currently) on distance. - // - // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method - // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" - String rv = helloClient.best(new Retryable<String>() { - @Override - public String code(Rcli<?> client) throws CadiException, ConnectException, APIException { - Future<String> future = client.read("hello","text/plain"); - // The "future" calling method allows you to do other processing, such as call more than one backend - // client before picking up the result - // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then - if(future.get(CALL_TIMEOUT)) { - // Client Returned expected value - return future.value; - } else { - throw new APIException(future.code() + future.body()); - } - } - }); - - // You want to do something with returned value. Here, we say "hello" - System.out.printf("\nPositive Response from Hello: %s\n",rv); - - - ////////////////////////////////////////////////////////////////////// - // Scenario 2: - // As a Service, read Introspection information as proof of Authenticated Authorization - ////////////////////////////////////////////////////////////////////// - // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( - // i.e. if(isUserInRole("ns.perm|instance|action")) {... - // - // Here, however, is a way to introspect via Java - // - // now, call Introspect (making sure right URLs are set in properties) - // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) - TokenClient tci = tcf.newClient(Config.AAF_OAUTH2_INTROSPECT_URL); - Result<Introspect> is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { - // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure - print(is.value); // do something with Introspect Object - } else { - access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", - token.getAccessToken(),rtt.code,rtt.error); - } - } else { - access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); - } - - } catch (CadiException | LocatorException | APIException | IOException e) { - e.printStackTrace(); - } - } - - ///////////////////////////////////////////////////////////// - // Examples of Object Access - ///////////////////////////////////////////////////////////// - private static void print(Token t) { - GregorianCalendar exp_date = new GregorianCalendar(); - exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); - System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", - t.getAccessToken(), - t.getTokenType(), - t.getExpiresIn(), - Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), - t.getScope(), - t.getRefreshToken()); - } - - private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { - System.out.println("Empty Introspect"); - return; - } - Date exp = new Date(ti.getExp()*1000); // seconds - System.out.printf("Introspect\n" - + "\tAccessToken:\t%s\n" - + "\tClient-id:\t%s\n" - + "\tClient Type:\t%s\n" - + "\tActive: \t%s\n" - + "\tUserName:\t%s\n" - + "\tExpires: \t%d (%s)\n" - + "\tScope:\t\t%s\n" - + "\tContent:\t%s\n", - ti.getAccessToken(), - ti.getClientId(), - ti.getClientType(), - ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), - ti.getUsername(), - ti.getExp(), - Chrono.timeStamp(exp), - ti.getScope(), - ti.getContent()==null?"":ti.getContent()); - - System.out.println(); - } + TzClient helloClient = tcf.newTzClient(endServicesURL); + helloClient.setToken(tc.client_id(), token); + + // This client call style, "best" call with "Retryable" inner class covers finding an available Service + // (when Multi-services exist) for the best service, based (currently) on distance. + // + // the "Generic" in Type gives a Return Value for the Code, which you can set on the "best" method + // Note that variables used in the inner class from this part of the code must be "final", see "CALL_TIMEOUT" + String rv = helloClient.best(new Retryable<String>() { + @Override + public String code(Rcli<?> client) throws CadiException, ConnectException, APIException { + Future<String> future = client.read("hello","text/plain"); + // The "future" calling method allows you to do other processing, such as call more than one backend + // client before picking up the result + // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then + if(future.get(CALL_TIMEOUT)) { + // Client Returned expected value + return future.value; + } else { + throw new APIException(future.code() + future.body()); + } + } + }); + + // You want to do something with returned value. Here, we say "hello" + System.out.printf("\nPositive Response from Hello: %s\n",rv); + + + ////////////////////////////////////////////////////////////////////// + // Scenario 2: + // As a Service, read Introspection information as proof of Authenticated Authorization + ////////////////////////////////////////////////////////////////////// + // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( + // i.e. if(isUserInRole("ns.perm|instance|action")) {... + // + // Here, however, is a way to introspect via Java + // + // now, call Introspect (making sure right URLs are set in properties) + // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) + TokenClient tci = tcf.newClient(Config.AAF_OAUTH2_INTROSPECT_URL); + Result<Introspect> is = tci.introspect(token.getAccessToken()); + if(is.isOK()) { + // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure + print(is.value); // do something with Introspect Object + } else { + access.printf(Level.ERROR, "Unable to introspect OAuth Token %s: %d %s\n", + token.getAccessToken(),rtt.code,rtt.error); + } + } else { + access.printf(Level.ERROR, "Unable to obtain OAuth Token: %d %s\n",rtt.code,rtt.error); + } + + } catch (CadiException | LocatorException | APIException | IOException e) { + e.printStackTrace(); + } + } + + ///////////////////////////////////////////////////////////// + // Examples of Object Access + ///////////////////////////////////////////////////////////// + private static void print(Token t) { + GregorianCalendar exp_date = new GregorianCalendar(); + exp_date.add(GregorianCalendar.SECOND, t.getExpiresIn()); + System.out.printf("Access Token\n\tToken:\t\t%s\n\tToken Type:\t%s\n\tExpires In:\t%d (%s)\n\tScope:\t\t%s\n\tRefresh Token:\t%s\n", + t.getAccessToken(), + t.getTokenType(), + t.getExpiresIn(), + Chrono.timeStamp(new Date(System.currentTimeMillis()+(t.getExpiresIn()*1000))), + t.getScope(), + t.getRefreshToken()); + } + + private static void print(Introspect ti) { + if(ti==null || ti.getClientId()==null) { + System.out.println("Empty Introspect"); + return; + } + Date exp = new Date(ti.getExp()*1000); // seconds + System.out.printf("Introspect\n" + + "\tAccessToken:\t%s\n" + + "\tClient-id:\t%s\n" + + "\tClient Type:\t%s\n" + + "\tActive: \t%s\n" + + "\tUserName:\t%s\n" + + "\tExpires: \t%d (%s)\n" + + "\tScope:\t\t%s\n" + + "\tContent:\t%s\n", + ti.getAccessToken(), + ti.getClientId(), + ti.getClientType(), + ti.isActive()?Boolean.TRUE.toString():Boolean.FALSE.toString(), + ti.getUsername(), + ti.getExp(), + Chrono.timeStamp(exp), + ti.getScope(), + ti.getContent()==null?"":ti.getContent()); + + System.out.println(); + } } diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java index 6cabc654..27f9198a 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java @@ -35,185 +35,185 @@ import org.onap.aaf.misc.env.APIException; public class SimpleRestClientExample { - public final static void main(final String args[]) throws URISyntaxException, LocatorException { - try { - // Note: Expect ClientFactory to be long-lived... do NOT create more than once. - ClientFactory cf = new ClientFactory(args); - - - String urlString = cf.getAccess().getProperty("myurl", null); - if(urlString==null) { - System.out.println("Note: In your startup, add \"myurl=https://<aaf hello machine>:8130\" to command line\n\t" - + "OR\n\t" - + " add -Dmyurl=https://<aaf hello machine>:8130 to VM Args\n\t" - + "where \"aaf hello machine\" is an aaf Installation you know about."); - } else { - - SimpleRESTClient restClient = cf.simpleRESTClient(urlString,"org.osaaf.aaf"); - - ///////////////////////////////////////////////////////////// - // - // Creating Content for CREATE/UPDATE - // - ///////////////////////////////////////////////////////////// - // Create an object that can be reusable IN THIS THREAD ONLY... Not Thread-safe on purpose - Input input = new SimpleRESTClient.Input(); - - // Note: alternate use is to set the input object to an already created String - // Input input = new SimpleRESTClient.Input(aString); - - PrintWriter pw = input.writer(); - pw.print("{\"something\": ["); - for(int i=0;i<4;++i) { - if(i>0) { - pw.print(','); - } - pw.print("{\"myint\":"); - pw.print(i); - pw.print('}'); - } - pw.println("]}"); - - // You can check or log the content - String content = input.toString(); - System.out.println(content); - - // Good form for Writers is that you should close it... - pw.close(); - - ///////////////////////////////////////////////////////////// - // - // CREATE/POST - // - ///////////////////////////////////////////////////////////// - System.out.println("-------- START REST CREATE/UPDATE --------"); - try { - restClient.create("resthello/rest_id", input); - // No Error code, it worked. - System.out.println("No Error Code, Create worked..."); - } catch (RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - } finally { - System.out.println("-------- END REST CREATE/UPDATE --------"); - } - - - ///////////////////////////////////////////////////////////// - // - // READ/GET - // - ///////////////////////////////////////////////////////////// - - // Make some calls. Note that RESTException is thrown if Call does not complete. - // RESTException has HTTP Code and any Message sent from Server - System.out.println("-------- START REST READ/GET --------"); - boolean expectException = false; - try { - - // Call with no Queries - String rv = restClient.get("resthello/rest_id"); - System.out.println(rv); - - // Same call with "read" style - rv = restClient.read("resthello/rest_id"); - System.out.println(rv); - - - // Call with Queries - rv = restClient.get("resthello/rest_id?perm=org.osaaf.people|*|read"); - System.out.println(rv); - - // Call setting ID from principal coming from Trans - // Pretend Transaction - HRequest req = new HRequest("demo@people.osaaf.org"); // Pretend Trans has Jonathan as Identity - - // Call with RESTException, which allows obtaining HTTPCode and any Error message sent - rv = restClient.endUser(req.userPrincipal()).get("resthello/rest_id?perm=org.osaaf.people|*|read"); - System.out.println(rv); - - // Expect Exception here. - System.out.println("-------- START Expecting Exception starting here --------"); - expectException = true; - restClient.get("notAnAPI"); - } catch(RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - System.out.println(e.getMessage()); - System.out.println(e.getLocalizedMessage()); - System.out.println(e); - } finally { - if(expectException) { - System.out.println("-------- END Expecting Exception starting here --------"); - } - System.out.println("-------- END REST READ/GET --------"); - } - - ///////////////////////////////////////////////////////////// - // - // UPDATE/PUT - // - ///////////////////////////////////////////////////////////// - - - // If you use "input" object again as a writer, you can clear it on the same thread, and go again - input.clear(); - // Here we just set to a String, instead of Writing - input.set("{\"something\" : []}"); - - System.out.println("-------- END REST UPDATE/PUT --------"); - try { - String rv = restClient.update("resthello/rest_id", input); - // No Error code, it worked. REST Update will return the updated Data - System.out.println("Update worked"); - System.out.println(rv); - } catch (RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - } finally { - System.out.println("-------- END REST UPDATE/PUT --------"); - } - - ///////////////////////////////////////////////////////////// - // - // DELETE - // - ///////////////////////////////////////////////////////////// - - System.out.println("-------- START REST DELETE --------"); - try { - restClient.delete("resthello/rest_id"); - // No Error code, it worked. REST Update will return the updated Data - System.out.println("Delete worked"); - } catch (RESTException e) { - System.out.println(e.getCode()); - System.out.println(e.getMsg()); - } finally { - System.out.println("-------- END REST DELETE --------"); - } - } - } catch (CadiException | APIException e) { - e.printStackTrace(); - } - } - - private static class HRequest { - - public HRequest(String fqi) { - name = fqi; - } - protected final String name; - - // fake out HttpServletRequest, only for get Principal - public Principal userPrincipal() { - return new Principal() { - - @Override - public String getName() { - return name; - } - - }; - } - } + public final static void main(final String args[]) throws URISyntaxException, LocatorException { + try { + // Note: Expect ClientFactory to be long-lived... do NOT create more than once. + ClientFactory cf = new ClientFactory(args); + + + String urlString = cf.getAccess().getProperty("myurl", null); + if(urlString==null) { + System.out.println("Note: In your startup, add \"myurl=https://<aaf hello machine>:8130\" to command line\n\t" + + "OR\n\t" + + " add -Dmyurl=https://<aaf hello machine>:8130 to VM Args\n\t" + + "where \"aaf hello machine\" is an aaf Installation you know about."); + } else { + + SimpleRESTClient restClient = cf.simpleRESTClient(urlString,"org.osaaf.aaf"); + + ///////////////////////////////////////////////////////////// + // + // Creating Content for CREATE/UPDATE + // + ///////////////////////////////////////////////////////////// + // Create an object that can be reusable IN THIS THREAD ONLY... Not Thread-safe on purpose + Input input = new SimpleRESTClient.Input(); + + // Note: alternate use is to set the input object to an already created String + // Input input = new SimpleRESTClient.Input(aString); + + PrintWriter pw = input.writer(); + pw.print("{\"something\": ["); + for(int i=0;i<4;++i) { + if(i>0) { + pw.print(','); + } + pw.print("{\"myint\":"); + pw.print(i); + pw.print('}'); + } + pw.println("]}"); + + // You can check or log the content + String content = input.toString(); + System.out.println(content); + + // Good form for Writers is that you should close it... + pw.close(); + + ///////////////////////////////////////////////////////////// + // + // CREATE/POST + // + ///////////////////////////////////////////////////////////// + System.out.println("-------- START REST CREATE/UPDATE --------"); + try { + restClient.create("resthello/rest_id", input); + // No Error code, it worked. + System.out.println("No Error Code, Create worked..."); + } catch (RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + } finally { + System.out.println("-------- END REST CREATE/UPDATE --------"); + } + + + ///////////////////////////////////////////////////////////// + // + // READ/GET + // + ///////////////////////////////////////////////////////////// + + // Make some calls. Note that RESTException is thrown if Call does not complete. + // RESTException has HTTP Code and any Message sent from Server + System.out.println("-------- START REST READ/GET --------"); + boolean expectException = false; + try { + + // Call with no Queries + String rv = restClient.get("resthello/rest_id"); + System.out.println(rv); + + // Same call with "read" style + rv = restClient.read("resthello/rest_id"); + System.out.println(rv); + + + // Call with Queries + rv = restClient.get("resthello/rest_id?perm=org.osaaf.people|*|read"); + System.out.println(rv); + + // Call setting ID from principal coming from Trans + // Pretend Transaction + HRequest req = new HRequest("demo@people.osaaf.org"); // Pretend Trans has Jonathan as Identity + + // Call with RESTException, which allows obtaining HTTPCode and any Error message sent + rv = restClient.endUser(req.userPrincipal()).get("resthello/rest_id?perm=org.osaaf.people|*|read"); + System.out.println(rv); + + // Expect Exception here. + System.out.println("-------- START Expecting Exception starting here --------"); + expectException = true; + restClient.get("notAnAPI"); + } catch(RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + System.out.println(e.getMessage()); + System.out.println(e.getLocalizedMessage()); + System.out.println(e); + } finally { + if(expectException) { + System.out.println("-------- END Expecting Exception starting here --------"); + } + System.out.println("-------- END REST READ/GET --------"); + } + + ///////////////////////////////////////////////////////////// + // + // UPDATE/PUT + // + ///////////////////////////////////////////////////////////// + + + // If you use "input" object again as a writer, you can clear it on the same thread, and go again + input.clear(); + // Here we just set to a String, instead of Writing + input.set("{\"something\" : []}"); + + System.out.println("-------- END REST UPDATE/PUT --------"); + try { + String rv = restClient.update("resthello/rest_id", input); + // No Error code, it worked. REST Update will return the updated Data + System.out.println("Update worked"); + System.out.println(rv); + } catch (RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + } finally { + System.out.println("-------- END REST UPDATE/PUT --------"); + } + + ///////////////////////////////////////////////////////////// + // + // DELETE + // + ///////////////////////////////////////////////////////////// + + System.out.println("-------- START REST DELETE --------"); + try { + restClient.delete("resthello/rest_id"); + // No Error code, it worked. REST Update will return the updated Data + System.out.println("Delete worked"); + } catch (RESTException e) { + System.out.println(e.getCode()); + System.out.println(e.getMsg()); + } finally { + System.out.println("-------- END REST DELETE --------"); + } + } + } catch (CadiException | APIException e) { + e.printStackTrace(); + } + } + + private static class HRequest { + + public HRequest(String fqi) { + name = fqi; + } + protected final String name; + + // fake out HttpServletRequest, only for get Principal + public Principal userPrincipal() { + return new Principal() { + + @Override + public String getName() { + return name; + } + + }; + } + } } |