summaryrefslogtreecommitdiffstats
path: root/cadi/oauth-enduser/src
diff options
context:
space:
mode:
Diffstat (limited to 'cadi/oauth-enduser/src')
-rw-r--r--cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java36
-rw-r--r--cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java70
-rw-r--r--cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java494
-rw-r--r--cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java354
-rw-r--r--cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java302
-rw-r--r--cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java362
6 files changed, 809 insertions, 809 deletions
diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java
index 50eaa759..2a1ecdeb 100644
--- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java
+++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/ClientFactory.java
@@ -33,24 +33,24 @@ import org.onap.aaf.cadi.oauth.TokenClientFactory;
import org.onap.aaf.misc.env.APIException;
public class ClientFactory {
- private final TokenClientFactory tcf;
- public ClientFactory(final PropAccess access) throws APIException, CadiException {
- try {
- tcf = TokenClientFactory.instance(access);
- } catch (GeneralSecurityException | IOException e) {
- throw new CadiException(e);
- }
- }
-
- public ClientFactory(String[] args) throws APIException, CadiException {
- this(new PropAccess(args));
- }
+ private final TokenClientFactory tcf;
+ public ClientFactory(final PropAccess access) throws APIException, CadiException {
+ try {
+ tcf = TokenClientFactory.instance(access);
+ } catch (GeneralSecurityException | IOException e) {
+ throw new CadiException(e);
+ }
+ }
+
+ public ClientFactory(String[] args) throws APIException, CadiException {
+ this(new PropAccess(args));
+ }
- public SimpleRESTClient simpleRESTClient(final String endpoint, final String ... scopes) throws URISyntaxException, LocatorException, CadiException, APIException {
- return new SimpleRESTClient(tcf, Config.AAF_OAUTH2_TOKEN_URL, endpoint, scopes);
- }
+ public SimpleRESTClient simpleRESTClient(final String endpoint, final String ... scopes) throws URISyntaxException, LocatorException, CadiException, APIException {
+ return new SimpleRESTClient(tcf, Config.AAF_OAUTH2_TOKEN_URL, endpoint, scopes);
+ }
- public Access getAccess() {
- return tcf.access;
- }
+ public Access getAccess() {
+ return tcf.access;
+ }
}
diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java
index 95c9fe85..107e1d89 100644
--- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java
+++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/RESTException.java
@@ -23,44 +23,44 @@ package org.onap.aaf.cadi.enduser;
import org.onap.aaf.cadi.client.Future;
public class RESTException extends Exception {
- /**
- *
- */
- private static final long serialVersionUID = -5232371598208651058L;
- private Future<?> future;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -5232371598208651058L;
+ private Future<?> future;
- public RESTException(Future<?> future) {
- this.future = future;
- }
-
- public int getCode() {
- return future.code();
- }
-
- public String getMsg() {
- return future.body();
- }
+ public RESTException(Future<?> future) {
+ this.future = future;
+ }
+
+ public int getCode() {
+ return future.code();
+ }
+
+ public String getMsg() {
+ return future.body();
+ }
- public String errorString() {
- String body = future.body();
- return "RESTClient Error: " + future.code() + ": " + (body.isEmpty()?"<no message in call>":body);
- }
+ public String errorString() {
+ String body = future.body();
+ return "RESTClient Error: " + future.code() + ": " + (body.isEmpty()?"<no message in call>":body);
+ }
- /* (non-Javadoc)
- * @see java.lang.Throwable#getMessage()
- */
- @Override
- public String getMessage() {
- return errorString();
- }
+ /* (non-Javadoc)
+ * @see java.lang.Throwable#getMessage()
+ */
+ @Override
+ public String getMessage() {
+ return errorString();
+ }
- /* (non-Javadoc)
- * @see java.lang.Throwable#getLocalizedMessage()
- */
- @Override
- public String getLocalizedMessage() {
- return errorString();
- }
-
+ /* (non-Javadoc)
+ * @see java.lang.Throwable#getLocalizedMessage()
+ */
+ @Override
+ public String getLocalizedMessage() {
+ return errorString();
+ }
+
}
diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java
index 30344de5..7c633640 100644
--- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java
+++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java
@@ -43,266 +43,266 @@ import org.onap.aaf.misc.env.APIException;
import org.onap.aaf.misc.env.util.StringBuilderWriter;
public class SimpleRESTClient {
- private static final String APPLICATION_JSON = "application/json";
- private static final String[] EMPTY = new String[0];
- private final TokenClient tokenClient;
- private final TzClient restClient;
- private int callTimeout;
- private String client_id;
- private String app;
- private String chain;
- private Headers headers = new Headers() {
- @Override
- public String[] headers() {
- return EMPTY;
- }};
-
- public SimpleRESTClient(final TokenClientFactory tcf, final String tokenURL, final String endpoint, final String[] scope) throws CadiException, LocatorException, APIException {
- callTimeout = Integer.parseInt(tcf.access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF));
- tokenClient = tcf.newClient(tokenURL);
- Result<TimedToken> rtt = tokenClient.getToken(scope);
- if(rtt.isOK()) {
- restClient = tcf.newTzClient(endpoint);
-
- if((client_id = tcf.access.getProperty(Config.AAF_APPID, null))==null) {
- if((client_id = tcf.access.getProperty(Config.CADI_ALIAS, null))==null) {
- throw new CadiException(Config.AAF_APPID + " or " + Config.CADI_ALIAS + " needs to be defined");
- }
- }
- try {
- restClient.setToken(client_id,rtt.value);
- } catch (IOException e) {
- throw new CadiException(e);
- }
- } else {
- throw new CadiException(rtt.error);
- }
- }
-
- public SimpleRESTClient timeout(int newTimeout) {
- callTimeout = newTimeout;
- return this;
- }
+ private static final String APPLICATION_JSON = "application/json";
+ private static final String[] EMPTY = new String[0];
+ private final TokenClient tokenClient;
+ private final TzClient restClient;
+ private int callTimeout;
+ private String client_id;
+ private String app;
+ private String chain;
+ private Headers headers = new Headers() {
+ @Override
+ public String[] headers() {
+ return EMPTY;
+ }};
+
+ public SimpleRESTClient(final TokenClientFactory tcf, final String tokenURL, final String endpoint, final String[] scope) throws CadiException, LocatorException, APIException {
+ callTimeout = Integer.parseInt(tcf.access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF));
+ tokenClient = tcf.newClient(tokenURL);
+ Result<TimedToken> rtt = tokenClient.getToken(scope);
+ if(rtt.isOK()) {
+ restClient = tcf.newTzClient(endpoint);
+
+ if((client_id = tcf.access.getProperty(Config.AAF_APPID, null))==null) {
+ if((client_id = tcf.access.getProperty(Config.CADI_ALIAS, null))==null) {
+ throw new CadiException(Config.AAF_APPID + " or " + Config.CADI_ALIAS + " needs to be defined");
+ }
+ }
+ try {
+ restClient.setToken(client_id,rtt.value);
+ } catch (IOException e) {
+ throw new CadiException(e);
+ }
+ } else {
+ throw new CadiException(rtt.error);
+ }
+ }
+
+ public SimpleRESTClient timeout(int newTimeout) {
+ callTimeout = newTimeout;
+ return this;
+ }
- //Format:<ID>:<APP>:<protocol>[:AS][,<ID>:<APP>:<protocol>]*
- public SimpleRESTClient endUser(Principal principal) {
- if(principal==null) {
- chain = null;
- } else {
- if(principal instanceof TaggedPrincipal) {
- TaggedPrincipal tp = (TaggedPrincipal)principal;
- chain = tp.getName() + ':' + (app==null?"":app) + ':' + tp.tag() + ":AS";
- } else {
- chain = principal.getName() + (app==null?"":':'+app);
- }
- }
- return this;
- }
-
- /**
- * Single Threaded Class for building up content
- * @author jg1555
- *
- */
- public static class Input {
- private static final byte[] EMPTY_STREAM_BYTES = "".getBytes();
+ //Format:<ID>:<APP>:<protocol>[:AS][,<ID>:<APP>:<protocol>]*
+ public SimpleRESTClient endUser(Principal principal) {
+ if(principal==null) {
+ chain = null;
+ } else {
+ if(principal instanceof TaggedPrincipal) {
+ TaggedPrincipal tp = (TaggedPrincipal)principal;
+ chain = tp.getName() + ':' + (app==null?"":app) + ':' + tp.tag() + ":AS";
+ } else {
+ chain = principal.getName() + (app==null?"":':'+app);
+ }
+ }
+ return this;
+ }
+
+ /**
+ * Single Threaded Class for building up content
+ * @author jg1555
+ *
+ */
+ public static class Input {
+ private static final byte[] EMPTY_STREAM_BYTES = "".getBytes();
- private String content;
- private StringBuilder sb;
-
- public Input() {
- content = null;
- sb = null;
- }
-
- public Input(final String content) {
- this.content = content;
- }
-
- public void set(final String content) {
- this.content = content;
- }
-
- public PrintWriter writer() {
- return new PrintWriter(new StringBuilderWriter(builder()));
- }
-
- public StringBuilder builder() {
- if(sb==null) {
- sb = new StringBuilder();
- content = null;
- }
- return sb;
- }
-
- /**
- * Reuse StringBuilder object
- */
- public void clear() {
- content = null;
- if(sb!=null) {
- sb.setLength(0);
- }
- }
-
- @Override
- public String toString() {
- if(content!=null) {
- return content;
- } else if(sb!=null) {
- return sb.toString();
- } else {
- return "";
- }
- }
+ private String content;
+ private StringBuilder sb;
+
+ public Input() {
+ content = null;
+ sb = null;
+ }
+
+ public Input(final String content) {
+ this.content = content;
+ }
+
+ public void set(final String content) {
+ this.content = content;
+ }
+
+ public PrintWriter writer() {
+ return new PrintWriter(new StringBuilderWriter(builder()));
+ }
+
+ public StringBuilder builder() {
+ if(sb==null) {
+ sb = new StringBuilder();
+ content = null;
+ }
+ return sb;
+ }
+
+ /**
+ * Reuse StringBuilder object
+ */
+ public void clear() {
+ content = null;
+ if(sb!=null) {
+ sb.setLength(0);
+ }
+ }
+
+ @Override
+ public String toString() {
+ if(content!=null) {
+ return content;
+ } else if(sb!=null) {
+ return sb.toString();
+ } else {
+ return "";
+ }
+ }
- public byte[] getBytes() {
- byte[] rv;
- if(content==null) {
- if(sb==null) {
- rv = EMPTY_STREAM_BYTES;
- } else {
- rv = sb.toString().getBytes();
- }
- } else {
- rv = content.getBytes();
- }
- content = null;
- return rv;
- }
- }
+ public byte[] getBytes() {
+ byte[] rv;
+ if(content==null) {
+ if(sb==null) {
+ rv = EMPTY_STREAM_BYTES;
+ } else {
+ rv = sb.toString().getBytes();
+ }
+ } else {
+ rv = content.getBytes();
+ }
+ content = null;
+ return rv;
+ }
+ }
- /////////////////////////////////////////////////////////////
- //
- // CREATE
- //
- /////////////////////////////////////////////////////////////
- public void create(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
- post(path,APPLICATION_JSON, input);
- }
+ /////////////////////////////////////////////////////////////
+ //
+ // CREATE
+ //
+ /////////////////////////////////////////////////////////////
+ public void create(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
+ post(path,APPLICATION_JSON, input);
+ }
- public void post(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
- post(path,APPLICATION_JSON, input);
- }
+ public void post(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
+ post(path,APPLICATION_JSON, input);
+ }
- public void post(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException {
- Future<Void> future = restClient.best(new Retryable<Future<Void>>() {
- @Override
- public Future<Void> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
- return client.create(path, contentType, new ETransfer(input));
- }
- });
- if(!future.get(callTimeout)) {
- throw new RESTException(future);
- }
- }
+ public void post(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException {
+ Future<Void> future = restClient.best(new Retryable<Future<Void>>() {
+ @Override
+ public Future<Void> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
+ return client.create(path, contentType, new ETransfer(input));
+ }
+ });
+ if(!future.get(callTimeout)) {
+ throw new RESTException(future);
+ }
+ }
- /////////////////////////////////////////////////////////////
- //
- // READ
- //
- /////////////////////////////////////////////////////////////
- public String read(final String path) throws RESTException, CadiException, LocatorException, APIException {
- return get(path,APPLICATION_JSON);
- }
+ /////////////////////////////////////////////////////////////
+ //
+ // READ
+ //
+ /////////////////////////////////////////////////////////////
+ public String read(final String path) throws RESTException, CadiException, LocatorException, APIException {
+ return get(path,APPLICATION_JSON);
+ }
- public String get(final String path) throws RESTException, CadiException, LocatorException, APIException {
- return get(path,APPLICATION_JSON);
- }
+ public String get(final String path) throws RESTException, CadiException, LocatorException, APIException {
+ return get(path,APPLICATION_JSON);
+ }
- public String get(final String path, final String accepts) throws RESTException, CadiException, LocatorException, APIException {
- Future<String> future = restClient.best(new Retryable<Future<String>>() {
- @Override
- public Future<String> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
- return client.read(path,accepts, headers());
- }
- });
- if(future.get(callTimeout)) {
- return future.value;
- } else {
- throw new RESTException(future);
- }
- }
-
- /////////////////////////////////////////////////////////////
- //
- // UPDATE
- //
- /////////////////////////////////////////////////////////////
+ public String get(final String path, final String accepts) throws RESTException, CadiException, LocatorException, APIException {
+ Future<String> future = restClient.best(new Retryable<Future<String>>() {
+ @Override
+ public Future<String> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
+ return client.read(path,accepts, headers());
+ }
+ });
+ if(future.get(callTimeout)) {
+ return future.value;
+ } else {
+ throw new RESTException(future);
+ }
+ }
+
+ /////////////////////////////////////////////////////////////
+ //
+ // UPDATE
+ //
+ /////////////////////////////////////////////////////////////
- public String update(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
- return put(path,APPLICATION_JSON, input);
- }
+ public String update(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
+ return put(path,APPLICATION_JSON, input);
+ }
- public String put(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
- return put(path,APPLICATION_JSON, input);
- }
+ public String put(final String path, final Input input) throws RESTException, CadiException, LocatorException, APIException {
+ return put(path,APPLICATION_JSON, input);
+ }
- public String put(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException {
- Future<String> future = restClient.best(new Retryable<Future<String>>() {
- @Override
- public Future<String> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
- return client.update(path, contentType, new ETransfer(input));
- }
- });
- if(future.get(callTimeout)) {
- return future.value;
- } else {
- throw new RESTException(future);
- }
- }
+ public String put(final String path, final String contentType, final Input input) throws RESTException, CadiException, LocatorException, APIException {
+ Future<String> future = restClient.best(new Retryable<Future<String>>() {
+ @Override
+ public Future<String> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
+ return client.update(path, contentType, new ETransfer(input));
+ }
+ });
+ if(future.get(callTimeout)) {
+ return future.value;
+ } else {
+ throw new RESTException(future);
+ }
+ }
- /////////////////////////////////////////////////////////////
- //
- // DELETE
- //
- /////////////////////////////////////////////////////////////
- public void delete(final String path) throws RESTException, CadiException, LocatorException, APIException {
- delete(path,APPLICATION_JSON);
- }
-
- public void delete(final String path, final String contentType) throws RESTException, CadiException, LocatorException, APIException {
- Future<Void> future = restClient.best(new Retryable<Future<Void>>() {
- @Override
- public Future<Void> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
- return client.delete(path, contentType);
- }
- });
- if(!future.get(callTimeout)) {
- throw new RESTException(future);
- }
- }
+ /////////////////////////////////////////////////////////////
+ //
+ // DELETE
+ //
+ /////////////////////////////////////////////////////////////
+ public void delete(final String path) throws RESTException, CadiException, LocatorException, APIException {
+ delete(path,APPLICATION_JSON);
+ }
+
+ public void delete(final String path, final String contentType) throws RESTException, CadiException, LocatorException, APIException {
+ Future<Void> future = restClient.best(new Retryable<Future<Void>>() {
+ @Override
+ public Future<Void> code(Rcli<?> client) throws CadiException, ConnectException, APIException {
+ return client.delete(path, contentType);
+ }
+ });
+ if(!future.get(callTimeout)) {
+ throw new RESTException(future);
+ }
+ }
- /////////////////////////////////////////////////////////////
-
- private static class ETransfer implements EClient.Transfer {
- private Input input;
- public ETransfer(final Input input) {
- this.input = input;
- }
-
- @Override
- public void transfer(OutputStream os) throws IOException, APIException {
- os.write(input.getBytes());
- }
- }
+ /////////////////////////////////////////////////////////////
+
+ private static class ETransfer implements EClient.Transfer {
+ private Input input;
+ public ETransfer(final Input input) {
+ this.input = input;
+ }
+
+ @Override
+ public void transfer(OutputStream os) throws IOException, APIException {
+ os.write(input.getBytes());
+ }
+ }
- public interface Headers {
- String[] headers();
- }
-
- public String[] headers() {
- if(chain==null) {
- return headers.headers();
- } else {
- String[] strs = headers.headers();
- String[] rv = new String[strs.length+2];
- rv[0]=Config.CADI_USER_CHAIN;
- rv[1]=chain;
- for(int i = 0;i<strs.length;++i) {
- rv[i+2]=strs[i];
- }
- return rv;
- }
- }
+ public interface Headers {
+ String[] headers();
+ }
+
+ public String[] headers() {
+ if(chain==null) {
+ return headers.headers();
+ } else {
+ String[] strs = headers.headers();
+ String[] rv = new String[strs.length+2];
+ rv[0]=Config.CADI_USER_CHAIN;
+ rv[1]=chain;
+ for(int i = 0;i<strs.length;++i) {
+ rv[i+2]=strs[i];
+ }
+ return rv;
+ }
+ }
}
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;
+ }
+
+ };
+ }
+ }
}