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/client | |
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/client')
45 files changed, 4117 insertions, 4117 deletions
diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java index 80e6dc40..cce7b5f3 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsAuthentication.java @@ -41,90 +41,90 @@ import org.onap.aaf.cadi.config.SecurityInfoC; * @param <CLIENT> */ public abstract class AbsAuthentication<CLIENT> implements SecuritySetter<CLIENT> { - // HTTP Header for Authentication is "Authorization". This was from an early stage of internet where - // Access by Credential "Authorized" you for everything on the site. Since those early days, it became - // clear that "full access" wasn't appropriate, so the split between Authentication and Authorization - // came into being... But the Header remains. - public static final String AUTHORIZATION = "Authorization"; - private static final Symm symm; + // HTTP Header for Authentication is "Authorization". This was from an early stage of internet where + // Access by Credential "Authorized" you for everything on the site. Since those early days, it became + // clear that "full access" wasn't appropriate, so the split between Authentication and Authorization + // came into being... But the Header remains. + public static final String AUTHORIZATION = "Authorization"; + private static final Symm symm; - protected static final String REPEAT_OFFENDER = "This call is aborted because of repeated usage of invalid Passwords"; - private static final int MAX_TEMP_COUNT = 10; - private static final int MAX_SPAM_COUNT = 10000; - private static final long WAIT_TIME = 1000*60*4L; - private final byte[] headValue; - private String user; - protected final SecurityInfoC<CLIENT> securityInfo; - protected long lastMiss; - protected int count; - - static { - try { - symm = Symm.encrypt.obtain(); - } catch (IOException e) { - throw new RuntimeException("Cannot create critical internal encryption key",e); - } - - } + protected static final String REPEAT_OFFENDER = "This call is aborted because of repeated usage of invalid Passwords"; + private static final int MAX_TEMP_COUNT = 10; + private static final int MAX_SPAM_COUNT = 10000; + private static final long WAIT_TIME = 1000*60*4L; + private final byte[] headValue; + private String user; + protected final SecurityInfoC<CLIENT> securityInfo; + protected long lastMiss; + protected int count; + + static { + try { + symm = Symm.encrypt.obtain(); + } catch (IOException e) { + throw new RuntimeException("Cannot create critical internal encryption key",e); + } + + } - public AbsAuthentication(final SecurityInfoC<CLIENT> securityInfo, final String user, final byte[] headValue) throws IOException { - this.headValue = headValue==null?null:symm.encode(headValue); - this.user = user; - this.securityInfo = securityInfo; - lastMiss=0L; - count=0; - } + public AbsAuthentication(final SecurityInfoC<CLIENT> securityInfo, final String user, final byte[] headValue) throws IOException { + this.headValue = headValue==null?null:symm.encode(headValue); + this.user = user; + this.securityInfo = securityInfo; + lastMiss=0L; + count=0; + } - protected String headValue() throws IOException { - if(headValue==null) { - return ""; - } else { - return new String(symm.decode(headValue)); - } - } - - protected void setUser(String id) { - user = id; - } - - @Override - public String getID() { - return user; - } + protected String headValue() throws IOException { + if(headValue==null) { + return ""; + } else { + return new String(symm.decode(headValue)); + } + } + + protected void setUser(String id) { + user = id; + } + + @Override + public String getID() { + return user; + } - public boolean isDenied() { - if(lastMiss>0 && lastMiss>System.currentTimeMillis()) { - return true; - } else { - lastMiss=0L; - return false; - } - } + public boolean isDenied() { + if(lastMiss>0 && lastMiss>System.currentTimeMillis()) { + return true; + } else { + lastMiss=0L; + return false; + } + } - public synchronized int setLastResponse(int httpcode) { - if(httpcode == 401) { - ++count; - if(lastMiss==0L && count>MAX_TEMP_COUNT) { - lastMiss=System.currentTimeMillis()+WAIT_TIME; - } - // if(count>MAX_SPAM_COUNT) { - // System.err.printf("Your service has %d consecutive bad service logins to AAF. \nIt will now exit\n", - // count); - // System.exit(401); - // } - if(count%1000==0) { - System.err.printf("Your service has %d consecutive bad service logins to AAF. AAF Access will be disabled after %d\n", - count,MAX_SPAM_COUNT); - } + public synchronized int setLastResponse(int httpcode) { + if(httpcode == 401) { + ++count; + if(lastMiss==0L && count>MAX_TEMP_COUNT) { + lastMiss=System.currentTimeMillis()+WAIT_TIME; + } + // if(count>MAX_SPAM_COUNT) { + // System.err.printf("Your service has %d consecutive bad service logins to AAF. \nIt will now exit\n", + // count); + // System.exit(401); + // } + if(count%1000==0) { + System.err.printf("Your service has %d consecutive bad service logins to AAF. AAF Access will be disabled after %d\n", + count,MAX_SPAM_COUNT); + } - } else { - lastMiss=0; - } - return count; - } + } else { + lastMiss=0; + } + return count; + } - public int count() { - return count; - } + public int count() { + return count; + } }
\ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java index 3815bc67..0c38bd90 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/AbsTransferSS.java @@ -38,39 +38,39 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; * @param <CLIENT> */ public abstract class AbsTransferSS<CLIENT> implements SecuritySetter<CLIENT> { - protected String value; - protected SecurityInfoC<CLIENT> securityInfo; - protected SecuritySetter<CLIENT> defSS; - private Principal principal; + protected String value; + protected SecurityInfoC<CLIENT> securityInfo; + protected SecuritySetter<CLIENT> defSS; + private Principal principal; - //Format:<ID>:<APP>:<protocol>[:AS][,<ID>:<APP>:<protocol>]* - public AbsTransferSS(TaggedPrincipal principal, String app) { - init(principal, app); - } + //Format:<ID>:<APP>:<protocol>[:AS][,<ID>:<APP>:<protocol>]* + public AbsTransferSS(TaggedPrincipal principal, String app) { + init(principal, app); + } - public AbsTransferSS(TaggedPrincipal principal, String app, SecurityInfoC<CLIENT> si) { - init(principal,app); - securityInfo = si; - this.defSS = si.defSS; - } + public AbsTransferSS(TaggedPrincipal principal, String app, SecurityInfoC<CLIENT> si) { + init(principal,app); + securityInfo = si; + this.defSS = si.defSS; + } - private void init(TaggedPrincipal principal, String app) { - this.principal=principal; - if(principal==null) { - return; - } else { - value = principal.getName() + ':' + - app + ':' + - principal.tag() + ':' + - "AS"; - } - } + private void init(TaggedPrincipal principal, String app) { + this.principal=principal; + if(principal==null) { + return; + } else { + value = principal.getName() + ':' + + app + ':' + + principal.tag() + ':' + + "AS"; + } + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.SecuritySetter#getID() - */ - @Override - public String getID() { - return principal==null?"":principal.getName(); - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.SecuritySetter#getID() + */ + @Override + public String getID() { + return principal==null?"":principal.getName(); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java index d5dfebf5..9aa9cad6 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/EClient.java @@ -32,20 +32,20 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; public interface EClient<CT> { - public void setMethod(String meth); - public void setPathInfo(String pathinfo); - public void setPayload(Transfer transfer); - public void addHeader(String tag, String value); - public void setQueryParams(String q); - public void setFragment(String f); - public void send() throws APIException; - public<T> Future<T> futureCreate(Class<T> t); - public Future<String> futureReadString(); - public<T> Future<T> futureRead(RosettaDF<T> df,Data.TYPE type); - public<T> Future<T> future(T t); - public Future<Void> future(HttpServletResponse resp, int expected) throws APIException; - - public interface Transfer { - public void transfer(OutputStream os) throws IOException, APIException; - } + public void setMethod(String meth); + public void setPathInfo(String pathinfo); + public void setPayload(Transfer transfer); + public void addHeader(String tag, String value); + public void setQueryParams(String q); + public void setFragment(String f); + public void send() throws APIException; + public<T> Future<T> futureCreate(Class<T> t); + public Future<String> futureReadString(); + public<T> Future<T> futureRead(RosettaDF<T> df,Data.TYPE type); + public<T> Future<T> future(T t); + public Future<Void> future(HttpServletResponse resp, int expected) throws APIException; + + public interface Transfer { + public void transfer(OutputStream os) throws IOException, APIException; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java index 2579dc11..39f88687 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Future.java @@ -24,10 +24,10 @@ package org.onap.aaf.cadi.client; import org.onap.aaf.cadi.CadiException; public abstract class Future<T> { - public T value; - public abstract boolean get(int timeout) throws CadiException; - - public abstract int code(); - public abstract String body(); - public abstract String header(String tag); + public T value; + public abstract boolean get(int timeout) throws CadiException; + + public abstract int code(); + public abstract String body(); + public abstract String header(String tag); }
\ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java index c13afc25..af97c465 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Holder.java @@ -28,19 +28,19 @@ package org.onap.aaf.cadi.client; * @param <T> */ public class Holder<T> { - private T value; - public Holder(T t) { - value = t; - } - public T set(T t) { - value = t; - return t; - } - - public T get() { - return value; - } - public String toString() { - return value.toString(); - } + private T value; + public Holder(T t) { + value = t; + } + public T set(T t) { + value = t; + return t; + } + + public T get() { + return value; + } + public String toString() { + return value.toString(); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java index 04075f29..b414487b 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Rcli.java @@ -41,729 +41,729 @@ import org.onap.aaf.misc.env.util.Pool.Pooled; import org.onap.aaf.misc.rosetta.env.RosettaDF; public abstract class Rcli<CT> { - public static final String FORM_ENCODED = "application/x-www-form-urlencoded"; - public static final String APPL_JSON = "application/json"; - public static final String APPL_XML = "application/xml"; - public static final String BLANK = ""; - public static final String CONTENT_TYPE = "Content-Type"; - public static final String ACCEPT = "Accept"; - - protected static final String POST = "POST"; - protected static final String GET = "GET"; - protected static final String PUT = "PUT"; - protected static final String DELETE = "DELETE"; - protected TYPE type; - protected String apiVersion; - protected int readTimeout = 5000; - protected int connectionTimeout = 3000; - protected URI uri; - private String oneCallQueryParams; - public static Pool<byte[]> buffPool = new Pool<byte[]>(new Pool.Creator<byte[]>() { - @Override - public byte[] create() throws APIException { - return new byte[1024]; - } - - @Override - public void destroy(byte[] t) { - } - - @Override - public boolean isValid(byte[] t) { - return true; - } - - @Override - public void reuse(byte[] t) { - } - }); - - - public Rcli() { - super(); - } - - public abstract void setSecuritySetter(SecuritySetter<CT> ss); - public abstract SecuritySetter<CT> getSecuritySetter(); - - - public Rcli<CT> forUser(SecuritySetter<CT> ss) { - Rcli<CT> rv = clone(uri==null?this.uri:uri,ss); - setSecuritySetter(ss); - rv.type = type; - rv.apiVersion = apiVersion; - return rv; - } - - protected abstract Rcli<CT> clone(URI uri, SecuritySetter<CT> ss); - - public abstract void invalidate() throws CadiException; - - public Rcli<CT> readTimeout(int millis) { - readTimeout = millis; - return this; - } - - public Rcli<CT> connectionTimeout(int millis) { - connectionTimeout = millis; - return this; - } - - public Rcli<CT> type(TYPE type) { - this.type=type; - return this; - } - - public Rcli<CT> apiVersion(String apiVersion) { - this.apiVersion = apiVersion; - return this; - } - - public boolean isApiVersion(String prospective) { - return apiVersion.equals(prospective); - } - - - public String typeString(Class<?> cls) { - return "application/"+cls.getSimpleName()+"+"+type.name().toLowerCase()+ - (apiVersion==null?BLANK:";version="+apiVersion); - } - - protected abstract EClient<CT> client() throws CadiException; - - - public<T> Future<T> create(final String pathinfo, final String contentType, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureCreate(df.getTypeClass()); - } - - public<T> Future<T> create(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureCreate(df.getTypeClass()); - } - - public<T> Future<T> create(String pathinfo, Class<?> cls, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureCreate(df.getTypeClass()); - } - - public<T> Future<T> create(String pathinfo, Class<T> cls) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(null); - client.send(); - return client.futureCreate(cls); - } - - public Future<Void> create(String pathinfo, String contentType) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(null); - client.send(); - return client.futureCreate(Void.class); - } - - public Future<Void> create(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(content); - client.send(); - return client.futureCreate(Void.class); - } - - - /** - * Post Data in WWW expected format, with the format tag1=value1&tag2=value2, etc - * Note Shortcut: - * Because typically, you will want to have a variable as value, you can type, as long as tag ends with "=" - * postForm(..., "tag1=value1","tag2=",var2); - * @param pathinfo - * @param df - * @param cls - * @param formParam - * @return - * @throws APIException - * @throws CadiException - */ - public <T> Future<T> postForm(String pathinfo, final RosettaDF<T> df, final String ... formParam) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,FORM_ENCODED); - switch(type) { - case JSON: - client.addHeader(ACCEPT, APPL_JSON); - break; - case XML: - client.addHeader(ACCEPT, APPL_XML); - break; - default: - break; - } - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - PrintStream ps; - if(os instanceof PrintStream) { - ps = (PrintStream)os; - } else { - ps = new PrintStream(os); - } - boolean first = true; - for(String fp : formParam) { - if(fp!=null) { - if(first) { - first = false; - } else { - ps.print('&'); - } - if(fp.endsWith("=")) { - first = true; - } - ps.print(fp); - } - } - }}); - client.send(); - return client.futureRead(df,TYPE.JSON); - } - - /** - * Read String, using POST for keyInfo - * - * @param pathinfo - * @param df - * @param t - * @param resp - * @return - * @throws APIException - * @throws CadiException - */ - public<T> Future<String> readPost(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureReadString(); - } - - /** - * Read using POST for keyInfo, responding with marshaled Objects - * - * @param pathinfo - * @param df - * @param t - * @param resp - * @return - * @throws APIException - * @throws CadiException - */ - public<T,R> Future<R> readPost(String pathinfo, final RosettaDF<T> df, final T t, final RosettaDF<R> resp) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureRead(resp,resp.getOutType()); - } - - public Future<String> readPost(String pathinfo, String contentType, String ... headers) throws CadiException, APIException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(POST); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - }}); - client.send(); - return client.futureReadString(); - } - - public Future<String> read(String pathinfo, String accept, String ... headers) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, accept); - - for(int i=1;i<headers.length;i=i+2) { - client.addHeader(headers[i-1],headers[i]); - } - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(null); - client.send(); - return client.futureReadString(); - } - - public<T> Future<T> read(String pathinfo, String accept, RosettaDF<T> df, String ... headers) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, accept); - for(int i=1;i<headers.length;i=i+2) { - client.addHeader(headers[i-1],headers[i]); - } - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(null); - client.send(); - return client.futureRead(df,type); - } - - public<T> Future<T> read(String pathinfo, RosettaDF<T> df,String ... headers) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, typeString(df.getTypeClass())); - for(int i=1;i<headers.length;i=i+2) { - client.addHeader(headers[i-1],headers[i]); - } - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.futureRead(df,type); - } - - public<T> Future<T> read(String pathinfo, Class<?> cls, RosettaDF<T> df) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(GET); - client.addHeader(ACCEPT, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.futureRead(df,type); - } - - public<T> Future<T> update(String pathinfo, String contentType, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public<T> Future<String> updateRespondString(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - //String s = df.newData().out(type).load(t).asString(); - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.futureReadString(); - } - - public Future<String> update(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE,contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(content); - client.send(); - return client.futureReadString(); - } - - - - - public<T> Future<T> update(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public<T> Future<T> update(String pathinfo, Class<?> cls, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - - - /** - * A method to update with a VOID - * @param pathinfo - * @param resp - * @param expected - * @return - * @throws APIException - * @throws CadiException - */ - public<T> Future<Void> update(String pathinfo) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(PUT); - client.addHeader(CONTENT_TYPE, typeString(Void.class)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - -// client.setPayload(new EClient.Transfer() { -// @Override -// public void transfer(OutputStream os) throws IOException, APIException { -// } -// }); - client.send(); - return client.future(null); - } - - - public<T> Future<T> delete(String pathinfo, String contentType, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public<T> Future<T> delete(String pathinfo, Class<?> cls, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - client.send(); - return client.future(t); - } - - public<T> Future<T> delete(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - df.newData().out(type).direct(t,os); - } - }); - - client.send(); - return client.future(t); - } - - - public<T> Future<T> delete(String pathinfo, Class<T> cls) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, typeString(cls)); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.future((T)null); - } - - public Future<Void> delete(String pathinfo, String contentType) throws APIException, CadiException { - final ParsePath pp = new ParsePath(pathinfo); - - EClient<CT> client = client(); - client.setMethod(DELETE); - client.addHeader(CONTENT_TYPE, contentType); - client.setPathInfo(pp.path()); - client.setQueryParams(pp.query()); - client.setFragment(pp.frag()); - - client.setPayload(null); - client.send(); - return client.future(null); - } - - public Future<Void> transfer(final HttpServletRequest req, final HttpServletResponse resp, final String pathParam, final int expected) throws CadiException, APIException { - EClient<CT> client = client(); - URI uri; - try { - uri = new URI(req.getRequestURI()); - } catch (Exception e) { - throw new CadiException("Invalid incoming URI",e); - } - String name; - for(Enumeration<String> en = req.getHeaderNames();en.hasMoreElements();) { - name = en.nextElement(); - client.addHeader(name,req.getHeader(name)); - } - client.setQueryParams(req.getQueryString()); - client.setFragment(uri.getFragment()); - client.setPathInfo(pathParam); - String meth = req.getMethod(); - client.setMethod(meth); - if(!"GET".equals(meth)) { - client.setPayload(new EClient.Transfer() { - @Override - public void transfer(OutputStream os) throws IOException, APIException { - final ServletInputStream is = req.getInputStream(); - int read; - // reuse Buffers - Pooled<byte[]> pbuff = buffPool.get(); - try { - while((read=is.read(pbuff.content))>=0) { - os.write(pbuff.content,0,read); - } - } finally { - pbuff.done(); - } - } - }); - } - client.send(); - return client.future(resp, expected); - } - - private class ParsePath { - private final String path; - private final int query; - private final int queryEnd; - private final int pound; - private final String queryParams; - - public ParsePath(final String origPath) { - path = origPath; - if(origPath==null) { - query=queryEnd=pound=-1; - queryParams=null; - } else { - query = origPath.indexOf('?'); - pound = origPath.indexOf('#'); - queryEnd = pound>=0?pound:path.length(); - if(oneCallQueryParams==null) { - if(query>=0) { - queryParams = path.substring(query+1,queryEnd); - } else { - queryParams=null; - } - } else { - if(query>=0) { - queryParams = oneCallQueryParams + '&' + path.substring(query+1,queryEnd); - } else { - queryParams = oneCallQueryParams; - } - oneCallQueryParams = null; - } - } - } - - public String path() { - if(query>=0) { - if(pound>=0) { - return path.substring(pound+1); - } - return path.substring(0,query); - } else if(pound>=0) { - return path.substring(0,pound); - } else { - return path; - } - } - - public String query() { - return queryParams; - } - - public String frag() { - if(pound>=0) { - return path.substring(pound+1); - } else { - return null; - } - } - } - - public String toString() { - return uri.toString(); - } - - public URI getURI() { - return uri; - } - - public void setQueryParams(final String queryParams) { - oneCallQueryParams=queryParams; - } + public static final String FORM_ENCODED = "application/x-www-form-urlencoded"; + public static final String APPL_JSON = "application/json"; + public static final String APPL_XML = "application/xml"; + public static final String BLANK = ""; + public static final String CONTENT_TYPE = "Content-Type"; + public static final String ACCEPT = "Accept"; + + protected static final String POST = "POST"; + protected static final String GET = "GET"; + protected static final String PUT = "PUT"; + protected static final String DELETE = "DELETE"; + protected TYPE type; + protected String apiVersion; + protected int readTimeout = 5000; + protected int connectionTimeout = 3000; + protected URI uri; + private String oneCallQueryParams; + public static Pool<byte[]> buffPool = new Pool<byte[]>(new Pool.Creator<byte[]>() { + @Override + public byte[] create() throws APIException { + return new byte[1024]; + } + + @Override + public void destroy(byte[] t) { + } + + @Override + public boolean isValid(byte[] t) { + return true; + } + + @Override + public void reuse(byte[] t) { + } + }); + + + public Rcli() { + super(); + } + + public abstract void setSecuritySetter(SecuritySetter<CT> ss); + public abstract SecuritySetter<CT> getSecuritySetter(); + + + public Rcli<CT> forUser(SecuritySetter<CT> ss) { + Rcli<CT> rv = clone(uri==null?this.uri:uri,ss); + setSecuritySetter(ss); + rv.type = type; + rv.apiVersion = apiVersion; + return rv; + } + + protected abstract Rcli<CT> clone(URI uri, SecuritySetter<CT> ss); + + public abstract void invalidate() throws CadiException; + + public Rcli<CT> readTimeout(int millis) { + readTimeout = millis; + return this; + } + + public Rcli<CT> connectionTimeout(int millis) { + connectionTimeout = millis; + return this; + } + + public Rcli<CT> type(TYPE type) { + this.type=type; + return this; + } + + public Rcli<CT> apiVersion(String apiVersion) { + this.apiVersion = apiVersion; + return this; + } + + public boolean isApiVersion(String prospective) { + return apiVersion.equals(prospective); + } + + + public String typeString(Class<?> cls) { + return "application/"+cls.getSimpleName()+"+"+type.name().toLowerCase()+ + (apiVersion==null?BLANK:";version="+apiVersion); + } + + protected abstract EClient<CT> client() throws CadiException; + + + public<T> Future<T> create(final String pathinfo, final String contentType, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureCreate(df.getTypeClass()); + } + + public<T> Future<T> create(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureCreate(df.getTypeClass()); + } + + public<T> Future<T> create(String pathinfo, Class<?> cls, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureCreate(df.getTypeClass()); + } + + public<T> Future<T> create(String pathinfo, Class<T> cls) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(null); + client.send(); + return client.futureCreate(cls); + } + + public Future<Void> create(String pathinfo, String contentType) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(null); + client.send(); + return client.futureCreate(Void.class); + } + + public Future<Void> create(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(content); + client.send(); + return client.futureCreate(Void.class); + } + + + /** + * Post Data in WWW expected format, with the format tag1=value1&tag2=value2, etc + * Note Shortcut: + * Because typically, you will want to have a variable as value, you can type, as long as tag ends with "=" + * postForm(..., "tag1=value1","tag2=",var2); + * @param pathinfo + * @param df + * @param cls + * @param formParam + * @return + * @throws APIException + * @throws CadiException + */ + public <T> Future<T> postForm(String pathinfo, final RosettaDF<T> df, final String ... formParam) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,FORM_ENCODED); + switch(type) { + case JSON: + client.addHeader(ACCEPT, APPL_JSON); + break; + case XML: + client.addHeader(ACCEPT, APPL_XML); + break; + default: + break; + } + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + PrintStream ps; + if(os instanceof PrintStream) { + ps = (PrintStream)os; + } else { + ps = new PrintStream(os); + } + boolean first = true; + for(String fp : formParam) { + if(fp!=null) { + if(first) { + first = false; + } else { + ps.print('&'); + } + if(fp.endsWith("=")) { + first = true; + } + ps.print(fp); + } + } + }}); + client.send(); + return client.futureRead(df,TYPE.JSON); + } + + /** + * Read String, using POST for keyInfo + * + * @param pathinfo + * @param df + * @param t + * @param resp + * @return + * @throws APIException + * @throws CadiException + */ + public<T> Future<String> readPost(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureReadString(); + } + + /** + * Read using POST for keyInfo, responding with marshaled Objects + * + * @param pathinfo + * @param df + * @param t + * @param resp + * @return + * @throws APIException + * @throws CadiException + */ + public<T,R> Future<R> readPost(String pathinfo, final RosettaDF<T> df, final T t, final RosettaDF<R> resp) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureRead(resp,resp.getOutType()); + } + + public Future<String> readPost(String pathinfo, String contentType, String ... headers) throws CadiException, APIException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(POST); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + }}); + client.send(); + return client.futureReadString(); + } + + public Future<String> read(String pathinfo, String accept, String ... headers) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, accept); + + for(int i=1;i<headers.length;i=i+2) { + client.addHeader(headers[i-1],headers[i]); + } + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(null); + client.send(); + return client.futureReadString(); + } + + public<T> Future<T> read(String pathinfo, String accept, RosettaDF<T> df, String ... headers) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, accept); + for(int i=1;i<headers.length;i=i+2) { + client.addHeader(headers[i-1],headers[i]); + } + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(null); + client.send(); + return client.futureRead(df,type); + } + + public<T> Future<T> read(String pathinfo, RosettaDF<T> df,String ... headers) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, typeString(df.getTypeClass())); + for(int i=1;i<headers.length;i=i+2) { + client.addHeader(headers[i-1],headers[i]); + } + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.futureRead(df,type); + } + + public<T> Future<T> read(String pathinfo, Class<?> cls, RosettaDF<T> df) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(GET); + client.addHeader(ACCEPT, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.futureRead(df,type); + } + + public<T> Future<T> update(String pathinfo, String contentType, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public<T> Future<String> updateRespondString(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + //String s = df.newData().out(type).load(t).asString(); + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.futureReadString(); + } + + public Future<String> update(String pathinfo, String contentType, EClient.Transfer content) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE,contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(content); + client.send(); + return client.futureReadString(); + } + + + + + public<T> Future<T> update(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public<T> Future<T> update(String pathinfo, Class<?> cls, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + + + /** + * A method to update with a VOID + * @param pathinfo + * @param resp + * @param expected + * @return + * @throws APIException + * @throws CadiException + */ + public<T> Future<Void> update(String pathinfo) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(PUT); + client.addHeader(CONTENT_TYPE, typeString(Void.class)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + +// client.setPayload(new EClient.Transfer() { +// @Override +// public void transfer(OutputStream os) throws IOException, APIException { +// } +// }); + client.send(); + return client.future(null); + } + + + public<T> Future<T> delete(String pathinfo, String contentType, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public<T> Future<T> delete(String pathinfo, Class<?> cls, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + client.send(); + return client.future(t); + } + + public<T> Future<T> delete(String pathinfo, final RosettaDF<T> df, final T t) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, typeString(df.getTypeClass())); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + df.newData().out(type).direct(t,os); + } + }); + + client.send(); + return client.future(t); + } + + + public<T> Future<T> delete(String pathinfo, Class<T> cls) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, typeString(cls)); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.future((T)null); + } + + public Future<Void> delete(String pathinfo, String contentType) throws APIException, CadiException { + final ParsePath pp = new ParsePath(pathinfo); + + EClient<CT> client = client(); + client.setMethod(DELETE); + client.addHeader(CONTENT_TYPE, contentType); + client.setPathInfo(pp.path()); + client.setQueryParams(pp.query()); + client.setFragment(pp.frag()); + + client.setPayload(null); + client.send(); + return client.future(null); + } + + public Future<Void> transfer(final HttpServletRequest req, final HttpServletResponse resp, final String pathParam, final int expected) throws CadiException, APIException { + EClient<CT> client = client(); + URI uri; + try { + uri = new URI(req.getRequestURI()); + } catch (Exception e) { + throw new CadiException("Invalid incoming URI",e); + } + String name; + for(Enumeration<String> en = req.getHeaderNames();en.hasMoreElements();) { + name = en.nextElement(); + client.addHeader(name,req.getHeader(name)); + } + client.setQueryParams(req.getQueryString()); + client.setFragment(uri.getFragment()); + client.setPathInfo(pathParam); + String meth = req.getMethod(); + client.setMethod(meth); + if(!"GET".equals(meth)) { + client.setPayload(new EClient.Transfer() { + @Override + public void transfer(OutputStream os) throws IOException, APIException { + final ServletInputStream is = req.getInputStream(); + int read; + // reuse Buffers + Pooled<byte[]> pbuff = buffPool.get(); + try { + while((read=is.read(pbuff.content))>=0) { + os.write(pbuff.content,0,read); + } + } finally { + pbuff.done(); + } + } + }); + } + client.send(); + return client.future(resp, expected); + } + + private class ParsePath { + private final String path; + private final int query; + private final int queryEnd; + private final int pound; + private final String queryParams; + + public ParsePath(final String origPath) { + path = origPath; + if(origPath==null) { + query=queryEnd=pound=-1; + queryParams=null; + } else { + query = origPath.indexOf('?'); + pound = origPath.indexOf('#'); + queryEnd = pound>=0?pound:path.length(); + if(oneCallQueryParams==null) { + if(query>=0) { + queryParams = path.substring(query+1,queryEnd); + } else { + queryParams=null; + } + } else { + if(query>=0) { + queryParams = oneCallQueryParams + '&' + path.substring(query+1,queryEnd); + } else { + queryParams = oneCallQueryParams; + } + oneCallQueryParams = null; + } + } + } + + public String path() { + if(query>=0) { + if(pound>=0) { + return path.substring(pound+1); + } + return path.substring(0,query); + } else if(pound>=0) { + return path.substring(0,pound); + } else { + return path; + } + } + + public String query() { + return queryParams; + } + + public String frag() { + if(pound>=0) { + return path.substring(pound+1); + } else { + return null; + } + } + } + + public String toString() { + return uri.toString(); + } + + public URI getURI() { + return uri; + } + + public void setQueryParams(final String queryParams) { + oneCallQueryParams=queryParams; + } }
\ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java index fecb847b..e9de27e7 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Result.java @@ -22,39 +22,39 @@ package org.onap.aaf.cadi.client; public class Result<T> { - public final int code; - public final T value; - public final String error; + public final int code; + public final T value; + public final String error; - private Result(int code, T value, String error) { - this.code = code; - this.value = value; - this.error = error; - } + private Result(int code, T value, String error) { + this.code = code; + this.value = value; + this.error = error; + } - public static<T> Result<T> ok(int code,T t) { - return new Result<T>(code,t,null); - } - - public static<T> Result<T> err(int code,String body) { - return new Result<T>(code,null,body); - } + public static<T> Result<T> ok(int code,T t) { + return new Result<T>(code,t,null); + } + + public static<T> Result<T> err(int code,String body) { + return new Result<T>(code,null,body); + } - public static<T> Result<T> err(Result<?> r) { - return new Result<T>(r.code,null,r.error); - } + public static<T> Result<T> err(Result<?> r) { + return new Result<T>(r.code,null,r.error); + } - public boolean isOK() { - return error==null; - } - - public String toString() { - StringBuilder sb = new StringBuilder("Code: "); - sb.append(code); - if(error!=null) { - sb.append(" = "); - sb.append(error); - } - return sb.toString(); - } + public boolean isOK() { + return error==null; + } + + public String toString() { + StringBuilder sb = new StringBuilder("Code: "); + sb.append(code); + if(error!=null) { + sb.append(" = "); + sb.append(error); + } + return sb.toString(); + } }
\ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java index 8208efe1..58e7718d 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/client/Retryable.java @@ -35,37 +35,37 @@ import org.onap.aaf.misc.env.APIException; * @param <RET> */ public abstract class Retryable<RET> { - // be able to hold state for consistent Connections. Not required for all connection types. - public Rcli<?> lastClient; - private Locator.Item item; - - public Retryable() { - lastClient = null; - item = null; - } + // be able to hold state for consistent Connections. Not required for all connection types. + public Rcli<?> lastClient; + private Locator.Item item; + + public Retryable() { + lastClient = null; + item = null; + } - public Retryable(Retryable<?> ret) { - lastClient = ret.lastClient; - item = ret.item; - } + public Retryable(Retryable<?> ret) { + lastClient = ret.lastClient; + item = ret.item; + } - public Locator.Item item(Locator.Item item) { - lastClient = null; - this.item = item; - return item; - } - public Locator.Item item() { - return item; - } - - public abstract RET code(Rcli<?> client) throws CadiException, ConnectException, APIException; + public Locator.Item item(Locator.Item item) { + lastClient = null; + this.item = item; + return item; + } + public Locator.Item item() { + return item; + } + + public abstract RET code(Rcli<?> client) throws CadiException, ConnectException, APIException; - /** - * Note, Retryable is tightly coupled to the Client Utilizing. It will not be the wrong type. - * @return - */ - @SuppressWarnings("unchecked") - public <CLIENT> Rcli<CLIENT> lastClient() { - return (Rcli<CLIENT>)lastClient; - } + /** + * Note, Retryable is tightly coupled to the Client Utilizing. It will not be the wrong type. + * @return + */ + @SuppressWarnings("unchecked") + public <CLIENT> Rcli<CLIENT> lastClient() { + return (Rcli<CLIENT>)lastClient; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java index 787c5c29..3c38ff8d 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HAuthorizationHeader.java @@ -31,24 +31,24 @@ import org.onap.aaf.cadi.client.AbsAuthentication; import org.onap.aaf.cadi.config.SecurityInfoC; public class HAuthorizationHeader extends AbsAuthentication<HttpURLConnection> { - - public HAuthorizationHeader(SecurityInfoC<HttpURLConnection> si, String user, String headValue) throws IOException { - super(si,user,headValue==null?null:headValue.getBytes()); - } + + public HAuthorizationHeader(SecurityInfoC<HttpURLConnection> si, String user, String headValue) throws IOException { + super(si,user,headValue==null?null:headValue.getBytes()); + } - @Override - public void setSecurity(HttpURLConnection huc) throws CadiException { - if(isDenied()) { - throw new CadiException(REPEAT_OFFENDER); - } - try { - huc.addRequestProperty(AUTHORIZATION , headValue()); - } catch (IOException e) { - throw new CadiException(e); - } - if(securityInfo!=null && huc instanceof HttpsURLConnection) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); - } - } + @Override + public void setSecurity(HttpURLConnection huc) throws CadiException { + if(isDenied()) { + throw new CadiException(REPEAT_OFFENDER); + } + try { + huc.addRequestProperty(AUTHORIZATION , headValue()); + } catch (IOException e) { + throw new CadiException(e); + } + if(securityInfo!=null && huc instanceof HttpsURLConnection) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); + } + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java index 9e86c7fb..e4ab6d72 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HBasicAuthSS.java @@ -31,38 +31,38 @@ import org.onap.aaf.cadi.config.SecurityInfoC; import org.onap.aaf.cadi.principal.BasicPrincipal; public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { - public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, String user, String password) throws IOException { - super(si, user, "Basic " + Symm.base64noSplit.encode(user + ':' + password)); - } + public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, String user, String password) throws IOException { + super(si, user, "Basic " + Symm.base64noSplit.encode(user + ':' + password)); + } - public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si) throws IOException { - this(si,si.access.getProperty(Config.AAF_APPID, null), - si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false)); - } - - public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, boolean setDefault) throws IOException { - this(si,si.access.getProperty(Config.AAF_APPID, null), - si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false),setDefault); - } - + public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si) throws IOException { + this(si,si.access.getProperty(Config.AAF_APPID, null), + si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false)); + } + + public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, boolean setDefault) throws IOException { + this(si,si.access.getProperty(Config.AAF_APPID, null), + si.access.decrypt(si.access.getProperty(Config.AAF_APPPASS, null), false),setDefault); + } + - public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, String user, String pass, boolean asDefault) throws IOException { - this(si, user,pass); - if(asDefault) { - si.set(this); - } - } - - public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC<HttpURLConnection> si) throws IOException { - this(si, bp.getName(),new String(bp.getCred())); - } - - public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws IOException { - this(si, bp.getName(),new String(bp.getCred())); - if(asDefault) { - si.set(this); - } - } + public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, String user, String pass, boolean asDefault) throws IOException { + this(si, user,pass); + if(asDefault) { + si.set(this); + } + } + + public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC<HttpURLConnection> si) throws IOException { + this(si, bp.getName(),new String(bp.getCred())); + } + + public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws IOException { + this(si, bp.getName(),new String(bp.getCred())); + if(asDefault) { + si.set(this); + } + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java index a3dac7da..1d3d9547 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HClient.java @@ -54,388 +54,388 @@ import org.onap.aaf.misc.rosetta.env.RosettaDF; * */ public class HClient implements EClient<HttpURLConnection> { - private URI uri; - private ArrayList<Header> headers; - private String meth; - private String pathinfo; - private String query; - private String fragment; - private Transfer transfer; - private SecuritySetter<HttpURLConnection> ss; - private HttpURLConnection huc; - private int connectTimeout; + private URI uri; + private ArrayList<Header> headers; + private String meth; + private String pathinfo; + private String query; + private String fragment; + private Transfer transfer; + private SecuritySetter<HttpURLConnection> ss; + private HttpURLConnection huc; + private int connectTimeout; - public HClient(SecuritySetter<HttpURLConnection> ss, URI uri,int connectTimeout) throws LocatorException { - if (uri == null) { - throw new LocatorException("No Service available to call"); - } - this.uri = uri; - this.ss = ss; - this.connectTimeout = connectTimeout; - pathinfo = query = fragment = null; - } + public HClient(SecuritySetter<HttpURLConnection> ss, URI uri,int connectTimeout) throws LocatorException { + if (uri == null) { + throw new LocatorException("No Service available to call"); + } + this.uri = uri; + this.ss = ss; + this.connectTimeout = connectTimeout; + pathinfo = query = fragment = null; + } - @Override - public void setMethod(String meth) { - this.meth = meth; - } + @Override + public void setMethod(String meth) { + this.meth = meth; + } - @Override - public void setPathInfo(String pathinfo) { - this.pathinfo = pathinfo; - } + @Override + public void setPathInfo(String pathinfo) { + this.pathinfo = pathinfo; + } - @Override - public void setPayload(Transfer transfer) { - this.transfer = transfer; - } - - @Override - public void addHeader(String tag, String value) { - if (headers == null) - headers = new ArrayList<>(); - headers.add(new Header(tag, value)); - } + @Override + public void setPayload(Transfer transfer) { + this.transfer = transfer; + } + + @Override + public void addHeader(String tag, String value) { + if (headers == null) + headers = new ArrayList<>(); + headers.add(new Header(tag, value)); + } - @Override - public void setQueryParams(String q) { - query = q; - } + @Override + public void setQueryParams(String q) { + query = q; + } - @Override - public void setFragment(String f) { - fragment = f; - } + @Override + public void setFragment(String f) { + fragment = f; + } - @Override - public void send() throws APIException { - try { - // Build URL from given URI plus current Settings - if(uri.getPath()==null) { - throw new APIException("Invalid URL entered for HClient"); - } - StringBuilder pi=null; - if(pathinfo!=null) { // additional pathinfo - pi = new StringBuilder(uri.getPath()); - if(!pathinfo.startsWith("/")) { - pi.append('/'); - } - pi.append(pathinfo); - } - URI sendURI = new URI( - uri.getScheme(), - uri.getUserInfo(), - uri.getHost(), - uri.getPort(), - pi==null?uri.getPath():pi.toString(), - query==null?uri.getQuery():query, - fragment==null?uri.getFragment():fragment - ); - huc = getConnection(sendURI, pi); - huc.setRequestMethod(meth); - if(ss!=null) { - ss.setSecurity(huc); - } - if (headers != null) - for (Header d : headers) { - huc.addRequestProperty(d.tag, d.value); - } - huc.setDoInput(true); - huc.setDoOutput(true); - huc.setUseCaches(false); - huc.setConnectTimeout(connectTimeout); - huc.connect(); - if (transfer != null) { - transfer.transfer(huc.getOutputStream()); - } - // TODO other settings? There's a bunch here. - } catch (Exception e) { - throw new APIException(e); - } finally { // ensure all these are reset after sends - meth=pathinfo=null; - if(headers!=null) { - headers.clear(); - } - pathinfo = query = fragment = ""; - } - } - - public URI getURI() { - return uri; - } + @Override + public void send() throws APIException { + try { + // Build URL from given URI plus current Settings + if(uri.getPath()==null) { + throw new APIException("Invalid URL entered for HClient"); + } + StringBuilder pi=null; + if(pathinfo!=null) { // additional pathinfo + pi = new StringBuilder(uri.getPath()); + if(!pathinfo.startsWith("/")) { + pi.append('/'); + } + pi.append(pathinfo); + } + URI sendURI = new URI( + uri.getScheme(), + uri.getUserInfo(), + uri.getHost(), + uri.getPort(), + pi==null?uri.getPath():pi.toString(), + query==null?uri.getQuery():query, + fragment==null?uri.getFragment():fragment + ); + huc = getConnection(sendURI, pi); + huc.setRequestMethod(meth); + if(ss!=null) { + ss.setSecurity(huc); + } + if (headers != null) + for (Header d : headers) { + huc.addRequestProperty(d.tag, d.value); + } + huc.setDoInput(true); + huc.setDoOutput(true); + huc.setUseCaches(false); + huc.setConnectTimeout(connectTimeout); + huc.connect(); + if (transfer != null) { + transfer.transfer(huc.getOutputStream()); + } + // TODO other settings? There's a bunch here. + } catch (Exception e) { + throw new APIException(e); + } finally { // ensure all these are reset after sends + meth=pathinfo=null; + if(headers!=null) { + headers.clear(); + } + pathinfo = query = fragment = ""; + } + } + + public URI getURI() { + return uri; + } - public int timeout() { - return connectTimeout; - } - - protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException { - URL url = new URI( - uri.getScheme(), - uri.getUserInfo(), - uri.getHost(), - uri.getPort(), - pi==null?uri.getPath():pi.toString(), - query, - fragment).toURL(); - return (HttpURLConnection) url.openConnection(); - } - - public abstract class HFuture<T> extends Future<T> { - protected HttpURLConnection huc; - protected int respCode; - protected IOException exception; - protected StringBuilder errContent; - - public HFuture(final HttpURLConnection huc) { - this.huc = huc; - } - - protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{ - return respCode == 200; - }; - - @Override - public final boolean get(int timeout) throws CadiException { - try { - huc.setReadTimeout(timeout); - respCode = huc.getResponseCode(); - ss.setLastResponse(respCode); - if(evalInfo(huc)) { - return true; - } else { - extractError(); - return false; - } - } catch (IOException | APIException e) { - throw new CadiException(e); - } finally { - close(); - } - } - - private void extractError() { - InputStream is = huc.getErrorStream(); - try { - if(is==null) { - is = huc.getInputStream(); - } - if(is!=null) { - errContent = new StringBuilder(); - int c; - while((c=is.read())>=0) { - errContent.append((char)c); - } - } - } catch (IOException e) { - exception = e; - } - } - - // Typically only used by Read - public StringBuilder inputStreamToString(InputStream is) { - // Avoids Carriage returns, and is reasonably efficient, given - // the buffer reads. - try { - StringBuilder sb = new StringBuilder(); - Reader rdr = new InputStreamReader(is); - try { - char[] buf = new char[256]; - int read; - while ((read = rdr.read(buf)) >= 0) { - sb.append(buf, 0, read); - } - } finally { - rdr.close(); - } - return sb; - } catch (IOException e) { - exception = e; - return null; - } - } - - - @Override - public int code() { - return respCode; - } - - public HttpURLConnection huc() { - return huc; - } - - public IOException exception() { - return exception; - } - - @Override - public String header(String tag) { - return huc.getHeaderField(tag); - } - - public void close() { - if(huc!=null) { - huc.disconnect(); - } - } - } + public int timeout() { + return connectTimeout; + } + + protected HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException, URISyntaxException { + URL url = new URI( + uri.getScheme(), + uri.getUserInfo(), + uri.getHost(), + uri.getPort(), + pi==null?uri.getPath():pi.toString(), + query, + fragment).toURL(); + return (HttpURLConnection) url.openConnection(); + } + + public abstract class HFuture<T> extends Future<T> { + protected HttpURLConnection huc; + protected int respCode; + protected IOException exception; + protected StringBuilder errContent; + + public HFuture(final HttpURLConnection huc) { + this.huc = huc; + } + + protected boolean evalInfo(HttpURLConnection huc) throws APIException, IOException{ + return respCode == 200; + }; + + @Override + public final boolean get(int timeout) throws CadiException { + try { + huc.setReadTimeout(timeout); + respCode = huc.getResponseCode(); + ss.setLastResponse(respCode); + if(evalInfo(huc)) { + return true; + } else { + extractError(); + return false; + } + } catch (IOException | APIException e) { + throw new CadiException(e); + } finally { + close(); + } + } + + private void extractError() { + InputStream is = huc.getErrorStream(); + try { + if(is==null) { + is = huc.getInputStream(); + } + if(is!=null) { + errContent = new StringBuilder(); + int c; + while((c=is.read())>=0) { + errContent.append((char)c); + } + } + } catch (IOException e) { + exception = e; + } + } + + // Typically only used by Read + public StringBuilder inputStreamToString(InputStream is) { + // Avoids Carriage returns, and is reasonably efficient, given + // the buffer reads. + try { + StringBuilder sb = new StringBuilder(); + Reader rdr = new InputStreamReader(is); + try { + char[] buf = new char[256]; + int read; + while ((read = rdr.read(buf)) >= 0) { + sb.append(buf, 0, read); + } + } finally { + rdr.close(); + } + return sb; + } catch (IOException e) { + exception = e; + return null; + } + } + + + @Override + public int code() { + return respCode; + } + + public HttpURLConnection huc() { + return huc; + } + + public IOException exception() { + return exception; + } + + @Override + public String header(String tag) { + return huc.getHeaderField(tag); + } + + public void close() { + if(huc!=null) { + huc.disconnect(); + } + } + } - @Override - public <T> Future<T> futureCreate(Class<T> t) { - return new HFuture<T>(huc) { - public boolean evalInfo(HttpURLConnection huc) { - return respCode==201; - } + @Override + public <T> Future<T> futureCreate(Class<T> t) { + return new HFuture<T>(huc) { + public boolean evalInfo(HttpURLConnection huc) { + return respCode==201; + } - @Override - public String body() { - if (errContent != null) { - return errContent.toString(); - } - return ""; - } - }; - } + @Override + public String body() { + if (errContent != null) { + return errContent.toString(); + } + return ""; + } + }; + } - @Override - public Future<String> futureReadString() { - return new HFuture<String>(huc) { - public boolean evalInfo(HttpURLConnection huc) throws IOException { - if (respCode == 200) { - StringBuilder sb = inputStreamToString(huc.getInputStream()); - if (sb != null) { - value = sb.toString(); - } - return true; - } - return false; - } + @Override + public Future<String> futureReadString() { + return new HFuture<String>(huc) { + public boolean evalInfo(HttpURLConnection huc) throws IOException { + if (respCode == 200) { + StringBuilder sb = inputStreamToString(huc.getInputStream()); + if (sb != null) { + value = sb.toString(); + } + return true; + } + return false; + } - @Override - public String body() { - if (value != null) { - return value; - } else if (errContent != null) { - return errContent.toString(); - } - return ""; - } + @Override + public String body() { + if (value != null) { + return value; + } else if (errContent != null) { + return errContent.toString(); + } + return ""; + } - }; - } + }; + } - @Override - public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) { - return new HFuture<T>(huc) { - private Data<T> data; + @Override + public <T> Future<T> futureRead(final RosettaDF<T> df, final TYPE type) { + return new HFuture<T>(huc) { + private Data<T> data; - public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException { - if (respCode == 200) { - data = df.newData().in(type).load(huc.getInputStream()); - value = data.asObject(); - return true; - } - return false; - } + public boolean evalInfo(HttpURLConnection huc) throws APIException, IOException { + if (respCode == 200) { + data = df.newData().in(type).load(huc.getInputStream()); + value = data.asObject(); + return true; + } + return false; + } - @Override - public String body() { - if (data != null) { - try { - return data.asString(); - } catch (APIException e) { - } - } else if (errContent != null) { - return errContent.toString(); - } - return ""; - } - }; - } + @Override + public String body() { + if (data != null) { + try { + return data.asString(); + } catch (APIException e) { + } + } else if (errContent != null) { + return errContent.toString(); + } + return ""; + } + }; + } - @Override - public <T> Future<T> future(final T t) { - return new HFuture<T>(huc) { - public boolean evalInfo(HttpURLConnection huc) { - if (respCode == 200) { - value = t; - return true; - } - return false; - } + @Override + public <T> Future<T> future(final T t) { + return new HFuture<T>(huc) { + public boolean evalInfo(HttpURLConnection huc) { + if (respCode == 200) { + value = t; + return true; + } + return false; + } - @Override - public String body() { - if (errContent != null) { - return errContent.toString(); - } - return Integer.toString(respCode); - } - }; - } + @Override + public String body() { + if (errContent != null) { + return errContent.toString(); + } + return Integer.toString(respCode); + } + }; + } - @Override - public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException { - return new HFuture<Void>(huc) { - public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException { - resp.setStatus(respCode); - int read; - InputStream is; - OutputStream os = resp.getOutputStream(); - if(respCode==expected) { - is = huc.getInputStream(); - // reuse Buffers - Pooled<byte[]> pbuff = Rcli.buffPool.get(); - try { - while((read=is.read(pbuff.content))>=0) { - os.write(pbuff.content,0,read); - } - } finally { - pbuff.done(); - } - return true; - } else { - is = huc.getErrorStream(); - if(is==null) { - is = huc.getInputStream(); - } - if(is!=null) { - errContent = new StringBuilder(); - Pooled<byte[]> pbuff = Rcli.buffPool.get(); - try { - while((read=is.read(pbuff.content))>=0) { - os.write(pbuff.content,0,read); - } - } finally { - pbuff.done(); - } - } - } - return false; - } + @Override + public Future<Void> future(final HttpServletResponse resp, final int expected) throws APIException { + return new HFuture<Void>(huc) { + public boolean evalInfo(HttpURLConnection huc) throws IOException, APIException { + resp.setStatus(respCode); + int read; + InputStream is; + OutputStream os = resp.getOutputStream(); + if(respCode==expected) { + is = huc.getInputStream(); + // reuse Buffers + Pooled<byte[]> pbuff = Rcli.buffPool.get(); + try { + while((read=is.read(pbuff.content))>=0) { + os.write(pbuff.content,0,read); + } + } finally { + pbuff.done(); + } + return true; + } else { + is = huc.getErrorStream(); + if(is==null) { + is = huc.getInputStream(); + } + if(is!=null) { + errContent = new StringBuilder(); + Pooled<byte[]> pbuff = Rcli.buffPool.get(); + try { + while((read=is.read(pbuff.content))>=0) { + os.write(pbuff.content,0,read); + } + } finally { + pbuff.done(); + } + } + } + return false; + } - @Override - public String body() { - return errContent==null?null:errContent.toString(); - } - }; - } + @Override + public String body() { + return errContent==null?null:errContent.toString(); + } + }; + } - private static class Header { - public final String tag; - public final String value; + private static class Header { + public final String tag; + public final String value; - public Header(String t, String v) { - this.tag = t; - this.value = v; - } - - public String toString() { - return tag + '=' + value; - } - } - - public String toString() { - return "HttpURLConnection Client configured to " + uri.toString(); - } + public Header(String t, String v) { + this.tag = t; + this.value = v; + } + + public String toString() { + return tag + '=' + value; + } + } + + public String toString() { + return "HttpURLConnection Client configured to " + uri.toString(); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java index 772a499c..da349efc 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HMangr.java @@ -41,202 +41,202 @@ import org.onap.aaf.cadi.client.Retryable; import org.onap.aaf.misc.env.APIException; public class HMangr { - private String apiVersion; - private int readTimeout, connectionTimeout; - public final Locator<URI> loc; - private Access access; - - public HMangr(Access access, Locator<URI> loc) throws LocatorException { - readTimeout = 10000; - connectionTimeout=3000; - if(loc == null) { - throw new LocatorException("Null Locator passed"); - } - this.loc = loc; - this.access = access; - } + private String apiVersion; + private int readTimeout, connectionTimeout; + public final Locator<URI> loc; + private Access access; + + public HMangr(Access access, Locator<URI> loc) throws LocatorException { + readTimeout = 10000; + connectionTimeout=3000; + if(loc == null) { + throw new LocatorException("Null Locator passed"); + } + this.loc = loc; + this.access = access; + } - /** - * Reuse the same service. This is helpful for multiple calls that change service side cached data so that - * there is not a speed issue. - * - * If the service goes down, another service will be substituted, if available. - * - * @param access - * @param loc - * @param ss - * @param item - * @param retryable - * @return - * @throws URISyntaxException - * @throws Exception - */ - public<RET> RET same(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws APIException, CadiException, LocatorException { - RET ret = null; - boolean retry = true; - Rcli<HttpURLConnection> client = retryable.lastClient(); - try { - do { - Item item; - // if no previous state, get the best - if(retryable.item()==null) { - item = loc.best(); - if(item==null) { - throw new LocatorException("No Services Found for " + loc); - } - retryable.item(item); - retryable.lastClient = null; - } - if(client==null) { - item = retryable.item(); - URI uri=loc.get(item); - if(uri==null) { - loc.invalidate(retryable.item()); - if(loc.hasItems()) { - retryable.item(loc.next(retryable.item())); - continue; - } else { - throw new LocatorException("No clients available for " + loc.toString()); - } - } - client = new HRcli(this, uri,item,ss) - .connectionTimeout(connectionTimeout) - .readTimeout(readTimeout) - .apiVersion(apiVersion); - } else { - client.setSecuritySetter(ss); - } - - retry = false; - try { - ret = retryable.code(client); - } catch (APIException | CadiException e) { - item = retryable.item(); - loc.invalidate(item); - retryable.item(loc.next(item)); - try { - Throwable ec = e.getCause(); - if(ec instanceof java.net.ConnectException) { - if(client!=null && loc.hasItems()) { - access.log(Level.WARN,"Connection refused, trying next available service"); - retry = true; - } else { - throw new CadiException("Connection refused, no more services to try"); - } - } else if(ec instanceof java.net.SocketException) { - if(client!=null && loc.hasItems()) { - access.log(Level.WARN,"Socket prematurely closed, trying next available service"); - retry = true; - } else { - throw new CadiException("Socket prematurely closed, no more services to try"); - } - } else if(ec instanceof SocketException) { - if("java.net.SocketException: Connection reset".equals(ec.getMessage())) { - access.log(Level.ERROR, ec.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); - } - retryable.item(null); - throw e; - } else { - retryable.item(null); - throw e; - } - } finally { - client = null; - } - } catch (ConnectException e) { - item = retryable.item(); - loc.invalidate(item); - retryable.item(loc.next(item)); - } - } while(retry); - } finally { - retryable.lastClient = client; - } - return ret; - } - - - public<RET> RET best(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws LocatorException, CadiException, APIException { - retryable.item(loc.best()); - return same(ss,retryable); - } - public<RET> RET all(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws LocatorException, CadiException, APIException { - return oneOf(ss,retryable,true,null); - } + /** + * Reuse the same service. This is helpful for multiple calls that change service side cached data so that + * there is not a speed issue. + * + * If the service goes down, another service will be substituted, if available. + * + * @param access + * @param loc + * @param ss + * @param item + * @param retryable + * @return + * @throws URISyntaxException + * @throws Exception + */ + public<RET> RET same(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws APIException, CadiException, LocatorException { + RET ret = null; + boolean retry = true; + Rcli<HttpURLConnection> client = retryable.lastClient(); + try { + do { + Item item; + // if no previous state, get the best + if(retryable.item()==null) { + item = loc.best(); + if(item==null) { + throw new LocatorException("No Services Found for " + loc); + } + retryable.item(item); + retryable.lastClient = null; + } + if(client==null) { + item = retryable.item(); + URI uri=loc.get(item); + if(uri==null) { + loc.invalidate(retryable.item()); + if(loc.hasItems()) { + retryable.item(loc.next(retryable.item())); + continue; + } else { + throw new LocatorException("No clients available for " + loc.toString()); + } + } + client = new HRcli(this, uri,item,ss) + .connectionTimeout(connectionTimeout) + .readTimeout(readTimeout) + .apiVersion(apiVersion); + } else { + client.setSecuritySetter(ss); + } + + retry = false; + try { + ret = retryable.code(client); + } catch (APIException | CadiException e) { + item = retryable.item(); + loc.invalidate(item); + retryable.item(loc.next(item)); + try { + Throwable ec = e.getCause(); + if(ec instanceof java.net.ConnectException) { + if(client!=null && loc.hasItems()) { + access.log(Level.WARN,"Connection refused, trying next available service"); + retry = true; + } else { + throw new CadiException("Connection refused, no more services to try"); + } + } else if(ec instanceof java.net.SocketException) { + if(client!=null && loc.hasItems()) { + access.log(Level.WARN,"Socket prematurely closed, trying next available service"); + retry = true; + } else { + throw new CadiException("Socket prematurely closed, no more services to try"); + } + } else if(ec instanceof SocketException) { + if("java.net.SocketException: Connection reset".equals(ec.getMessage())) { + access.log(Level.ERROR, ec.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); + } + retryable.item(null); + throw e; + } else { + retryable.item(null); + throw e; + } + } finally { + client = null; + } + } catch (ConnectException e) { + item = retryable.item(); + loc.invalidate(item); + retryable.item(loc.next(item)); + } + } while(retry); + } finally { + retryable.lastClient = client; + } + return ret; + } + + + public<RET> RET best(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws LocatorException, CadiException, APIException { + retryable.item(loc.best()); + return same(ss,retryable); + } + public<RET> RET all(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) throws LocatorException, CadiException, APIException { + return oneOf(ss,retryable,true,null); + } - public<RET> RET all(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify) throws LocatorException, CadiException, APIException { - return oneOf(ss,retryable,notify,null); - } - - public<RET> RET oneOf(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify,String host) throws LocatorException, CadiException, APIException { - RET ret = null; - // make sure we have all current references: - loc.refresh(); - for(Item li=loc.first();li!=null;li=loc.next(li)) { - URI uri=loc.get(li); - if(host!=null && !host.equals(uri.getHost())) { - break; - } - try { - ret = retryable.code(new HRcli(this,uri,li,ss)); - access.log(Level.DEBUG,"Success calling",uri,"during call to all services"); - } catch (APIException | CadiException e) { - Throwable t = e.getCause(); - if(t!=null && t instanceof ConnectException) { - loc.invalidate(li); - access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); - } else if(t instanceof SSLHandshakeException) { - access.log(Level.ERROR,t.getMessage()); - loc.invalidate(li); - } else if(t instanceof SocketException) { - if("java.net.SocketException: Connection reset".equals(t.getMessage())) { - access.log(Level.ERROR, t.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); - } - retryable.item(null); - throw e; - } else { - throw e; - } - } catch (ConnectException e) { - loc.invalidate(li); - access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); - } - } - - if(ret == null && notify) - throw new LocatorException("No available clients to call"); - return ret; - } - + public<RET> RET all(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify) throws LocatorException, CadiException, APIException { + return oneOf(ss,retryable,notify,null); + } + + public<RET> RET oneOf(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify,String host) throws LocatorException, CadiException, APIException { + RET ret = null; + // make sure we have all current references: + loc.refresh(); + for(Item li=loc.first();li!=null;li=loc.next(li)) { + URI uri=loc.get(li); + if(host!=null && !host.equals(uri.getHost())) { + break; + } + try { + ret = retryable.code(new HRcli(this,uri,li,ss)); + access.log(Level.DEBUG,"Success calling",uri,"during call to all services"); + } catch (APIException | CadiException e) { + Throwable t = e.getCause(); + if(t!=null && t instanceof ConnectException) { + loc.invalidate(li); + access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); + } else if(t instanceof SSLHandshakeException) { + access.log(Level.ERROR,t.getMessage()); + loc.invalidate(li); + } else if(t instanceof SocketException) { + if("java.net.SocketException: Connection reset".equals(t.getMessage())) { + access.log(Level.ERROR, t.getMessage(), " can mean Certificate Expiration or TLS Protocol issues"); + } + retryable.item(null); + throw e; + } else { + throw e; + } + } catch (ConnectException e) { + loc.invalidate(li); + access.log(Level.ERROR,"Connection to",uri,"refused during call to all services"); + } + } + + if(ret == null && notify) + throw new LocatorException("No available clients to call"); + return ret; + } + - public void close() { - // TODO Anything here? - } + public void close() { + // TODO Anything here? + } - public HMangr readTimeout(int timeout) { - this.readTimeout = timeout; - return this; - } + public HMangr readTimeout(int timeout) { + this.readTimeout = timeout; + return this; + } - public int readTimeout() { - return readTimeout; - } - - public void connectionTimeout(int t) { - connectionTimeout = t; - } + public int readTimeout() { + return readTimeout; + } + + public void connectionTimeout(int t) { + connectionTimeout = t; + } - public int connectionTimeout() { - return connectionTimeout; - } + public int connectionTimeout() { + return connectionTimeout; + } - public HMangr apiVersion(String version) { - apiVersion = version; - return this; - } + public HMangr apiVersion(String version) { + apiVersion = version; + return this; + } - public String apiVersion() { - return apiVersion; - } + public String apiVersion() { + return apiVersion; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java index b857f3ad..0f1c8b41 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HNoAuthSS.java @@ -31,15 +31,15 @@ import org.onap.aaf.cadi.client.AbsAuthentication; import org.onap.aaf.cadi.config.SecurityInfoC; public class HNoAuthSS extends AbsAuthentication<HttpURLConnection> { - public HNoAuthSS(SecurityInfoC<HttpURLConnection> si) throws IOException { - super(si,"noauth",null); - } + public HNoAuthSS(SecurityInfoC<HttpURLConnection> si) throws IOException { + super(si,"noauth",null); + } - @Override - public void setSecurity(HttpURLConnection client) throws CadiException { - if(securityInfo!=null && client instanceof HttpsURLConnection) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)client); - } - } + @Override + public void setSecurity(HttpURLConnection client) throws CadiException { + if(securityInfo!=null && client instanceof HttpsURLConnection) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)client); + } + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java index 908b895b..674936d7 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HRcli.java @@ -44,87 +44,87 @@ import org.onap.aaf.misc.env.Data.TYPE; * @param <T> */ public class HRcli extends Rcli<HttpURLConnection> { - private HMangr hman; - private Item item; - private SecuritySetter<HttpURLConnection> ss; + private HMangr hman; + private Item item; + private SecuritySetter<HttpURLConnection> ss; - public HRcli(HMangr hman, Item locItem, SecuritySetter<HttpURLConnection> secSet) throws URISyntaxException, LocatorException { - item=locItem; - uri=hman.loc.get(locItem); - this.hman = hman; - ss=secSet; - type = TYPE.JSON; - apiVersion = hman.apiVersion(); - } + public HRcli(HMangr hman, Item locItem, SecuritySetter<HttpURLConnection> secSet) throws URISyntaxException, LocatorException { + item=locItem; + uri=hman.loc.get(locItem); + this.hman = hman; + ss=secSet; + type = TYPE.JSON; + apiVersion = hman.apiVersion(); + } - public HRcli(HMangr hman, URI uri, Item locItem, SecuritySetter<HttpURLConnection> secSet) { - item=locItem; - this.uri = uri; - this.hman = hman; - ss=secSet; - type = TYPE.JSON; - apiVersion = hman.apiVersion(); - } + public HRcli(HMangr hman, URI uri, Item locItem, SecuritySetter<HttpURLConnection> secSet) { + item=locItem; + this.uri = uri; + this.hman = hman; + ss=secSet; + type = TYPE.JSON; + apiVersion = hman.apiVersion(); + } - @Override - protected HRcli clone(URI uri, SecuritySetter<HttpURLConnection> ss) { - return new HRcli(hman,uri,item,ss); - } + @Override + protected HRcli clone(URI uri, SecuritySetter<HttpURLConnection> ss) { + return new HRcli(hman,uri,item,ss); + } - /** - * - * @return - * @throws APIException - * @throws DME2Exception - */ - protected EClient<HttpURLConnection> client() throws CadiException { - try { - if(uri==null) { - Item item = hman.loc.best(); - if(item==null) { - throw new CadiException("No service available for " + hman.loc.toString()); - } - uri = hman.loc.get(item); - } - return new HClient(ss,uri,connectionTimeout); - } catch (Exception e) { - throw new CadiException(e); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.client.Rcli#setSecuritySetter(org.onap.aaf.cadi.SecuritySetter) - */ - @Override - public void setSecuritySetter(SecuritySetter<HttpURLConnection> ss) { - this.ss = ss; - } + /** + * + * @return + * @throws APIException + * @throws DME2Exception + */ + protected EClient<HttpURLConnection> client() throws CadiException { + try { + if(uri==null) { + Item item = hman.loc.best(); + if(item==null) { + throw new CadiException("No service available for " + hman.loc.toString()); + } + uri = hman.loc.get(item); + } + return new HClient(ss,uri,connectionTimeout); + } catch (Exception e) { + throw new CadiException(e); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.client.Rcli#setSecuritySetter(org.onap.aaf.cadi.SecuritySetter) + */ + @Override + public void setSecuritySetter(SecuritySetter<HttpURLConnection> ss) { + this.ss = ss; + } - /* (non-Javadoc) - * @see org.onap.aaf.cadi.client.Rcli#getSecuritySetter() - */ - @Override - public SecuritySetter<HttpURLConnection> getSecuritySetter() { - return ss; - } + /* (non-Javadoc) + * @see org.onap.aaf.cadi.client.Rcli#getSecuritySetter() + */ + @Override + public SecuritySetter<HttpURLConnection> getSecuritySetter() { + return ss; + } - public void invalidate() throws CadiException { - try { - hman.loc.invalidate(item); - } catch (Exception e) { - throw new CadiException(e); - } - } - - public HRcli setManager(HMangr hman) { - this.hman = hman; - return this; - } + public void invalidate() throws CadiException { + try { + hman.loc.invalidate(item); + } catch (Exception e) { + throw new CadiException(e); + } + } + + public HRcli setManager(HMangr hman) { + this.hman = hman; + return this; + } - public String toString() { - return uri.toString(); - } - + public String toString() { + return uri.toString(); + } + } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java index 8eb2dec3..d792be49 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HSecurityInfoInit.java @@ -38,19 +38,19 @@ import org.onap.aaf.misc.env.APIException; */ public class HSecurityInfoInit implements SecurityInfoInit<HttpURLConnection> { - @Override - public SecuritySetter<HttpURLConnection> bestDefault(SecurityInfoC<HttpURLConnection> si) throws CadiException { - try { - if(si.defaultAlias!=null) { - si.set(new HX509SS(si)); - } else if(si.access.getProperty(Config.AAF_APPID, null)!=null && - si.access.getProperty(Config.AAF_APPPASS, null)!=null) { - si.set(new HBasicAuthSS(si)); - } - } catch (APIException | IOException e) { - throw new CadiException(e); - } - return si.defSS; - } + @Override + public SecuritySetter<HttpURLConnection> bestDefault(SecurityInfoC<HttpURLConnection> si) throws CadiException { + try { + if(si.defaultAlias!=null) { + si.set(new HX509SS(si)); + } else if(si.access.getProperty(Config.AAF_APPID, null)!=null && + si.access.getProperty(Config.AAF_APPPASS, null)!=null) { + si.set(new HBasicAuthSS(si)); + } + } catch (APIException | IOException e) { + throw new CadiException(e); + } + return si.defSS; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java index 873e0fe7..cd20585f 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTokenSS.java @@ -27,8 +27,8 @@ import java.net.HttpURLConnection; import org.onap.aaf.cadi.config.SecurityInfoC; public class HTokenSS extends HAuthorizationHeader { - public HTokenSS(final SecurityInfoC<HttpURLConnection> si, final String client_id, final String token) throws IOException { - super(si, client_id,"Bearer " + token); - } + public HTokenSS(final SecurityInfoC<HttpURLConnection> si, final String client_id, final String token) throws IOException { + super(si, client_id,"Bearer " + token); + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java index d19c42e9..c527ed02 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HTransferSS.java @@ -34,31 +34,31 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; public class HTransferSS extends AbsTransferSS<HttpURLConnection> { - public HTransferSS(TaggedPrincipal principal, String app) throws IOException { - super(principal, app); - } - - public HTransferSS(TaggedPrincipal principal, String app, SecurityInfoC<HttpURLConnection> si) { - super(principal, app, si); - } + public HTransferSS(TaggedPrincipal principal, String app) throws IOException { + super(principal, app); + } + + public HTransferSS(TaggedPrincipal principal, String app, SecurityInfoC<HttpURLConnection> si) { + super(principal, app, si); + } - @Override - public void setSecurity(HttpURLConnection huc) throws CadiException { - if(defSS==null) { - throw new CadiException("Need App Credentials to send message"); - } - defSS.setSecurity(huc); - if(value!=null) { - huc.addRequestProperty(Config.CADI_USER_CHAIN, value); - } - if(securityInfo!=null) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); - } - } - - @Override - public int setLastResponse(int respCode) { - return 0; - } + @Override + public void setSecurity(HttpURLConnection huc) throws CadiException { + if(defSS==null) { + throw new CadiException("Need App Credentials to send message"); + } + defSS.setSecurity(huc); + if(value!=null) { + huc.addRequestProperty(Config.CADI_USER_CHAIN, value); + } + if(securityInfo!=null) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); + } + } + + @Override + public int setLastResponse(int respCode) { + return 0; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java index c9ff59db..cb8e6ce0 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/http/HX509SS.java @@ -45,108 +45,108 @@ import org.onap.aaf.misc.env.util.Chrono; public class HX509SS implements SecuritySetter<HttpURLConnection> { - private static final byte[] X509 = "x509 ".getBytes(); - private PrivateKey priv; - private byte[] pub; - private String cert; - private SecurityInfoC<HttpURLConnection> securityInfo; - private String algo; - private String alias; - private static int count = new SecureRandom().nextInt(); + private static final byte[] X509 = "x509 ".getBytes(); + private PrivateKey priv; + private byte[] pub; + private String cert; + private SecurityInfoC<HttpURLConnection> securityInfo; + private String algo; + private String alias; + private static int count = new SecureRandom().nextInt(); - public HX509SS(SecurityInfoC<HttpURLConnection> si) throws APIException, CadiException { - this(null,si,false); - } - - public HX509SS(SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws APIException, CadiException { - this(null,si,asDefault); - } - - public HX509SS(final String sendAlias, SecurityInfoC<HttpURLConnection> si) throws APIException, CadiException { - this(sendAlias, si, false); - } + public HX509SS(SecurityInfoC<HttpURLConnection> si) throws APIException, CadiException { + this(null,si,false); + } + + public HX509SS(SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws APIException, CadiException { + this(null,si,asDefault); + } + + public HX509SS(final String sendAlias, SecurityInfoC<HttpURLConnection> si) throws APIException, CadiException { + this(sendAlias, si, false); + } - public HX509SS(final String sendAlias, SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws APIException, CadiException { - securityInfo = si; - if((alias=sendAlias) == null) { - if(si.defaultAlias == null) { - throw new APIException("JKS Alias is required to use X509SS Security. Use " + Config.CADI_ALIAS +" to set default alias"); - } else { - alias = si.defaultAlias; - } - } - - priv=null; - X509KeyManager[] xkms = si.getKeyManagers(); - if(xkms==null || xkms.length==0) { - throw new APIException("There are no valid keys available in given Keystores. Wrong Keypass? Expired?"); - } - for(int i=0;priv==null&&i<xkms.length;++i) { - priv = xkms[i].getPrivateKey(alias); - } - try { - for(int i=0;cert==null&&i<xkms.length;++i) { - X509Certificate[] chain = xkms[i].getCertificateChain(alias); - if(chain!=null&&chain.length>0) { - algo = chain[0].getSigAlgName(); - pub = chain[0].getEncoded(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(pub.length*2); - ByteArrayInputStream bais = new ByteArrayInputStream(pub); - Symm.base64noSplit.encode(bais,baos,X509); - cert = baos.toString(); - } - } - } catch (CertificateEncodingException | IOException e) { - throw new CadiException(e); - } - if(algo==null) { - throw new APIException("X509 Security Setter not configured"); - } - } + public HX509SS(final String sendAlias, SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws APIException, CadiException { + securityInfo = si; + if((alias=sendAlias) == null) { + if(si.defaultAlias == null) { + throw new APIException("JKS Alias is required to use X509SS Security. Use " + Config.CADI_ALIAS +" to set default alias"); + } else { + alias = si.defaultAlias; + } + } + + priv=null; + X509KeyManager[] xkms = si.getKeyManagers(); + if(xkms==null || xkms.length==0) { + throw new APIException("There are no valid keys available in given Keystores. Wrong Keypass? Expired?"); + } + for(int i=0;priv==null&&i<xkms.length;++i) { + priv = xkms[i].getPrivateKey(alias); + } + try { + for(int i=0;cert==null&&i<xkms.length;++i) { + X509Certificate[] chain = xkms[i].getCertificateChain(alias); + if(chain!=null&&chain.length>0) { + algo = chain[0].getSigAlgName(); + pub = chain[0].getEncoded(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(pub.length*2); + ByteArrayInputStream bais = new ByteArrayInputStream(pub); + Symm.base64noSplit.encode(bais,baos,X509); + cert = baos.toString(); + } + } + } catch (CertificateEncodingException | IOException e) { + throw new CadiException(e); + } + if(algo==null) { + throw new APIException("X509 Security Setter not configured"); + } + } - @Override - public void setSecurity(HttpURLConnection huc) throws CadiException { - if(huc instanceof HttpsURLConnection) { - securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); - } - if(alias==null) { // must be a one-way - huc.setRequestProperty(AbsAuthentication.AUTHORIZATION, cert); - - // Test Signed content - try { - String data = "SignedContent["+ inc() + ']' + Chrono.dateTime(); - huc.setRequestProperty("Data", data); - - Signature sig = Signature.getInstance(algo); - sig.initSign(priv); - sig.update(data.getBytes()); - byte[] signature = sig.sign(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(signature.length*1.3)); - ByteArrayInputStream bais = new ByteArrayInputStream(signature); - Symm.base64noSplit.encode(bais, baos); - huc.setRequestProperty("Signature", new String(baos.toByteArray())); - - } catch (Exception e) { - throw new CadiException(e); - } - } - } - - private synchronized int inc() { - return ++count; - } - - /* (non-Javadoc) - * @see org.onap.aaf.cadi.SecuritySetter#getID() - */ - @Override - public String getID() { - return alias; - } - - @Override - public int setLastResponse(int respCode) { - return 0; - } + @Override + public void setSecurity(HttpURLConnection huc) throws CadiException { + if(huc instanceof HttpsURLConnection) { + securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); + } + if(alias==null) { // must be a one-way + huc.setRequestProperty(AbsAuthentication.AUTHORIZATION, cert); + + // Test Signed content + try { + String data = "SignedContent["+ inc() + ']' + Chrono.dateTime(); + huc.setRequestProperty("Data", data); + + Signature sig = Signature.getInstance(algo); + sig.initSign(priv); + sig.update(data.getBytes()); + byte[] signature = sig.sign(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(signature.length*1.3)); + ByteArrayInputStream bais = new ByteArrayInputStream(signature); + Symm.base64noSplit.encode(bais, baos); + huc.setRequestProperty("Signature", new String(baos.toByteArray())); + + } catch (Exception e) { + throw new CadiException(e); + } + } + } + + private synchronized int inc() { + return ++count; + } + + /* (non-Javadoc) + * @see org.onap.aaf.cadi.SecuritySetter#getID() + */ + @Override + public String getID() { + return alias; + } + + @Override + public int setLastResponse(int respCode) { + return 0; + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java index ed60b877..1fc4b83e 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/DNSLocator.java @@ -32,192 +32,192 @@ import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.cadi.Access.Level; public class DNSLocator implements Locator<URI> { - private static enum Status {UNTRIED, OK, INVALID, SLOW}; - private static final int CHECK_TIME = 3000; - - private String host, protocol; - private Access access; - private Host[] hosts; - private int startPort, endPort; - private String suffix; - - public DNSLocator(Access access, String protocol, String host, String range) { - this.host = host; - this.protocol = protocol; - this.access = access; - int dash = range.indexOf('-'); - if(dash<0) { - startPort = endPort = Integer.parseInt(range); - } else { - startPort = Integer.parseInt(range.substring(0,dash)); - endPort = Integer.parseInt(range.substring(dash + 1)); - } - refresh(); - } + private static enum Status {UNTRIED, OK, INVALID, SLOW}; + private static final int CHECK_TIME = 3000; + + private String host, protocol; + private Access access; + private Host[] hosts; + private int startPort, endPort; + private String suffix; + + public DNSLocator(Access access, String protocol, String host, String range) { + this.host = host; + this.protocol = protocol; + this.access = access; + int dash = range.indexOf('-'); + if(dash<0) { + startPort = endPort = Integer.parseInt(range); + } else { + startPort = Integer.parseInt(range.substring(0,dash)); + endPort = Integer.parseInt(range.substring(dash + 1)); + } + refresh(); + } - public DNSLocator(Access access, String aaf_locate) throws LocatorException { - this.access = access; - if(aaf_locate==null) { - throw new LocatorException("Null passed into DNSLocator constructor"); - } - int start, port; - if(aaf_locate.startsWith("https:")) { - protocol = "https:"; - start = 9; // https:// - port = 443; - } else if(aaf_locate.startsWith("http:")) { - protocol = "http:"; - start = 8; // http:// - port = 80; - } else { - throw new LocatorException("DNSLocator accepts only https or http protocols. (requested URL " + aaf_locate + ')'); - } - - parsePorts(aaf_locate.substring(start), port); - } + public DNSLocator(Access access, String aaf_locate) throws LocatorException { + this.access = access; + if(aaf_locate==null) { + throw new LocatorException("Null passed into DNSLocator constructor"); + } + int start, port; + if(aaf_locate.startsWith("https:")) { + protocol = "https:"; + start = 9; // https:// + port = 443; + } else if(aaf_locate.startsWith("http:")) { + protocol = "http:"; + start = 8; // http:// + port = 80; + } else { + throw new LocatorException("DNSLocator accepts only https or http protocols. (requested URL " + aaf_locate + ')'); + } + + parsePorts(aaf_locate.substring(start), port); + } - @Override - public URI get(Item item) throws LocatorException { - return hosts[((DLItem)item).cnt].uri; - } + @Override + public URI get(Item item) throws LocatorException { + return hosts[((DLItem)item).cnt].uri; + } - @Override - public boolean hasItems() { - for(Host h : hosts) { - if(h.status==Status.OK) { - return true; - } - } - return false; - } + @Override + public boolean hasItems() { + for(Host h : hosts) { + if(h.status==Status.OK) { + return true; + } + } + return false; + } - @Override - public void invalidate(Item item) { - DLItem di = (DLItem)item; - hosts[di.cnt].status = Status.INVALID; - } + @Override + public void invalidate(Item item) { + DLItem di = (DLItem)item; + hosts[di.cnt].status = Status.INVALID; + } - @Override - public Item best() throws LocatorException { - // not a good "best" - for(int i=0;i<hosts.length;++i) { - switch(hosts[i].status) { - case OK: - return new DLItem(i); - case INVALID: - break; - case SLOW: - break; - case UNTRIED: - try { - if(hosts[i].ia.isReachable(CHECK_TIME)) { - hosts[i].status = Status.OK; - return new DLItem(i); - } - } catch (IOException e) { - throw new LocatorException(e); - } - break; - default: - break; - } - } - throw new LocatorException("No Available URIs for " + host); - } + @Override + public Item best() throws LocatorException { + // not a good "best" + for(int i=0;i<hosts.length;++i) { + switch(hosts[i].status) { + case OK: + return new DLItem(i); + case INVALID: + break; + case SLOW: + break; + case UNTRIED: + try { + if(hosts[i].ia.isReachable(CHECK_TIME)) { + hosts[i].status = Status.OK; + return new DLItem(i); + } + } catch (IOException e) { + throw new LocatorException(e); + } + break; + default: + break; + } + } + throw new LocatorException("No Available URIs for " + host); + } - @Override - public Item first() throws LocatorException { - return new DLItem(0); - } + @Override + public Item first() throws LocatorException { + return new DLItem(0); + } - @Override - public Item next(Item item) throws LocatorException { - DLItem di = (DLItem)item; - if(++di.cnt<hosts.length) { - return di; - } else { - return null; - } - } + @Override + public Item next(Item item) throws LocatorException { + DLItem di = (DLItem)item; + if(++di.cnt<hosts.length) { + return di; + } else { + return null; + } + } - @Override - public boolean refresh() { - try { - InetAddress[] ias = InetAddress.getAllByName(host); - Host[] temp = new Host[ias.length * (1 + endPort - startPort)]; - int cnt = -1; - for(int j=startPort; j<=endPort; ++j) { - for(int i=0;i<ias.length;++i) { - temp[++cnt] = new Host(ias[i], j, suffix); - } - } - hosts = temp; - return true; - } catch (Exception e) { - access.log(Level.ERROR, e); - } - return false; - } - - private void parsePorts(String aaf_locate, int defaultPort) throws LocatorException { - int slash, start; - int colon = aaf_locate.indexOf(':'); - if(colon > 0) { - start = colon + 1; - int left = aaf_locate.indexOf('[', start); - if(left > 0) { - int right = aaf_locate.indexOf(']', left + 1); - if (right < 0) { - throw new LocatorException("Missing closing bracket in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } else if (right == (left + 1)) { - throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } - int dash = aaf_locate.indexOf('-', left + 1); - if (dash == (right - 1) || dash == (left + 1)) { - throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } - if(dash < 0) { - startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); - } else { - startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); - endPort = Integer.parseInt(aaf_locate.substring(dash + 1, right)); - } - - } else { - slash = aaf_locate.indexOf('/', start); - if (slash == start) { - throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); - } - if(slash < 0) { - startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); - } else { - startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); - } - } - } else { - startPort = endPort = defaultPort; - } - } + @Override + public boolean refresh() { + try { + InetAddress[] ias = InetAddress.getAllByName(host); + Host[] temp = new Host[ias.length * (1 + endPort - startPort)]; + int cnt = -1; + for(int j=startPort; j<=endPort; ++j) { + for(int i=0;i<ias.length;++i) { + temp[++cnt] = new Host(ias[i], j, suffix); + } + } + hosts = temp; + return true; + } catch (Exception e) { + access.log(Level.ERROR, e); + } + return false; + } + + private void parsePorts(String aaf_locate, int defaultPort) throws LocatorException { + int slash, start; + int colon = aaf_locate.indexOf(':'); + if(colon > 0) { + start = colon + 1; + int left = aaf_locate.indexOf('[', start); + if(left > 0) { + int right = aaf_locate.indexOf(']', left + 1); + if (right < 0) { + throw new LocatorException("Missing closing bracket in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } else if (right == (left + 1)) { + throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + int dash = aaf_locate.indexOf('-', left + 1); + if (dash == (right - 1) || dash == (left + 1)) { + throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + if(dash < 0) { + startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); + } else { + startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); + endPort = Integer.parseInt(aaf_locate.substring(dash + 1, right)); + } + + } else { + slash = aaf_locate.indexOf('/', start); + if (slash == start) { + throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); + } + if(slash < 0) { + startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); + } else { + startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); + } + } + } else { + startPort = endPort = defaultPort; + } + } - private class Host { - private URI uri; - private InetAddress ia; - private Status status; - - public Host(InetAddress inetAddress, int port, String suffix) throws URISyntaxException { - ia = inetAddress; - uri = new URI(protocol,null,inetAddress.getHostAddress(),port,suffix,null,null); - status = Status.UNTRIED; - } - } - - private class DLItem implements Item { - public DLItem(int i) { - cnt = i; - } + private class Host { + private URI uri; + private InetAddress ia; + private Status status; + + public Host(InetAddress inetAddress, int port, String suffix) throws URISyntaxException { + ia = inetAddress; + uri = new URI(protocol,null,inetAddress.getHostAddress(),port,suffix,null,null); + status = Status.UNTRIED; + } + } + + private class DLItem implements Item { + public DLItem(int i) { + cnt = i; + } - private int cnt; - } - - public void destroy() {} + private int cnt; + } + + public void destroy() {} } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java index b97768a6..488d35d5 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HClientHotPeerLocator.java @@ -30,31 +30,31 @@ import org.onap.aaf.cadi.http.HClient; import org.onap.aaf.cadi.http.HX509SS; public class HClientHotPeerLocator extends HotPeerLocator<HClient> { - private final HX509SS ss; - - public HClientHotPeerLocator(Access access, String urlstr, long invalidateTime, String localLatitude, - String localLongitude, HX509SS ss) throws LocatorException { - super(access, urlstr, invalidateTime, localLatitude, localLongitude); - - this.ss = ss; - } - - @Override - protected HClient _newClient(String clientInfo) throws LocatorException { - try { - int idx = clientInfo.indexOf('/'); - return new HClient(ss,new URI("https://"+(idx<0?clientInfo:clientInfo.substring(0, idx))),3000); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - } - - @Override - protected HClient _invalidate(HClient client) { - return null; - } - - @Override - protected void _destroy(HClient client) { - } + private final HX509SS ss; + + public HClientHotPeerLocator(Access access, String urlstr, long invalidateTime, String localLatitude, + String localLongitude, HX509SS ss) throws LocatorException { + super(access, urlstr, invalidateTime, localLatitude, localLongitude); + + this.ss = ss; + } + + @Override + protected HClient _newClient(String clientInfo) throws LocatorException { + try { + int idx = clientInfo.indexOf('/'); + return new HClient(ss,new URI("https://"+(idx<0?clientInfo:clientInfo.substring(0, idx))),3000); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + } + + @Override + protected HClient _invalidate(HClient client) { + return null; + } + + @Override + protected void _destroy(HClient client) { + } }
\ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java index fd8e99dc..26b8817b 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/HotPeerLocator.java @@ -30,8 +30,8 @@ import org.onap.aaf.misc.env.util.Split; /** * This Locator is to handle Hot Peer load protection, when the Servers are - * 1) Static - * 2) Well known client URL + * 1) Static + * 2) Well known client URL * * The intention is to change traffic over to the Hot Peer, if a server goes down, and reinstate * when it is back up. @@ -43,259 +43,259 @@ import org.onap.aaf.misc.env.util.Split; * @param <CLIENT> */ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { - private final String[] urlstrs; - private final CLIENT[] clients; - private final long[] failures; - private final double[] distances; - private int preferred; - private long invalidateTime; - private Thread refreshThread; - protected Access access; + private final String[] urlstrs; + private final CLIENT[] clients; + private final long[] failures; + private final double[] distances; + private int preferred; + private long invalidateTime; + private Thread refreshThread; + protected Access access; - /** - * Construct: Expect one or more Strings in the form: - * 192.555.112.223:39/38.88087/-77.30122 - * separated by commas - * - * @param trans - * @param urlstr - * @param invalidateTime - * @param localLatitude - * @param localLongitude - * @throws LocatorException - */ - @SuppressWarnings("unchecked") - protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException { - this.access = access; - urlstrs = Split.split(',', urlstr); - clients = (CLIENT[])new Object[urlstrs.length]; - failures = new long[urlstrs.length]; - distances= new double[urlstrs.length]; - this.invalidateTime = invalidateTime; + /** + * Construct: Expect one or more Strings in the form: + * 192.555.112.223:39/38.88087/-77.30122 + * separated by commas + * + * @param trans + * @param urlstr + * @param invalidateTime + * @param localLatitude + * @param localLongitude + * @throws LocatorException + */ + @SuppressWarnings("unchecked") + protected HotPeerLocator(Access access, final String urlstr, final long invalidateTime, final String localLatitude, final String localLongitude) throws LocatorException { + this.access = access; + urlstrs = Split.split(',', urlstr); + clients = (CLIENT[])new Object[urlstrs.length]; + failures = new long[urlstrs.length]; + distances= new double[urlstrs.length]; + this.invalidateTime = invalidateTime; - double distance = Double.MAX_VALUE; - for(int i=0;i<urlstrs.length;++i) { - String[] info = Split.split('/', urlstrs[i]); - if(info.length<3) { - throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long"); - } - try { - clients[i] = _newClient(urlstrs[i]); - failures[i] = 0L; - } catch(LocatorException le) { - failures[i] = System.currentTimeMillis()+invalidateTime; - } + double distance = Double.MAX_VALUE; + for(int i=0;i<urlstrs.length;++i) { + String[] info = Split.split('/', urlstrs[i]); + if(info.length<3) { + throw new LocatorException("Configuration needs LAT and LONG, i.e. ip:port/lat/long"); + } + try { + clients[i] = _newClient(urlstrs[i]); + failures[i] = 0L; + } catch(LocatorException le) { + failures[i] = System.currentTimeMillis()+invalidateTime; + } - double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude); - distances[i]=d; + double d = GreatCircle.calc(info[1],info[2],localLatitude,localLongitude); + distances[i]=d; - // find preferred server - if(d<distance) { - preferred = i; - distance=d; - } - } + // find preferred server + if(d<distance) { + preferred = i; + distance=d; + } + } - access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]); - for(int i=0;i<urlstrs.length;++i) { - if(i!=preferred) { - access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]); - } - } - } + access.printf(Level.INIT,"Preferred Client is %s",urlstrs[preferred]); + for(int i=0;i<urlstrs.length;++i) { + if(i!=preferred) { + access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]); + } + } + } - protected abstract CLIENT _newClient(String hostInfo) throws LocatorException; - /** - * If client can reconnect, then return. Otherwise, destroy and return null; - * @param client - * @return - * @throws LocatorException - */ - protected abstract CLIENT _invalidate(CLIENT client); + protected abstract CLIENT _newClient(String hostInfo) throws LocatorException; + /** + * If client can reconnect, then return. Otherwise, destroy and return null; + * @param client + * @return + * @throws LocatorException + */ + protected abstract CLIENT _invalidate(CLIENT client); - protected abstract void _destroy(CLIENT client); + protected abstract void _destroy(CLIENT client); - @Override - public Item best() throws LocatorException { - if(failures[preferred]==0L) { - return new HPItem(preferred); - } else { - long now = System.currentTimeMillis(); - double d = Double.MAX_VALUE; - int best = -1; - boolean tickle = false; - // try for best existing client - for(int i=0;i<urlstrs.length;++i) { - if(failures[i]<now && distances[i]<d) { - if(clients[i]!=null) { - best = i; - break; - } else { - tickle = true; // There's some failed clients which can be restored - } - } - } - if(best<0 && tickle) { - tickle=false; - if(refresh()) { - // try again - for(int i=0;i<urlstrs.length;++i) { - if(failures[i]==0L && distances[i]<d) { - if(clients[i]!=null) { - best = i; - break; - } - } - } - } - } + @Override + public Item best() throws LocatorException { + if(failures[preferred]==0L) { + return new HPItem(preferred); + } else { + long now = System.currentTimeMillis(); + double d = Double.MAX_VALUE; + int best = -1; + boolean tickle = false; + // try for best existing client + for(int i=0;i<urlstrs.length;++i) { + if(failures[i]<now && distances[i]<d) { + if(clients[i]!=null) { + best = i; + break; + } else { + tickle = true; // There's some failed clients which can be restored + } + } + } + if(best<0 && tickle) { + tickle=false; + if(refresh()) { + // try again + for(int i=0;i<urlstrs.length;++i) { + if(failures[i]==0L && distances[i]<d) { + if(clients[i]!=null) { + best = i; + break; + } + } + } + } + } - /* - * If a valid client is available, but there are some that can refresh, return the client immediately - * but start a Thread to do the background Client setup. - */ - if(tickle) { - synchronized(clients) { - if(refreshThread==null) { - refreshThread = new Thread(new Runnable(){ - @Override - public void run() { - refresh(); - refreshThread = null; - } - }); - refreshThread.setDaemon(true); - refreshThread.start(); - } - } - } + /* + * If a valid client is available, but there are some that can refresh, return the client immediately + * but start a Thread to do the background Client setup. + */ + if(tickle) { + synchronized(clients) { + if(refreshThread==null) { + refreshThread = new Thread(new Runnable(){ + @Override + public void run() { + refresh(); + refreshThread = null; + } + }); + refreshThread.setDaemon(true); + refreshThread.start(); + } + } + } - if(best<0) { - throw new LocatorException("No Clients available"); - } + if(best<0) { + throw new LocatorException("No Clients available"); + } - return new HPItem(best); - } - } + return new HPItem(best); + } + } - @Override - public CLIENT get(Item item) throws LocatorException { - HPItem hpi = (HPItem)item; - CLIENT c = clients[hpi.idx]; - if(c==null) { - if(failures[hpi.idx]>System.currentTimeMillis()) { - throw new LocatorException("Client requested is invalid"); - } else { - synchronized(clients) { - c = _newClient(urlstrs[hpi.idx]); - failures[hpi.idx]=0L; - } - } - } else if(failures[hpi.idx]>0){ - throw new LocatorException("Client requested is invalid"); - } - return c; - } + @Override + public CLIENT get(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + CLIENT c = clients[hpi.idx]; + if(c==null) { + if(failures[hpi.idx]>System.currentTimeMillis()) { + throw new LocatorException("Client requested is invalid"); + } else { + synchronized(clients) { + c = _newClient(urlstrs[hpi.idx]); + failures[hpi.idx]=0L; + } + } + } else if(failures[hpi.idx]>0){ + throw new LocatorException("Client requested is invalid"); + } + return c; + } - public String info(Item item) { - HPItem hpi = (HPItem)item; - if(hpi!=null && hpi.idx<urlstrs.length) { - return urlstrs[hpi.idx]; - } else { - return "Invalid Item"; - } - } + public String info(Item item) { + HPItem hpi = (HPItem)item; + if(hpi!=null && hpi.idx<urlstrs.length) { + return urlstrs[hpi.idx]; + } else { + return "Invalid Item"; + } + } - @Override - public boolean hasItems() { - for(int i=0;i<clients.length;++i) { - if(clients[i]!=null && failures[i]==0L) { - return true; - } - } - return false; - } + @Override + public boolean hasItems() { + for(int i=0;i<clients.length;++i) { + if(clients[i]!=null && failures[i]==0L) { + return true; + } + } + return false; + } - @Override - public synchronized void invalidate(Item item) throws LocatorException { - HPItem hpi = (HPItem)item; - failures[hpi.idx] = System.currentTimeMillis() + invalidateTime; - CLIENT c = clients[hpi.idx]; - clients[hpi.idx] = _invalidate(c); - } + @Override + public synchronized void invalidate(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + failures[hpi.idx] = System.currentTimeMillis() + invalidateTime; + CLIENT c = clients[hpi.idx]; + clients[hpi.idx] = _invalidate(c); + } - @Override - public Item first() throws LocatorException { - return new HPItem(0); - } + @Override + public Item first() throws LocatorException { + return new HPItem(0); + } - @Override - public Item next(Item item) throws LocatorException { - HPItem hpi = (HPItem)item; - if(++hpi.idx>=clients.length) { - return null; - } - return hpi; - } + @Override + public Item next(Item item) throws LocatorException { + HPItem hpi = (HPItem)item; + if(++hpi.idx>=clients.length) { + return null; + } + return hpi; + } - @Override - public boolean refresh() { - boolean force = !hasItems(); // If no Items at all, reset - boolean rv = true; - long now = System.currentTimeMillis(); - for(int i=0;i<clients.length;++i) { - if(failures[i]>0L && (failures[i]<now || force)) { // retry - try { - synchronized(clients) { - if(clients[i]==null) { - clients[i]=_newClient(urlstrs[i]); - } - failures[i]=0L; - } - } catch (LocatorException e) { - failures[i]=now+invalidateTime; - rv = false; - } - } - } - return rv; - } + @Override + public boolean refresh() { + boolean force = !hasItems(); // If no Items at all, reset + boolean rv = true; + long now = System.currentTimeMillis(); + for(int i=0;i<clients.length;++i) { + if(failures[i]>0L && (failures[i]<now || force)) { // retry + try { + synchronized(clients) { + if(clients[i]==null) { + clients[i]=_newClient(urlstrs[i]); + } + failures[i]=0L; + } + } catch (LocatorException e) { + failures[i]=now+invalidateTime; + rv = false; + } + } + } + return rv; + } - @Override - public void destroy() { - for(int i=0;i<clients.length;++i) { - if(clients[i]!=null) { - _destroy(clients[i]); - clients[i] = null; - } - } - } + @Override + public void destroy() { + for(int i=0;i<clients.length;++i) { + if(clients[i]!=null) { + _destroy(clients[i]); + clients[i] = null; + } + } + } - private static class HPItem implements Item { - private int idx; + private static class HPItem implements Item { + private int idx; - public HPItem(int i) { - idx = i; - } - } + public HPItem(int i) { + idx = i; + } + } - /* - * Convenience Functions - */ - public CLIENT bestClient() throws LocatorException { - return get(best()); - } + /* + * Convenience Functions + */ + public CLIENT bestClient() throws LocatorException { + return get(best()); + } - public boolean invalidate(CLIENT client) throws LocatorException { - for(int i=0;i<clients.length;++i) { - if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference - invalidate(new HPItem(i)); - return true; - } - } - return false; - } + public boolean invalidate(CLIENT client) throws LocatorException { + for(int i=0;i<clients.length;++i) { + if(clients[i]==client) { // yes, "==" is appropriate here.. Comparing Java Object Reference + invalidate(new HPItem(i)); + return true; + } + } + return false; + } }
\ No newline at end of file diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java index b75e8bc2..c1073315 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/PropertyLocator.java @@ -39,260 +39,260 @@ import org.onap.aaf.cadi.LocatorException; import org.onap.aaf.misc.env.util.Split; public class PropertyLocator implements Locator<URI> { - private final URI [] orig; - private PLItem[] current; - private int end; - private final SecureRandom random; - private URI[] resolved; - private long lastRefreshed; - private long minRefresh; - private long backgroundRefresh; + private final URI [] orig; + private PLItem[] current; + private int end; + private final SecureRandom random; + private URI[] resolved; + private long lastRefreshed; + private long minRefresh; + private long backgroundRefresh; - public PropertyLocator(String locList) throws LocatorException { - this(locList,10000L, 1000*60*20L); // defaults, do not refresh more than once in 10 seconds, Refresh Locator every 20 mins. - } - /** - * comma delimited root url list - * - * @param locList - * @throws LocatorException - */ - public PropertyLocator(String locList, long minRefreshMillis, long backgroundRefreshMillis) throws LocatorException { - minRefresh = minRefreshMillis; - backgroundRefresh = backgroundRefreshMillis; - lastRefreshed=0L; - if(locList==null) { - throw new LocatorException("No Location List given for PropertyLocator"); - } - String[] locarray = Split.split(',',locList); - List<URI> uriList = new ArrayList<>(); - - random = new SecureRandom(); - - for(int i=0;i<locarray.length;++i) { - try { - int range = locarray[i].indexOf(":["); - if(range<0) { - uriList.add(new URI(locarray[i])); - } else { - String mach_colon = locarray[i].substring(0, range+1); - int dash = locarray[i].indexOf('-',range+2); - int brac = locarray[i].indexOf(']',dash+1); - int slash = locarray[i].indexOf('/',brac); - int start = Integer.parseInt(locarray[i].substring(range+2, dash)); - int end = Integer.parseInt(locarray[i].substring(dash+1, brac)); - for(int port=start;port<=end;++port) { - uriList.add(new URI(mach_colon+port + (slash>=0?locarray[i].substring(slash):""))); - } - } - } catch (NumberFormatException nf) { - throw new LocatorException("Invalid URI format: " + locarray[i]); - } catch (URISyntaxException e) { - throw new LocatorException(e); - } - } - orig = new URI[uriList.size()]; - uriList.toArray(orig); + public PropertyLocator(String locList) throws LocatorException { + this(locList,10000L, 1000*60*20L); // defaults, do not refresh more than once in 10 seconds, Refresh Locator every 20 mins. + } + /** + * comma delimited root url list + * + * @param locList + * @throws LocatorException + */ + public PropertyLocator(String locList, long minRefreshMillis, long backgroundRefreshMillis) throws LocatorException { + minRefresh = minRefreshMillis; + backgroundRefresh = backgroundRefreshMillis; + lastRefreshed=0L; + if(locList==null) { + throw new LocatorException("No Location List given for PropertyLocator"); + } + String[] locarray = Split.split(',',locList); + List<URI> uriList = new ArrayList<>(); + + random = new SecureRandom(); + + for(int i=0;i<locarray.length;++i) { + try { + int range = locarray[i].indexOf(":["); + if(range<0) { + uriList.add(new URI(locarray[i])); + } else { + String mach_colon = locarray[i].substring(0, range+1); + int dash = locarray[i].indexOf('-',range+2); + int brac = locarray[i].indexOf(']',dash+1); + int slash = locarray[i].indexOf('/',brac); + int start = Integer.parseInt(locarray[i].substring(range+2, dash)); + int end = Integer.parseInt(locarray[i].substring(dash+1, brac)); + for(int port=start;port<=end;++port) { + uriList.add(new URI(mach_colon+port + (slash>=0?locarray[i].substring(slash):""))); + } + } + } catch (NumberFormatException nf) { + throw new LocatorException("Invalid URI format: " + locarray[i]); + } catch (URISyntaxException e) { + throw new LocatorException(e); + } + } + orig = new URI[uriList.size()]; + uriList.toArray(orig); - refresh(); - new Timer("PropertyLocator Refresh Timer",true).scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - refresh(); - } - }, backgroundRefresh,backgroundRefresh); - } + refresh(); + new Timer("PropertyLocator Refresh Timer",true).scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + refresh(); + } + }, backgroundRefresh,backgroundRefresh); + } - @Override - public URI get(Item item) throws LocatorException { - synchronized(orig) { - if(item==null) { - return null; - } else { - return resolved[((PLItem)item).idx]; - } - } - } + @Override + public URI get(Item item) throws LocatorException { + synchronized(orig) { + if(item==null) { + return null; + } else { + return resolved[((PLItem)item).idx]; + } + } + } - @Override - public Item first() throws LocatorException { - return end>0?current[0]:null; - } + @Override + public Item first() throws LocatorException { + return end>0?current[0]:null; + } - @Override - public boolean hasItems() { - return end>0; - } + @Override + public boolean hasItems() { + return end>0; + } - @Override - public Item next(Item item) throws LocatorException { - if(item==null) { - return null; - } else { - int spot; - if((spot=(((PLItem)item).order+1))>=end)return null; - return current[spot]; - } - } + @Override + public Item next(Item item) throws LocatorException { + if(item==null) { + return null; + } else { + int spot; + if((spot=(((PLItem)item).order+1))>=end)return null; + return current[spot]; + } + } - @Override - public synchronized void invalidate(Item item) throws LocatorException { - if(--end<0) { - refresh(); - return; - } - if(item==null) { - return; - } - PLItem pli = (PLItem)item; - int i,order; - for(i=0;i<end;++i) { - if(pli==current[i])break; - } - order = current[i].order; - for(;i<end;++i) { - current[i]=current[i+1]; - current[i].order=order++; - } - current[end]=pli; - } + @Override + public synchronized void invalidate(Item item) throws LocatorException { + if(--end<0) { + refresh(); + return; + } + if(item==null) { + return; + } + PLItem pli = (PLItem)item; + int i,order; + for(i=0;i<end;++i) { + if(pli==current[i])break; + } + order = current[i].order; + for(;i<end;++i) { + current[i]=current[i+1]; + current[i].order=order++; + } + current[end]=pli; + } - @Override - public Item best() throws LocatorException { - if(current.length==0) { - refresh(); - } - switch(current.length) { - case 0: - return null; - case 1: - return current[0]; - default: - int rand = random.nextInt(); // sonar driven syntax - return current[Math.abs(rand)%current.length]; - } - } + @Override + public Item best() throws LocatorException { + if(current.length==0) { + refresh(); + } + switch(current.length) { + case 0: + return null; + case 1: + return current[0]; + default: + int rand = random.nextInt(); // sonar driven syntax + return current[Math.abs(rand)%current.length]; + } + } - @Override - public synchronized boolean refresh() { - if(System.currentTimeMillis()>lastRefreshed) { - // Build up list - List<URI> resolve = new ArrayList<>(); - String realname; - for(int i = 0; i < orig.length ; ++i) { - try { - InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost()); + @Override + public synchronized boolean refresh() { + if(System.currentTimeMillis()>lastRefreshed) { + // Build up list + List<URI> resolve = new ArrayList<>(); + String realname; + for(int i = 0; i < orig.length ; ++i) { + try { + InetAddress ia[] = InetAddress.getAllByName(orig[i].getHost()); - URI o,n; - for(int j=0;j<ia.length;++j) { - o = orig[i]; - Socket socket = createSocket(); - try { - realname=ia[j].getHostAddress().equals(ia[j].getHostName())?ia[j].getCanonicalHostName():ia[j].getHostName(); - int port = o.getPort(); - if(port<0) { // default - port = "https".equalsIgnoreCase(o.getScheme())?443:80; - } - socket.connect(new InetSocketAddress(realname,port),3000); - try { - if(socket.isConnected()) { - n = new URI( - o.getScheme(), - o.getUserInfo(), - realname, - o.getPort(), - o.getPath(), - o.getQuery(), - o.getFragment() - ); - resolve.add(n); - } - } finally { - socket.close(); - } - } catch (IOException e) { - } finally { - if(!socket.isClosed()) { - try { - socket.close(); - } catch (IOException e) { - // nothing to do. - } - } - } - } - } catch (UnknownHostException | URISyntaxException e) { - // Note: Orig Name already known as valid, based on constructor - } - } - end=resolve.size(); - PLItem[] newCurrent; - if(current==null || current.length!=end) { - newCurrent = new PLItem[end]; - } else { - newCurrent = current; - } - - for(int i=0; i< end; ++i) { - if(newCurrent[i]==null){ - newCurrent[i]=new PLItem(i); - } else { - newCurrent[i].idx=newCurrent[i].order=i; - } - } - synchronized(orig) { - resolved = new URI[end]; - resolve.toArray(resolved); - current = newCurrent; - } - lastRefreshed = System.currentTimeMillis()+minRefresh; - return !resolve.isEmpty(); - } else { - return false; - } - } + URI o,n; + for(int j=0;j<ia.length;++j) { + o = orig[i]; + Socket socket = createSocket(); + try { + realname=ia[j].getHostAddress().equals(ia[j].getHostName())?ia[j].getCanonicalHostName():ia[j].getHostName(); + int port = o.getPort(); + if(port<0) { // default + port = "https".equalsIgnoreCase(o.getScheme())?443:80; + } + socket.connect(new InetSocketAddress(realname,port),3000); + try { + if(socket.isConnected()) { + n = new URI( + o.getScheme(), + o.getUserInfo(), + realname, + o.getPort(), + o.getPath(), + o.getQuery(), + o.getFragment() + ); + resolve.add(n); + } + } finally { + socket.close(); + } + } catch (IOException e) { + } finally { + if(!socket.isClosed()) { + try { + socket.close(); + } catch (IOException e) { + // nothing to do. + } + } + } + } + } catch (UnknownHostException | URISyntaxException e) { + // Note: Orig Name already known as valid, based on constructor + } + } + end=resolve.size(); + PLItem[] newCurrent; + if(current==null || current.length!=end) { + newCurrent = new PLItem[end]; + } else { + newCurrent = current; + } + + for(int i=0; i< end; ++i) { + if(newCurrent[i]==null){ + newCurrent[i]=new PLItem(i); + } else { + newCurrent[i].idx=newCurrent[i].order=i; + } + } + synchronized(orig) { + resolved = new URI[end]; + resolve.toArray(resolved); + current = newCurrent; + } + lastRefreshed = System.currentTimeMillis()+minRefresh; + return !resolve.isEmpty(); + } else { + return false; + } + } - protected Socket createSocket() { - return new Socket(); - } - - private class PLItem implements Item { - public int idx,order; - - public PLItem(int i) { - idx = order =i; - } - - public String toString() { - return "Item: " + idx + " order: " + order; - } - } + protected Socket createSocket() { + return new Socket(); + } + + private class PLItem implements Item { + public int idx,order; + + public PLItem(int i) { + idx = order =i; + } + + public String toString() { + return "Item: " + idx + " order: " + order; + } + } - public String toString() { - StringBuilder sb = new StringBuilder(); - boolean first = true; - for(URI uri : orig) { - boolean isResolved=false; - if(uri!=null) { - if(first) { - first = false; - } else { - sb.append(", "); - } - sb.append(uri.toString()); - sb.append(" ["); - for(URI u2 : resolved) { - if(uri.equals(u2)) { - isResolved = true; - break; - } - } - sb.append(isResolved?"X]\n":" ]"); - } - } - return sb.toString(); - } - - public void destroy() { - } + public String toString() { + StringBuilder sb = new StringBuilder(); + boolean first = true; + for(URI uri : orig) { + boolean isResolved=false; + if(uri!=null) { + if(first) { + first = false; + } else { + sb.append(", "); + } + sb.append(uri.toString()); + sb.append(" ["); + for(URI u2 : resolved) { + if(uri.equals(u2)) { + isResolved = true; + break; + } + } + sb.append(isResolved?"X]\n":" ]"); + } + } + return sb.toString(); + } + + public void destroy() { + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java index 23bcd4ad..816dec82 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/locator/SingleEndpointLocator.java @@ -28,65 +28,65 @@ import org.onap.aaf.cadi.Locator; import org.onap.aaf.cadi.LocatorException; public class SingleEndpointLocator implements Locator<URI> { - private final URI uri; - private final static Item item = new Item() {}; - private Date noRetryUntil; - - public SingleEndpointLocator(final URI uri) { - this.uri = uri; - } - - public SingleEndpointLocator(final String endpoint) throws URISyntaxException { - this.uri = new URI(endpoint); - } + private final URI uri; + private final static Item item = new Item() {}; + private Date noRetryUntil; + + public SingleEndpointLocator(final URI uri) { + this.uri = uri; + } + + public SingleEndpointLocator(final String endpoint) throws URISyntaxException { + this.uri = new URI(endpoint); + } - @Override - public URI get(Item item) throws LocatorException { - return uri; - } + @Override + public URI get(Item item) throws LocatorException { + return uri; + } - @Override - public boolean hasItems() { - if(noRetryUntil!=null) { - if(new Date().after(noRetryUntil)) { - noRetryUntil = null; - } else { - return false; - } - } - return true; - } + @Override + public boolean hasItems() { + if(noRetryUntil!=null) { + if(new Date().after(noRetryUntil)) { + noRetryUntil = null; + } else { + return false; + } + } + return true; + } - @Override - public void invalidate(Item item) throws LocatorException { - // one minute timeout, because there is no other item - noRetryUntil = new Date(System.currentTimeMillis()+60000); - } + @Override + public void invalidate(Item item) throws LocatorException { + // one minute timeout, because there is no other item + noRetryUntil = new Date(System.currentTimeMillis()+60000); + } - @Override - public Item best() throws LocatorException { - return item; - } + @Override + public Item best() throws LocatorException { + return item; + } - @Override - public Item first() throws LocatorException { - return item; - } + @Override + public Item first() throws LocatorException { + return item; + } - @Override - public Item next(Item inItem) throws LocatorException { - // only one item - return null; - } + @Override + public Item next(Item inItem) throws LocatorException { + // only one item + return null; + } - @Override - public boolean refresh() { - // Never refreshed - return true; - } + @Override + public boolean refresh() { + // Never refreshed + return true; + } - @Override - public void destroy() { - // Nothing to do here - } + @Override + public void destroy() { + // Nothing to do here + } } diff --git a/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java b/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java index 36906188..3bce5245 100644 --- a/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java +++ b/cadi/client/src/main/java/org/onap/aaf/cadi/routing/GreatCircle.java @@ -24,101 +24,101 @@ package org.onap.aaf.cadi.routing; import org.onap.aaf.misc.env.util.Split; public class GreatCircle { - // Note: multiplying by this constant is faster than calling Math equivalent function - private static final double DEGREES_2_RADIANS = Math.PI/180.0; - - public static final double DEGREES_2_NM = 60; - public static final double DEGREES_2_KM = DEGREES_2_NM * 1.852; // 1.852 is exact ratio per 1929 Standard Treaty, adopted US 1954 - public static final double DEGREES_2_MI = DEGREES_2_NM * 1.1507795; - - /** - * - * Calculate the length of an arc on a perfect sphere based on Latitude and Longitudes of two points - * Parameters are in Degrees (i.e. the coordinate system you get from GPS, Mapping WebSites, Phones, etc) - * - * L1 = Latitude of point A - * G1 = Longitude of point A - * L2 = Latitude of point B - * G2 = Longitude of point B - * - * d = acos (sin(L1)*sin(L2) + cos(L1)*cos(L2)*cos(G1 - G2)) - * - * Returns answer in Degrees - * - * Since there are 60 degrees per nautical miles, you can convert to NM by multiplying by 60 - * - * Essential formula from a Princeton website, the "Law of Cosines" method. - * - * Refactored cleaned up for speed Jonathan 3/8/2013 - * - * @param latA - * @param lonA - * @param latB - * @param lonB - * @return - */ - public static double calc(double latA, double lonA, double latB, double lonB) { - // Formula requires Radians. Expect Params to be Coordinates (Degrees) - // Simple ratio, quicker than calling Math.toRadians() - latA *= DEGREES_2_RADIANS; - lonA *= DEGREES_2_RADIANS; - latB *= DEGREES_2_RADIANS; - lonB *= DEGREES_2_RADIANS; + // Note: multiplying by this constant is faster than calling Math equivalent function + private static final double DEGREES_2_RADIANS = Math.PI/180.0; + + public static final double DEGREES_2_NM = 60; + public static final double DEGREES_2_KM = DEGREES_2_NM * 1.852; // 1.852 is exact ratio per 1929 Standard Treaty, adopted US 1954 + public static final double DEGREES_2_MI = DEGREES_2_NM * 1.1507795; + + /** + * + * Calculate the length of an arc on a perfect sphere based on Latitude and Longitudes of two points + * Parameters are in Degrees (i.e. the coordinate system you get from GPS, Mapping WebSites, Phones, etc) + * + * L1 = Latitude of point A + * G1 = Longitude of point A + * L2 = Latitude of point B + * G2 = Longitude of point B + * + * d = acos (sin(L1)*sin(L2) + cos(L1)*cos(L2)*cos(G1 - G2)) + * + * Returns answer in Degrees + * + * Since there are 60 degrees per nautical miles, you can convert to NM by multiplying by 60 + * + * Essential formula from a Princeton website, the "Law of Cosines" method. + * + * Refactored cleaned up for speed Jonathan 3/8/2013 + * + * @param latA + * @param lonA + * @param latB + * @param lonB + * @return + */ + public static double calc(double latA, double lonA, double latB, double lonB) { + // Formula requires Radians. Expect Params to be Coordinates (Degrees) + // Simple ratio, quicker than calling Math.toRadians() + latA *= DEGREES_2_RADIANS; + lonA *= DEGREES_2_RADIANS; + latB *= DEGREES_2_RADIANS; + lonB *= DEGREES_2_RADIANS; - return Math.acos( - Math.sin(latA) * Math.sin(latB) + - Math.cos(latA) * Math.cos(latB) * Math.cos(lonA-lonB) - ) - / DEGREES_2_RADIANS; - } - - /** - * Convert from "Lat,Long Lat,Long" String format - * "Lat,Long,Lat,Long" Format - * or all four entries "Lat Long Lat Long" - * - * (Convenience function) - * - * Since Distance is positive, a "-1" indicates an error in String formatting - */ - public static double calc(String ... coords) { - try { - String [] array; - switch(coords.length) { - case 1: - array = Split.split(',',coords[0]); - if(array.length!=4)return -1; - return calc( - Double.parseDouble(array[0]), - Double.parseDouble(array[1]), - Double.parseDouble(array[2]), - Double.parseDouble(array[3]) - ); - case 2: - array = Split.split(',',coords[0]); - String [] array2 = Split.split(',',coords[1]); - if(array.length!=2 || array2.length!=2)return -1; - return calc( - Double.parseDouble(array[0]), - Double.parseDouble(array[1]), - Double.parseDouble(array2[0]), - Double.parseDouble(array2[1]) - ); - case 4: - return calc( - Double.parseDouble(coords[0]), - Double.parseDouble(coords[1]), - Double.parseDouble(coords[2]), - Double.parseDouble(coords[3]) - ); - - default: - return -1; - } - } catch (NumberFormatException e) { - return -1; - } - } + return Math.acos( + Math.sin(latA) * Math.sin(latB) + + Math.cos(latA) * Math.cos(latB) * Math.cos(lonA-lonB) + ) + / DEGREES_2_RADIANS; + } + + /** + * Convert from "Lat,Long Lat,Long" String format + * "Lat,Long,Lat,Long" Format + * or all four entries "Lat Long Lat Long" + * + * (Convenience function) + * + * Since Distance is positive, a "-1" indicates an error in String formatting + */ + public static double calc(String ... coords) { + try { + String [] array; + switch(coords.length) { + case 1: + array = Split.split(',',coords[0]); + if(array.length!=4)return -1; + return calc( + Double.parseDouble(array[0]), + Double.parseDouble(array[1]), + Double.parseDouble(array[2]), + Double.parseDouble(array[3]) + ); + case 2: + array = Split.split(',',coords[0]); + String [] array2 = Split.split(',',coords[1]); + if(array.length!=2 || array2.length!=2)return -1; + return calc( + Double.parseDouble(array[0]), + Double.parseDouble(array[1]), + Double.parseDouble(array2[0]), + Double.parseDouble(array2[1]) + ); + case 4: + return calc( + Double.parseDouble(coords[0]), + Double.parseDouble(coords[1]), + Double.parseDouble(coords[2]), + Double.parseDouble(coords[3]) + ); + + default: + return -1; + } + } catch (NumberFormatException e) { + return -1; + } + } } @@ -132,30 +132,30 @@ public class GreatCircle { //* @return //*/ //public static double calc3(double alat, double alon, double blat, double blon) { -// alat *= DEGREES_2_RADIANS; -// alon *= DEGREES_2_RADIANS; -// blat *= DEGREES_2_RADIANS; -// blon *= DEGREES_2_RADIANS; -// return 2 * Math.asin( -// Math.min(1, Math.sqrt( -// Math.pow(Math.sin((blat-alat)/2), 2) + -// (Math.cos(alat)*Math.cos(blat)* -// Math.pow( -// Math.sin((blon-alon)/2),2) -// ) -// ) -// ) -// ) -// / DEGREES_2_RADIANS; +// alat *= DEGREES_2_RADIANS; +// alon *= DEGREES_2_RADIANS; +// blat *= DEGREES_2_RADIANS; +// blon *= DEGREES_2_RADIANS; +// return 2 * Math.asin( +// Math.min(1, Math.sqrt( +// Math.pow(Math.sin((blat-alat)/2), 2) + +// (Math.cos(alat)*Math.cos(blat)* +// Math.pow( +// Math.sin((blon-alon)/2),2) +// ) +// ) +// ) +// ) +// / DEGREES_2_RADIANS; //} // //This is a MEAN radius. The Earth is not perfectly spherical -// public static final double EARTH_RADIUS_KM = 6371.0; -// public static final double EARTH_RADIUS_NM = 3440.07; -// public static final double KM_2_MILES_RATIO = 0.621371192; +// public static final double EARTH_RADIUS_KM = 6371.0; +// public static final double EARTH_RADIUS_NM = 3440.07; +// public static final double KM_2_MILES_RATIO = 0.621371192; ///** //* Code on Internet based on Unknown book. Lat/Long is in Degrees //* @param alat @@ -165,20 +165,20 @@ public class GreatCircle { //* @return //*/ //public static double calc1(double alat, double alon, double blat, double blon) { -// alat *= DEGREES_2_RADIANS; -// alon *= DEGREES_2_RADIANS; -// blat *= DEGREES_2_RADIANS; -// blon *= DEGREES_2_RADIANS; -// -// // Reused values -// double cosAlat,cosBlat; -// -// return Math.acos( -// ((cosAlat=Math.cos(alat))*Math.cos(alon)*(cosBlat=Math.cos(blat))*Math.cos(blon)) + -// (cosAlat*Math.sin(alon)*cosBlat*Math.sin(blon)) + -// (Math.sin(alat)*Math.sin(blat)) -// )/DEGREES_2_RADIANS; -// +// alat *= DEGREES_2_RADIANS; +// alon *= DEGREES_2_RADIANS; +// blat *= DEGREES_2_RADIANS; +// blon *= DEGREES_2_RADIANS; +// +// // Reused values +// double cosAlat,cosBlat; +// +// return Math.acos( +// ((cosAlat=Math.cos(alat))*Math.cos(alon)*(cosBlat=Math.cos(blat))*Math.cos(blon)) + +// (cosAlat*Math.sin(alon)*cosBlat*Math.sin(blon)) + +// (Math.sin(alat)*Math.sin(blat)) +// )/DEGREES_2_RADIANS; +// //} /* diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java index cc67946e..65daa7b6 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsAuthentication.java @@ -34,70 +34,70 @@ import java.io.PrintStream; import java.net.HttpURLConnection; public class JU_AbsAuthentication { - - private final static String ID = "id"; - private final static String PASSWORD = "password"; - private final static String WARNING = "Your service has 1000 consecutive bad service " + - "logins to AAF. AAF Access will be disabled after 10000\n"; - - private static ByteArrayOutputStream errStream; - - @Before - public void setup() { - errStream = new ByteArrayOutputStream(); - System.setErr(new PrintStream(errStream)); - } - - @After - public void tearDown() { - System.setErr(System.err); - } + + private final static String ID = "id"; + private final static String PASSWORD = "password"; + private final static String WARNING = "Your service has 1000 consecutive bad service " + + "logins to AAF. AAF Access will be disabled after 10000\n"; + + private static ByteArrayOutputStream errStream; + + @Before + public void setup() { + errStream = new ByteArrayOutputStream(); + System.setErr(new PrintStream(errStream)); + } + + @After + public void tearDown() { + System.setErr(System.err); + } - @Test - public void test() throws IOException, InterruptedException { - AuthStub stub = new AuthStub(null, null, null); - assertThat(stub.getID(), is(nullValue())); - assertThat(stub.headValue(), is("")); - assertThat(stub.count(), is(0)); - - stub.setUser(ID); - assertThat(stub.getID(), is(ID)); + @Test + public void test() throws IOException, InterruptedException { + AuthStub stub = new AuthStub(null, null, null); + assertThat(stub.getID(), is(nullValue())); + assertThat(stub.headValue(), is("")); + assertThat(stub.count(), is(0)); + + stub.setUser(ID); + assertThat(stub.getID(), is(ID)); - stub = new AuthStub(null, ID, PASSWORD.getBytes()); - assertThat(stub.getID(), is(ID)); - assertThat(stub.headValue(), is(PASSWORD)); - assertThat(stub.count(), is(0)); - - assertThat(stub.setLastResponse(200), is(0)); - assertThat(stub.isDenied(), is(false)); + stub = new AuthStub(null, ID, PASSWORD.getBytes()); + assertThat(stub.getID(), is(ID)); + assertThat(stub.headValue(), is(PASSWORD)); + assertThat(stub.count(), is(0)); + + assertThat(stub.setLastResponse(200), is(0)); + assertThat(stub.isDenied(), is(false)); - for (int i = 1; i <= 10; i++) { - assertThat(stub.setLastResponse(401), is(i)); - assertThat(stub.isDenied(), is(false)); - } - assertThat(stub.setLastResponse(401), is(11)); - assertThat(stub.isDenied(), is(true)); + for (int i = 1; i <= 10; i++) { + assertThat(stub.setLastResponse(401), is(i)); + assertThat(stub.isDenied(), is(false)); + } + assertThat(stub.setLastResponse(401), is(11)); + assertThat(stub.isDenied(), is(true)); - stub.setCount(999); - assertThat(stub.setLastResponse(401), is(1000)); - assertThat(errStream.toString(), is(WARNING)); - - // coverage... - stub.setLastMiss(1); - assertThat(stub.isDenied(), is(false)); - } - - private class AuthStub extends AbsAuthentication<HttpURLConnection> { + stub.setCount(999); + assertThat(stub.setLastResponse(401), is(1000)); + assertThat(errStream.toString(), is(WARNING)); + + // coverage... + stub.setLastMiss(1); + assertThat(stub.isDenied(), is(false)); + } + + private class AuthStub extends AbsAuthentication<HttpURLConnection> { - public AuthStub(SecurityInfoC<HttpURLConnection> securityInfo, String user, byte[] headValue) - throws IOException { super(securityInfo, user, headValue); } + public AuthStub(SecurityInfoC<HttpURLConnection> securityInfo, String user, byte[] headValue) + throws IOException { super(securityInfo, user, headValue); } - @Override public void setSecurity(HttpURLConnection client) throws CadiException { } - @Override public void setUser(String id) { super.setUser(id); } - @Override public String headValue() throws IOException { return super.headValue(); } - - public void setLastMiss(long lastMiss) { this.lastMiss = lastMiss; } - public void setCount(int count) { this.count = count; } - } + @Override public void setSecurity(HttpURLConnection client) throws CadiException { } + @Override public void setUser(String id) { super.setUser(id); } + @Override public String headValue() throws IOException { return super.headValue(); } + + public void setLastMiss(long lastMiss) { this.lastMiss = lastMiss; } + public void setCount(int count) { this.count = count; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java index 507f90f4..c7720775 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_AbsTransferSS.java @@ -34,39 +34,39 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; import java.net.HttpURLConnection; public class JU_AbsTransferSS { - - @Mock TaggedPrincipal princMock; - @Mock SecurityInfoC<HttpURLConnection> siMock; - - private static final String princName = "name"; - private static final String princTag = "tag"; - private static final String app = "app"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - when(princMock.getName()).thenReturn(princName); - when(princMock.tag()).thenReturn(princTag); - } + + @Mock TaggedPrincipal princMock; + @Mock SecurityInfoC<HttpURLConnection> siMock; + + private static final String princName = "name"; + private static final String princTag = "tag"; + private static final String app = "app"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + when(princMock.getName()).thenReturn(princName); + when(princMock.tag()).thenReturn(princTag); + } - @Test - public void test() { - TransferSSStub stub = new TransferSSStub(princMock, app); - assertThat(stub.getID(), is(princName)); - assertThat(stub.getValue(), is(princName + ':' + app + ':' + princTag + ':' + "AS")); - - stub = new TransferSSStub(null, app, siMock); - assertThat(stub.getID(), is("")); - assertThat(stub.getValue(), is(nullValue())); - } - - private class TransferSSStub extends AbsTransferSS<HttpURLConnection> { - public TransferSSStub(TaggedPrincipal principal, String app) { super(principal, app); } - public TransferSSStub(TaggedPrincipal principal, String app, SecurityInfoC<HttpURLConnection> si) { super(principal, app, si); } - @Override public void setSecurity(HttpURLConnection client) throws CadiException { } - @Override public int setLastResponse(int respCode) { return 0; } - public String getValue() { return value; } - } + @Test + public void test() { + TransferSSStub stub = new TransferSSStub(princMock, app); + assertThat(stub.getID(), is(princName)); + assertThat(stub.getValue(), is(princName + ':' + app + ':' + princTag + ':' + "AS")); + + stub = new TransferSSStub(null, app, siMock); + assertThat(stub.getID(), is("")); + assertThat(stub.getValue(), is(nullValue())); + } + + private class TransferSSStub extends AbsTransferSS<HttpURLConnection> { + public TransferSSStub(TaggedPrincipal principal, String app) { super(principal, app); } + public TransferSSStub(TaggedPrincipal principal, String app, SecurityInfoC<HttpURLConnection> si) { super(principal, app, si); } + @Override public void setSecurity(HttpURLConnection client) throws CadiException { } + @Override public int setLastResponse(int respCode) { return 0; } + public String getValue() { return value; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java index ad0bd535..97fa9d21 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Future.java @@ -29,17 +29,17 @@ import org.onap.aaf.cadi.client.Future; public class JU_Future { - @Test - public void test() { - @SuppressWarnings("unused") - Future<Integer> f = new FutureStub(); - } - - private class FutureStub extends Future<Integer> { - @Override public boolean get(int timeout) throws CadiException { return false; } - @Override public int code() { return 0; } - @Override public String body() { return null; } - @Override public String header(String tag) { return null; } - } + @Test + public void test() { + @SuppressWarnings("unused") + Future<Integer> f = new FutureStub(); + } + + private class FutureStub extends Future<Integer> { + @Override public boolean get(int timeout) throws CadiException { return false; } + @Override public int code() { return 0; } + @Override public String body() { return null; } + @Override public String header(String tag) { return null; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java index 079951f5..dd9b0539 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Holder.java @@ -29,17 +29,17 @@ import org.onap.aaf.cadi.client.Holder; public class JU_Holder { - @Test - public void test() { - String str1 = "a string"; - String str2 = "another string"; - Holder<String> holder = new Holder<String>(str1); - assertThat(holder.get(), is(str1)); - assertThat(holder.toString(), is(str1)); - - holder.set(str2); - assertThat(holder.get(), is(str2)); - assertThat(holder.toString(), is(str2)); - } + @Test + public void test() { + String str1 = "a string"; + String str2 = "another string"; + Holder<String> holder = new Holder<String>(str1); + assertThat(holder.get(), is(str1)); + assertThat(holder.toString(), is(str1)); + + holder.set(str2); + assertThat(holder.get(), is(str2)); + assertThat(holder.toString(), is(str2)); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java index 886c5d84..d33811e3 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Rcli.java @@ -55,228 +55,228 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; public class JU_Rcli { - @Mock RosettaDF<HttpURLConnection> dfMock; - @Mock RosettaData<HttpURLConnection> dataMock; - @Mock HttpURLConnection conMock; - @Mock HttpServletRequest reqMock; - @Mock HttpServletResponse respMock; - @Mock ServletInputStream isMock; - - private final static String uriString = "example.com"; - private final static String apiVersion = "v1.0"; - private final static String contentType = "contentType"; - - private static URI uri; - private static Enumeration<String> enumeration; - - private Client client; - - @Before - public void setup() throws URISyntaxException, IOException { - MockitoAnnotations.initMocks(this); - - when(dfMock.getTypeClass()).thenReturn(HttpURLConnection.class); - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.out((TYPE) any())).thenReturn(dataMock); - - when(reqMock.getInputStream()).thenReturn(isMock); - when(isMock.read((byte[]) any())).thenReturn(-1); - - uri = new URI(uriString); - enumeration = new CustomEnumeration(); - client = new Client(); - } - - @Test - public void createTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.XML); - - rcli.create(null, contentType, dfMock, conMock); - rcli.create("No question mark", contentType, dfMock, conMock); - rcli.create("question?mark", contentType, dfMock, conMock); - - rcli.create(null, dfMock, conMock); - rcli.create("No question mark", dfMock, conMock); - rcli.create("question?mark", dfMock, conMock); - - rcli.create(null, HttpURLConnection.class, dfMock, conMock); - rcli.create("No question mark", HttpURLConnection.class, dfMock, conMock); - rcli.create("question?mark", HttpURLConnection.class, dfMock, conMock); - - rcli.create(null, HttpURLConnection.class); - rcli.create("No question mark", HttpURLConnection.class); - rcli.create("question?mark", HttpURLConnection.class); - - rcli.create(null, contentType); - rcli.create("No question mark", contentType); - rcli.create("question?mark", contentType); - } - - @Test - public void postFormTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - - rcli.type(Data.TYPE.DEFAULT); - rcli.postForm(null, dfMock); - rcli.postForm("No question mark", dfMock); - rcli.postForm("question?mark", dfMock); - - rcli.type(Data.TYPE.JSON); - rcli.postForm("question?mark", dfMock); - - rcli.type(Data.TYPE.XML); - rcli.postForm("question?mark", dfMock); - - } - - @Test - public void readPostTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.readPost(null, dfMock, conMock); - rcli.readPost("No question mark", dfMock, conMock); - rcli.readPost("question?mark", dfMock, conMock); - - rcli.readPost(null, dfMock, conMock, dfMock); - rcli.readPost("No question mark", dfMock, conMock, dfMock); - rcli.readPost("question?mark", dfMock, conMock, dfMock); - - rcli.readPost("First string", "Second string"); - } - - @Test - public void readTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.read("First string", "Second string", "Third string", "Fourth string"); - rcli.read("First string", "Second string", dfMock, "Third string", "Fourth string"); - rcli.read("First string", dfMock, "Third string", "Fourth string"); - rcli.read("First string", HttpURLConnection.class ,dfMock); - } - - @Test - public void updateTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.update("First string", "Second string", dfMock, conMock); - rcli.update("First string", dfMock, conMock); - rcli.update("First string", HttpURLConnection.class, dfMock, conMock); - rcli.update("First string"); - rcli.updateRespondString("First string", dfMock, conMock); - } - - @Test - public void deleteTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.delete("First string", "Second string", dfMock, conMock); - rcli.delete("First string", dfMock, conMock); - rcli.delete("First string", HttpURLConnection.class, dfMock, conMock); - rcli.delete("First string", HttpURLConnection.class); - rcli.delete("First string", "Second string"); - } - - @Test - public void transferTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - when(reqMock.getRequestURI()).thenReturn(uriString); - when(reqMock.getHeaderNames()).thenReturn(enumeration); - rcli.transfer(reqMock, respMock, "string", 200); - - // coverage... - when(reqMock.getMethod()).thenReturn("GET"); - rcli.transfer(reqMock, respMock, "string", 200); - } - - @Test(expected = CadiException.class) - public void transferThrowsTest() throws APIException, CadiException { - RcliStub rcli = new RcliStub(uri); - rcli.type(Data.TYPE.DEFAULT); - - rcli.transfer(reqMock, respMock, "string", 200); - } - - @Test - public void accessorMutatorTest() throws URISyntaxException { - RcliStub rcli = new RcliStub(); - Rcli<?> rcliClone = rcli.forUser(null); - - rcli = new RcliStub(uri); - assertThat(rcli.toString(), is(uriString)); - assertThat(rcli.getURI(), is(uri)); - assertThat(rcli.getReadTimeout(), is(5000)); - assertThat(rcli.getConnectionTimeout(), is(3000)); - - rcli.connectionTimeout(3001); - assertThat(rcli.getConnectionTimeout(), is(3001)); - rcli.readTimeout(5001); - assertThat(rcli.getReadTimeout(), is(5001)); - rcli.apiVersion(apiVersion); - assertThat(rcli.isApiVersion(apiVersion), is(true)); - rcli.type(Data.TYPE.XML); - assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml;version=" + apiVersion)); - rcli.apiVersion(null); - assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml")); - - rcliClone = rcli.forUser(null); - assertThat(rcliClone.toString(), is(uriString)); - } - - private class RcliStub extends Rcli<HttpURLConnection> { - public RcliStub() { super(); } - public RcliStub(URI uri) { this.uri = uri; } - @Override public void setSecuritySetter(SecuritySetter<HttpURLConnection> ss) { } - @Override public SecuritySetter<HttpURLConnection> getSecuritySetter() { return null; } - @Override protected Rcli<HttpURLConnection> clone(URI uri, SecuritySetter<HttpURLConnection> ss) { return this; } - @Override public void invalidate() throws CadiException { } - @Override protected EClient<HttpURLConnection> client() throws CadiException { return client; } - public int getReadTimeout() { return readTimeout; } - public int getConnectionTimeout() { return connectionTimeout; } - } - - private class CustomEnumeration implements Enumeration<String> { - private int idx = 0; - private final String[] elements = {"This", "is", "a", "test"}; - @Override - public String nextElement() { - return idx >= elements.length ? null : elements[idx++]; - } - @Override - public boolean hasMoreElements() { - return idx < elements.length; - } - } - - private class Client implements EClient<HttpURLConnection> { - private Transfer transfer; - @Override public void setPayload(Transfer transfer) { this.transfer = transfer; } - @Override public void setMethod(String meth) { } - @Override public void setPathInfo(String pathinfo) { } - @Override public void addHeader(String tag, String value) { } - @Override public void setQueryParams(String q) { } - @Override public void setFragment(String f) { } - @Override public void send() throws APIException { - try { - if (transfer != null) { - transfer.transfer(new PrintStream(new ByteArrayOutputStream())); - } - } catch (IOException e) { - } - } - @Override public <T> Future<T> futureCreate(Class<T> t) { return null; } - @Override public Future<String> futureReadString() { return null; } - @Override public <T> Future<T> futureRead(RosettaDF<T> df, TYPE type) { return null; } - @Override public <T> Future<T> future(T t) { return null; } - @Override public Future<Void> future(HttpServletResponse resp, int expected) throws APIException { return null; } - } - - //private class FutureStub implements Future<String> { - //} + @Mock RosettaDF<HttpURLConnection> dfMock; + @Mock RosettaData<HttpURLConnection> dataMock; + @Mock HttpURLConnection conMock; + @Mock HttpServletRequest reqMock; + @Mock HttpServletResponse respMock; + @Mock ServletInputStream isMock; + + private final static String uriString = "example.com"; + private final static String apiVersion = "v1.0"; + private final static String contentType = "contentType"; + + private static URI uri; + private static Enumeration<String> enumeration; + + private Client client; + + @Before + public void setup() throws URISyntaxException, IOException { + MockitoAnnotations.initMocks(this); + + when(dfMock.getTypeClass()).thenReturn(HttpURLConnection.class); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.out((TYPE) any())).thenReturn(dataMock); + + when(reqMock.getInputStream()).thenReturn(isMock); + when(isMock.read((byte[]) any())).thenReturn(-1); + + uri = new URI(uriString); + enumeration = new CustomEnumeration(); + client = new Client(); + } + + @Test + public void createTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.XML); + + rcli.create(null, contentType, dfMock, conMock); + rcli.create("No question mark", contentType, dfMock, conMock); + rcli.create("question?mark", contentType, dfMock, conMock); + + rcli.create(null, dfMock, conMock); + rcli.create("No question mark", dfMock, conMock); + rcli.create("question?mark", dfMock, conMock); + + rcli.create(null, HttpURLConnection.class, dfMock, conMock); + rcli.create("No question mark", HttpURLConnection.class, dfMock, conMock); + rcli.create("question?mark", HttpURLConnection.class, dfMock, conMock); + + rcli.create(null, HttpURLConnection.class); + rcli.create("No question mark", HttpURLConnection.class); + rcli.create("question?mark", HttpURLConnection.class); + + rcli.create(null, contentType); + rcli.create("No question mark", contentType); + rcli.create("question?mark", contentType); + } + + @Test + public void postFormTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + + rcli.type(Data.TYPE.DEFAULT); + rcli.postForm(null, dfMock); + rcli.postForm("No question mark", dfMock); + rcli.postForm("question?mark", dfMock); + + rcli.type(Data.TYPE.JSON); + rcli.postForm("question?mark", dfMock); + + rcli.type(Data.TYPE.XML); + rcli.postForm("question?mark", dfMock); + + } + + @Test + public void readPostTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.readPost(null, dfMock, conMock); + rcli.readPost("No question mark", dfMock, conMock); + rcli.readPost("question?mark", dfMock, conMock); + + rcli.readPost(null, dfMock, conMock, dfMock); + rcli.readPost("No question mark", dfMock, conMock, dfMock); + rcli.readPost("question?mark", dfMock, conMock, dfMock); + + rcli.readPost("First string", "Second string"); + } + + @Test + public void readTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.read("First string", "Second string", "Third string", "Fourth string"); + rcli.read("First string", "Second string", dfMock, "Third string", "Fourth string"); + rcli.read("First string", dfMock, "Third string", "Fourth string"); + rcli.read("First string", HttpURLConnection.class ,dfMock); + } + + @Test + public void updateTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.update("First string", "Second string", dfMock, conMock); + rcli.update("First string", dfMock, conMock); + rcli.update("First string", HttpURLConnection.class, dfMock, conMock); + rcli.update("First string"); + rcli.updateRespondString("First string", dfMock, conMock); + } + + @Test + public void deleteTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.delete("First string", "Second string", dfMock, conMock); + rcli.delete("First string", dfMock, conMock); + rcli.delete("First string", HttpURLConnection.class, dfMock, conMock); + rcli.delete("First string", HttpURLConnection.class); + rcli.delete("First string", "Second string"); + } + + @Test + public void transferTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + when(reqMock.getRequestURI()).thenReturn(uriString); + when(reqMock.getHeaderNames()).thenReturn(enumeration); + rcli.transfer(reqMock, respMock, "string", 200); + + // coverage... + when(reqMock.getMethod()).thenReturn("GET"); + rcli.transfer(reqMock, respMock, "string", 200); + } + + @Test(expected = CadiException.class) + public void transferThrowsTest() throws APIException, CadiException { + RcliStub rcli = new RcliStub(uri); + rcli.type(Data.TYPE.DEFAULT); + + rcli.transfer(reqMock, respMock, "string", 200); + } + + @Test + public void accessorMutatorTest() throws URISyntaxException { + RcliStub rcli = new RcliStub(); + Rcli<?> rcliClone = rcli.forUser(null); + + rcli = new RcliStub(uri); + assertThat(rcli.toString(), is(uriString)); + assertThat(rcli.getURI(), is(uri)); + assertThat(rcli.getReadTimeout(), is(5000)); + assertThat(rcli.getConnectionTimeout(), is(3000)); + + rcli.connectionTimeout(3001); + assertThat(rcli.getConnectionTimeout(), is(3001)); + rcli.readTimeout(5001); + assertThat(rcli.getReadTimeout(), is(5001)); + rcli.apiVersion(apiVersion); + assertThat(rcli.isApiVersion(apiVersion), is(true)); + rcli.type(Data.TYPE.XML); + assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml;version=" + apiVersion)); + rcli.apiVersion(null); + assertThat(rcli.typeString(HttpURLConnection.class), is("application/HttpURLConnection+xml")); + + rcliClone = rcli.forUser(null); + assertThat(rcliClone.toString(), is(uriString)); + } + + private class RcliStub extends Rcli<HttpURLConnection> { + public RcliStub() { super(); } + public RcliStub(URI uri) { this.uri = uri; } + @Override public void setSecuritySetter(SecuritySetter<HttpURLConnection> ss) { } + @Override public SecuritySetter<HttpURLConnection> getSecuritySetter() { return null; } + @Override protected Rcli<HttpURLConnection> clone(URI uri, SecuritySetter<HttpURLConnection> ss) { return this; } + @Override public void invalidate() throws CadiException { } + @Override protected EClient<HttpURLConnection> client() throws CadiException { return client; } + public int getReadTimeout() { return readTimeout; } + public int getConnectionTimeout() { return connectionTimeout; } + } + + private class CustomEnumeration implements Enumeration<String> { + private int idx = 0; + private final String[] elements = {"This", "is", "a", "test"}; + @Override + public String nextElement() { + return idx >= elements.length ? null : elements[idx++]; + } + @Override + public boolean hasMoreElements() { + return idx < elements.length; + } + } + + private class Client implements EClient<HttpURLConnection> { + private Transfer transfer; + @Override public void setPayload(Transfer transfer) { this.transfer = transfer; } + @Override public void setMethod(String meth) { } + @Override public void setPathInfo(String pathinfo) { } + @Override public void addHeader(String tag, String value) { } + @Override public void setQueryParams(String q) { } + @Override public void setFragment(String f) { } + @Override public void send() throws APIException { + try { + if (transfer != null) { + transfer.transfer(new PrintStream(new ByteArrayOutputStream())); + } + } catch (IOException e) { + } + } + @Override public <T> Future<T> futureCreate(Class<T> t) { return null; } + @Override public Future<String> futureReadString() { return null; } + @Override public <T> Future<T> futureRead(RosettaDF<T> df, TYPE type) { return null; } + @Override public <T> Future<T> future(T t) { return null; } + @Override public Future<Void> future(HttpServletResponse resp, int expected) throws APIException { return null; } + } + + //private class FutureStub implements Future<String> { + //} } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java index 05ca27f3..41570980 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Result.java @@ -28,24 +28,24 @@ import org.junit.*; import org.onap.aaf.cadi.client.Result; public class JU_Result { - - private static final int OK = 200; - private static final int NOT_FOUND = 404; + + private static final int OK = 200; + private static final int NOT_FOUND = 404; - @Test - public void test() { - Result<Integer> result; - result = Result.ok(OK, 10); - assertThat(result.toString(), is("Code: 200")); - assertThat(result.isOK(), is(true)); - - result = Result.err(NOT_FOUND, "File not found"); - assertThat(result.toString(), is("Code: 404 = File not found")); - assertThat(result.isOK(), is(false)); + @Test + public void test() { + Result<Integer> result; + result = Result.ok(OK, 10); + assertThat(result.toString(), is("Code: 200")); + assertThat(result.isOK(), is(true)); + + result = Result.err(NOT_FOUND, "File not found"); + assertThat(result.toString(), is("Code: 404 = File not found")); + assertThat(result.isOK(), is(false)); - result = Result.err(result); - assertThat(result.toString(), is("Code: 404 = File not found")); - assertThat(result.isOK(), is(false)); - } - + result = Result.err(result); + assertThat(result.toString(), is("Code: 404 = File not found")); + assertThat(result.isOK(), is(false)); + } + } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java index 84863744..200b393d 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/client/test/JU_Retryable.java @@ -35,25 +35,25 @@ import org.onap.aaf.misc.env.APIException; public class JU_Retryable { - @Test - public void test() { - RetryableStub retry = new RetryableStub(); - assertThat(retry.item(), is(nullValue())); - assertThat(retry.lastClient(), is(nullValue())); - - Locator.Item item = null; - assertThat(retry.item(item), is(item)); - - retry = new RetryableStub(retry); - assertThat(retry.item(), is(nullValue())); - assertThat(retry.lastClient(), is(nullValue())); - assertThat(retry.item(item), is(item)); - } - - private class RetryableStub extends Retryable<Integer> { - public RetryableStub() { super(); } - public RetryableStub(Retryable<?> ret) { super(ret); } - @Override public Integer code(Rcli<?> client) throws CadiException, ConnectException, APIException { return null; } - } + @Test + public void test() { + RetryableStub retry = new RetryableStub(); + assertThat(retry.item(), is(nullValue())); + assertThat(retry.lastClient(), is(nullValue())); + + Locator.Item item = null; + assertThat(retry.item(item), is(item)); + + retry = new RetryableStub(retry); + assertThat(retry.item(), is(nullValue())); + assertThat(retry.lastClient(), is(nullValue())); + assertThat(retry.item(item), is(item)); + } + + private class RetryableStub extends Retryable<Integer> { + public RetryableStub() { super(); } + public RetryableStub(Retryable<?> ret) { super(ret); } + @Override public Integer code(Rcli<?> client) throws CadiException, ConnectException, APIException { return null; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java index be12e7ac..4bb44e10 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HAuthorizationHeader.java @@ -36,44 +36,44 @@ import org.onap.aaf.cadi.http.HAuthorizationHeader; public class JU_HAuthorizationHeader { - @Mock - SecurityInfoC<HttpURLConnection> siMock; + @Mock + SecurityInfoC<HttpURLConnection> siMock; - @Mock - HttpsURLConnection hucsMock; - - @Mock - HttpURLConnection hucMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } + @Mock + HttpsURLConnection hucsMock; + + @Mock + HttpURLConnection hucMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } - @Test - public void test() throws IOException, CadiException { - HAuthorizationHeader header = new HAuthorizationHeader(siMock, null, null); - header.setSecurity(hucsMock); - header.setSecurity(hucMock); + @Test + public void test() throws IOException, CadiException { + HAuthorizationHeader header = new HAuthorizationHeader(siMock, null, null); + header.setSecurity(hucsMock); + header.setSecurity(hucMock); - header = new HAuthorizationHeader(null, null, null); - header.setSecurity(hucsMock); - } - - @Test(expected = CadiException.class) - public void throwsWhenDeniedTest() throws CadiException, IOException { - HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { - @Override public boolean isDenied() { return true; } - }; - header.setSecurity(null); - } + header = new HAuthorizationHeader(null, null, null); + header.setSecurity(hucsMock); + } + + @Test(expected = CadiException.class) + public void throwsWhenDeniedTest() throws CadiException, IOException { + HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { + @Override public boolean isDenied() { return true; } + }; + header.setSecurity(null); + } - @Test(expected = CadiException.class) - public void throwsTest() throws CadiException, IOException { - HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { - @Override public String headValue() throws IOException { throw new IOException(); } - }; - header.setSecurity(null); - } + @Test(expected = CadiException.class) + public void throwsTest() throws CadiException, IOException { + HAuthorizationHeader header = new HAuthorizationHeader(siMock, "string1", "string2") { + @Override public String headValue() throws IOException { throw new IOException(); } + }; + header.setSecurity(null); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java index fa0a673f..d0655979 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HBasicAuthSS.java @@ -39,57 +39,57 @@ import org.onap.aaf.cadi.http.HSecurityInfoInit; import org.onap.aaf.cadi.principal.BasicPrincipal; public class JU_HBasicAuthSS { - - @Mock - BasicPrincipal bpMock; - - private SecurityInfoC<HttpURLConnection> si; - private PropAccess access; - - private final static String id = "id"; - private final static String password = "password"; - - @Before - public void setup() throws CadiException, IOException { - MockitoAnnotations.initMocks(this); - - when(bpMock.getName()).thenReturn(id); - when(bpMock.getCred()).thenReturn(password.getBytes()); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.AAF_APPID, id); - access.setProperty(Config.AAF_APPPASS, access.encrypt(password)); + + @Mock + BasicPrincipal bpMock; + + private SecurityInfoC<HttpURLConnection> si; + private PropAccess access; + + private final static String id = "id"; + private final static String password = "password"; + + @Before + public void setup() throws CadiException, IOException { + MockitoAnnotations.initMocks(this); + + when(bpMock.getName()).thenReturn(id); + when(bpMock.getCred()).thenReturn(password.getBytes()); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.AAF_APPID, id); + access.setProperty(Config.AAF_APPPASS, access.encrypt(password)); - si = SecurityInfoC.instance(access, HttpURLConnection.class); - } + si = SecurityInfoC.instance(access, HttpURLConnection.class); + } - @Test - public void test() throws IOException { - // All the constructors accomplish the same thing - @SuppressWarnings("unused") - HBasicAuthSS auth = new HBasicAuthSS(si); - - // TODO: While these test _should_ pass, and they _do_ pass on my local machine, they won't - // pass when then onap jobbuilder runs them. Good luck! -// assertThat(auth.getID(), is(id)); + @Test + public void test() throws IOException { + // All the constructors accomplish the same thing + @SuppressWarnings("unused") + HBasicAuthSS auth = new HBasicAuthSS(si); + + // TODO: While these test _should_ pass, and they _do_ pass on my local machine, they won't + // pass when then onap jobbuilder runs them. Good luck! +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(si, false); -// assertThat(auth.getID(), is(id)); + auth = new HBasicAuthSS(si, false); +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(si, id, password, false); -// assertThat(auth.getID(), is(id)); + auth = new HBasicAuthSS(si, id, password, false); +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(si, id, password, true); -// assertThat(auth.getID(), is(id)); + auth = new HBasicAuthSS(si, id, password, true); +// assertThat(auth.getID(), is(id)); - auth = new HBasicAuthSS(bpMock, si); -// assertThat(auth.getID(), is(id)); - - auth = new HBasicAuthSS(bpMock, si, false); -// assertThat(auth.getID(), is(id)); - - auth = new HBasicAuthSS(bpMock, si, true); -// assertThat(auth.getID(), is(id)); - } + auth = new HBasicAuthSS(bpMock, si); +// assertThat(auth.getID(), is(id)); + + auth = new HBasicAuthSS(bpMock, si, false); +// assertThat(auth.getID(), is(id)); + + auth = new HBasicAuthSS(bpMock, si, true); +// assertThat(auth.getID(), is(id)); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java index 646d63fa..c32abe43 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HClient.java @@ -51,270 +51,270 @@ import org.onap.aaf.misc.rosetta.env.RosettaData; public class JU_HClient { - @Mock private SecuritySetter<HttpURLConnection> ssMock; - @Mock private Transfer transferMock; - @Mock private HttpURLConnection hucMock; - @Mock private HttpServletResponse respMock; - @Mock private RosettaDF<HttpURLConnection> dfMock; - @Mock private RosettaData<HttpURLConnection> dataMock; - - private static final String uriString = "http://example.com:8080/path/to/a/file.txt"; - private static final String fragment = "fragment"; - private static final String method = "method"; - private static final String pathinfo = "pathinfo"; - private static final String queryParams = "queryParams"; - - private static final String errorString = "error string"; - private static final String successString = "success string"; - - private static final String tag1 = "tag1"; - private static final String tag2 = "tag2"; - private static final String value1 = "value1"; - private static final String value2 = "value2"; - - private URI uri; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - uri = new URI(uriString); - } - - @Test - public void accessorsMutatorsTest() throws LocatorException { - HClient client = new HClient(ssMock, uri, 0); - client.setFragment(fragment); - client.setMethod(method); - client.setPathInfo(pathinfo); - client.setPayload(transferMock); - client.setQueryParams(queryParams); - assertThat(client.getURI(), is(uri)); - assertThat(client.timeout(), is(0)); - assertThat(client.toString(), is("HttpURLConnection Client configured to " + uri.toString())); - } - - @Test - public void sendTest() throws LocatorException, APIException, URISyntaxException { - HClientStub client; - client = new HClientStub(ssMock, uri, 0, null); - client.send(); - - client.setPathInfo("/pathinfo"); - client.send(); - - client.setPathInfo("pathinfo"); - client.send(); - - client = new HClientStub(null, uri, 0, null); - client.send(); - - client.addHeader(tag1, value1); - client.addHeader(tag2, value2); - client.send(); - - client.setPayload(transferMock); - client.send(); - } - - @Test(expected = APIException.class) - public void sendThrows1Test() throws APIException, LocatorException, URISyntaxException { - HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); - client.send(); - } - - @Test(expected = APIException.class) - public void sendThrows2Test() throws APIException, LocatorException, URISyntaxException { - HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); - client.addHeader(tag1, value1); - client.addHeader(tag2, value2); - client.send(); - } - - @Test - public void futureCreateTest() throws LocatorException, CadiException, IOException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - HFuture<HttpURLConnection> future = (HFuture<HttpURLConnection>) client.futureCreate(HttpURLConnection.class); - - // Test a bad response code (default 0) without output - assertThat(future.get(0), is(false)); - assertThat(future.body().length(), is(0)); - - // Test a bad response code (default 0) with output - ByteArrayInputStream bais = new ByteArrayInputStream(errorString.getBytes()); - when(hucMock.getInputStream()).thenReturn(bais); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - - // Test a good response code - when(hucMock.getResponseCode()).thenReturn(201); - assertThat(future.get(0), is(true)); - } - - @Test - public void futureReadStringTest() throws LocatorException, CadiException, IOException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future<String> future = client.futureReadString(); - - // Test a bad response code (default 0) without output - assertThat(future.get(0), is(false)); - assertThat(future.body().length(), is(0)); - - // Test a bad response code (default 0) with output - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is(successString)); - } - - @Test - public void futureReadTest() throws LocatorException, CadiException, IOException, APIException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future<HttpURLConnection> future = client.futureRead(dfMock, null); - - // Test a bad response code (default 0) without output - assertThat(future.get(0), is(false)); - assertThat(future.body().length(), is(0)); - - // Test a bad response code (default 0) with output - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(dfMock.newData()).thenReturn(dataMock); - when(dataMock.in(null)).thenReturn(dataMock); - when(dataMock.load((InputStream)any())).thenReturn(dataMock); - when(dataMock.asObject()).thenReturn(hucMock); - when(dataMock.asString()).thenReturn(successString); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is(successString)); - } - - @Test - public void future1Test() throws LocatorException, CadiException, IOException, APIException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future<HttpURLConnection> future = client.future(hucMock); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is("200")); - - // Test a bad response code - when(hucMock.getResponseCode()).thenReturn(0); - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is(errorString)); - } - - @Test - public void future2Test() throws LocatorException, CadiException, IOException, APIException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - Future<Void> future = client.future(respMock, 200); - - ServletOutputStream sos = new ServletOutputStream() { - @Override public void write(int arg0) throws IOException { } - }; - when(respMock.getOutputStream()).thenReturn(sos); - - // Test a good response code - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - assertThat(future.body(), is(nullValue())); - - // Test a bad response code - when(hucMock.getResponseCode()).thenReturn(0); - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - assertThat(future.body(), is("")); - } - - @Test - public void hfutureTest() throws CadiException, IOException, LocatorException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - HFutureStub future = new HFutureStub(client, hucMock); - assertThat(future.get(0), is(false)); - - // Test a bad response code (default 0) with output - when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); - assertThat(future.get(0), is(false)); - - assertThat(future.get(0), is(false)); - - when(hucMock.getResponseCode()).thenReturn(200); - assertThat(future.get(0), is(true)); - - StringBuilder sb = future.inputStreamToString(new ByteArrayInputStream(errorString.getBytes())); - assertThat(sb.toString(), is(errorString)); - - assertThat(future.code(), is(200)); - assertThat(future.huc(), is(hucMock)); - - assertThat(future.exception(), is(nullValue())); - assertThat(future.header("string"), is(nullValue())); - - // coverage... - future.setHuc(null); - future.close(); - } - - @Test - public void headerTest() throws LocatorException { - HClient client = new HClientStub(ssMock, uri, 0, hucMock); - String tag1 = "tag1"; - String tag2 = "tag2"; - String value1 = "value1"; - String value2 = "value2"; - client.addHeader(tag1, value1); - client.addHeader(tag2, value2); - } - - @Test(expected = LocatorException.class) - public void throws1Test() throws LocatorException { - @SuppressWarnings("unused") - HClient client = new HClient(ssMock, null, 0); - } - - private class HClientStub extends HClient { - public HClientStub(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout, HttpURLConnection huc) throws LocatorException { - super(ss, uri, connectTimeout); - setHuc(huc); - } - public void setHuc(HttpURLConnection huc) { - Field field; - try { - field = HClient.class.getDeclaredField("huc"); - field.setAccessible(true); - field.set(this, huc); - field.setAccessible(false); - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - fail("Caught an exception: " + e.getMessage()); - } - } - @Override - public HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException { - return hucMock; - } - } - - private class HFutureStub extends HFuture<HttpURLConnection> { - public HFutureStub(HClient hClient, HttpURLConnection huc) { - hClient.super(huc); - } - - @Override public String body() { return null; } - public void setHuc(HttpURLConnection huc) { this.huc = huc; } - } + @Mock private SecuritySetter<HttpURLConnection> ssMock; + @Mock private Transfer transferMock; + @Mock private HttpURLConnection hucMock; + @Mock private HttpServletResponse respMock; + @Mock private RosettaDF<HttpURLConnection> dfMock; + @Mock private RosettaData<HttpURLConnection> dataMock; + + private static final String uriString = "http://example.com:8080/path/to/a/file.txt"; + private static final String fragment = "fragment"; + private static final String method = "method"; + private static final String pathinfo = "pathinfo"; + private static final String queryParams = "queryParams"; + + private static final String errorString = "error string"; + private static final String successString = "success string"; + + private static final String tag1 = "tag1"; + private static final String tag2 = "tag2"; + private static final String value1 = "value1"; + private static final String value2 = "value2"; + + private URI uri; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + uri = new URI(uriString); + } + + @Test + public void accessorsMutatorsTest() throws LocatorException { + HClient client = new HClient(ssMock, uri, 0); + client.setFragment(fragment); + client.setMethod(method); + client.setPathInfo(pathinfo); + client.setPayload(transferMock); + client.setQueryParams(queryParams); + assertThat(client.getURI(), is(uri)); + assertThat(client.timeout(), is(0)); + assertThat(client.toString(), is("HttpURLConnection Client configured to " + uri.toString())); + } + + @Test + public void sendTest() throws LocatorException, APIException, URISyntaxException { + HClientStub client; + client = new HClientStub(ssMock, uri, 0, null); + client.send(); + + client.setPathInfo("/pathinfo"); + client.send(); + + client.setPathInfo("pathinfo"); + client.send(); + + client = new HClientStub(null, uri, 0, null); + client.send(); + + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + client.send(); + + client.setPayload(transferMock); + client.send(); + } + + @Test(expected = APIException.class) + public void sendThrows1Test() throws APIException, LocatorException, URISyntaxException { + HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); + client.send(); + } + + @Test(expected = APIException.class) + public void sendThrows2Test() throws APIException, LocatorException, URISyntaxException { + HClientStub client = new HClientStub(ssMock, new URI("mailto:me@domain.com"), 0, null); + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + client.send(); + } + + @Test + public void futureCreateTest() throws LocatorException, CadiException, IOException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + HFuture<HttpURLConnection> future = (HFuture<HttpURLConnection>) client.futureCreate(HttpURLConnection.class); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + ByteArrayInputStream bais = new ByteArrayInputStream(errorString.getBytes()); + when(hucMock.getInputStream()).thenReturn(bais); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getResponseCode()).thenReturn(201); + assertThat(future.get(0), is(true)); + } + + @Test + public void futureReadStringTest() throws LocatorException, CadiException, IOException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<String> future = client.futureReadString(); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(successString)); + } + + @Test + public void futureReadTest() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<HttpURLConnection> future = client.futureRead(dfMock, null); + + // Test a bad response code (default 0) without output + assertThat(future.get(0), is(false)); + assertThat(future.body().length(), is(0)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(dfMock.newData()).thenReturn(dataMock); + when(dataMock.in(null)).thenReturn(dataMock); + when(dataMock.load((InputStream)any())).thenReturn(dataMock); + when(dataMock.asObject()).thenReturn(hucMock); + when(dataMock.asString()).thenReturn(successString); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(successString)); + } + + @Test + public void future1Test() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<HttpURLConnection> future = client.future(hucMock); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is("200")); + + // Test a bad response code + when(hucMock.getResponseCode()).thenReturn(0); + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is(errorString)); + } + + @Test + public void future2Test() throws LocatorException, CadiException, IOException, APIException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + Future<Void> future = client.future(respMock, 200); + + ServletOutputStream sos = new ServletOutputStream() { + @Override public void write(int arg0) throws IOException { } + }; + when(respMock.getOutputStream()).thenReturn(sos); + + // Test a good response code + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(successString.getBytes())); + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + assertThat(future.body(), is(nullValue())); + + // Test a bad response code + when(hucMock.getResponseCode()).thenReturn(0); + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + assertThat(future.body(), is("")); + } + + @Test + public void hfutureTest() throws CadiException, IOException, LocatorException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + HFutureStub future = new HFutureStub(client, hucMock); + assertThat(future.get(0), is(false)); + + // Test a bad response code (default 0) with output + when(hucMock.getInputStream()).thenReturn(new ByteArrayInputStream(errorString.getBytes())); + assertThat(future.get(0), is(false)); + + assertThat(future.get(0), is(false)); + + when(hucMock.getResponseCode()).thenReturn(200); + assertThat(future.get(0), is(true)); + + StringBuilder sb = future.inputStreamToString(new ByteArrayInputStream(errorString.getBytes())); + assertThat(sb.toString(), is(errorString)); + + assertThat(future.code(), is(200)); + assertThat(future.huc(), is(hucMock)); + + assertThat(future.exception(), is(nullValue())); + assertThat(future.header("string"), is(nullValue())); + + // coverage... + future.setHuc(null); + future.close(); + } + + @Test + public void headerTest() throws LocatorException { + HClient client = new HClientStub(ssMock, uri, 0, hucMock); + String tag1 = "tag1"; + String tag2 = "tag2"; + String value1 = "value1"; + String value2 = "value2"; + client.addHeader(tag1, value1); + client.addHeader(tag2, value2); + } + + @Test(expected = LocatorException.class) + public void throws1Test() throws LocatorException { + @SuppressWarnings("unused") + HClient client = new HClient(ssMock, null, 0); + } + + private class HClientStub extends HClient { + public HClientStub(SecuritySetter<HttpURLConnection> ss, URI uri, int connectTimeout, HttpURLConnection huc) throws LocatorException { + super(ss, uri, connectTimeout); + setHuc(huc); + } + public void setHuc(HttpURLConnection huc) { + Field field; + try { + field = HClient.class.getDeclaredField("huc"); + field.setAccessible(true); + field.set(this, huc); + field.setAccessible(false); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + fail("Caught an exception: " + e.getMessage()); + } + } + @Override + public HttpURLConnection getConnection(URI uri, StringBuilder pi) throws IOException { + return hucMock; + } + } + + private class HFutureStub extends HFuture<HttpURLConnection> { + public HFutureStub(HClient hClient, HttpURLConnection huc) { + hClient.super(huc); + } + + @Override public String body() { return null; } + public void setHuc(HttpURLConnection huc) { this.huc = huc; } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java index b7415a52..9d87d699 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java @@ -50,216 +50,216 @@ import org.onap.aaf.cadi.http.HMangr; import org.onap.aaf.misc.env.APIException; public class JU_HMangr { - - @Mock Locator<URI> locMock; - @Mock SecuritySetter<HttpURLConnection> ssMock; - @Mock Retryable<Void> retryableMock; - @Mock Retryable<Integer> goodRetry; - @Mock Locator.Item itemMock; - @Mock Rcli<Object> clientMock; - - private PropAccess access; - private URI uri; - private final static String uriString = "http://example.com"; - - @Before - public void setup() throws URISyntaxException { - MockitoAnnotations.initMocks(this); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - uri = new URI(uriString); - } - - @Test - public void sameTest() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - //coverage... - when(retryableMock.lastClient()).thenReturn(clientMock); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - CadiException cadiException; - - ConnectException connectException = new ConnectException(); - cadiException = new CadiException(connectException); - doThrow(cadiException).when(retryableMock).code(clientMock); - when(locMock.hasItems()).thenReturn(true).thenReturn(false); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - SocketException socketException = new SocketException(); - cadiException = new CadiException(socketException); - doThrow(cadiException).when(retryableMock).code(clientMock); - when(locMock.hasItems()).thenReturn(true).thenReturn(false); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - doThrow(connectException).when(retryableMock).code(clientMock); - assertThat(hman.same(ssMock, retryableMock), is(nullValue())); - - } - - @Test(expected = LocatorException.class) - public void throwsLocatorException1Test() throws LocatorException { - @SuppressWarnings("unused") - HMangr hman = new HMangr(access, null); - } - - @Test(expected = LocatorException.class) - public void throwsLocatorException2Test() throws LocatorException, APIException, CadiException { - HMangr hman = new HMangr(access, locMock); - hman.same(ssMock, retryableMock); - } - - @Test(expected = LocatorException.class) - public void throwsLocatorException3Test() throws LocatorException, APIException, CadiException { - HMangr hman = new HMangr(access, locMock); - when(locMock.best()).thenReturn(itemMock); - when(locMock.hasItems()).thenReturn(true).thenReturn(false); - hman.same(ssMock, retryableMock); - } - - @SuppressWarnings("unchecked") - @Test(expected = CadiException.class) - public void throwsCadiException1Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - when(retryableMock.code(clientMock)).thenThrow(CadiException.class); - hman.same(ssMock, retryableMock); - } - - @Test(expected = CadiException.class) - public void throwsCadiException2Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - - ConnectException connectException = new ConnectException(); - CadiException cadiException = new CadiException(connectException); - doThrow(cadiException).when(retryableMock).code(clientMock); - hman.same(ssMock, retryableMock); - } - - @Test(expected = CadiException.class) - public void throwsCadiException3Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - - SocketException socketException = new SocketException(); - CadiException cadiException = new CadiException(socketException); - doThrow(cadiException).when(retryableMock).code(clientMock); - hman.same(ssMock, retryableMock); - } - - @Test(expected = CadiException.class) - public void throwsCadiException4Test() throws LocatorException, APIException, CadiException, ConnectException { - HMangr hman = new HMangr(access, locMock); - when(retryableMock.item()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - when(retryableMock.lastClient()).thenReturn(clientMock); - - Exception e = new Exception(); - CadiException cadiException = new CadiException(e); - doThrow(cadiException).when(retryableMock).code(clientMock); - hman.same(ssMock, retryableMock); - } - - @Test - public void allTest() throws LocatorException, CadiException, APIException { - HManagerStub hman = new HManagerStub(access, locMock); - assertThat(hman.best(ssMock, retryableMock), is(nullValue())); - assertThat(hman.all(ssMock, retryableMock), is(nullValue())); - assertThat(hman.all(ssMock, retryableMock, true), is(nullValue())); - } - - @Test - public void oneOfTest() throws LocatorException, CadiException, APIException, ConnectException { - HMangr hman = new HMangr(access, locMock); - assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); - - try { - hman.oneOf(ssMock, retryableMock, true, "host"); - fail("Should've thrown an exception"); - } catch (LocatorException e) { - } - - when(locMock.first()).thenReturn(itemMock); - when(locMock.get(itemMock)).thenReturn(uri); - - // Branching coverage... - assertThat(hman.oneOf(ssMock, retryableMock, false, null), is(nullValue())); - assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); - - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - CadiException cadiException; - - cadiException = new CadiException(new ConnectException()); - doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - cadiException = new CadiException(new SSLHandshakeException(null)); - doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - cadiException = new CadiException(new SocketException()); - doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); - try { - hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); - fail("Should've thrown an exception"); - } catch (CadiException e) { - } - - cadiException = new CadiException(new SocketException("java.net.SocketException: Connection reset")); - doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); - try { - hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); - fail("Should've thrown an exception"); - } catch (CadiException e) { - } - - cadiException = new CadiException(); - doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); - try { - hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); - fail("Should've thrown an exception"); - } catch (CadiException e) { - } - - doThrow(new ConnectException()).when(retryableMock).code((Rcli<?>) any()); - assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); - - when(goodRetry.code((Rcli<?>) any())).thenReturn(5); - assertThat(hman.oneOf(ssMock, goodRetry, false, uriString.substring(7)), is(5)); - } - - @Test - public void coverageTest() throws LocatorException { - HMangr hman = new HMangr(access, locMock); - hman.readTimeout(5); - assertThat(hman.readTimeout(), is(5)); - hman.connectionTimeout(5); - assertThat(hman.connectionTimeout(), is(5)); - hman.apiVersion("v1.0"); - assertThat(hman.apiVersion(), is("v1.0")); - hman.close(); - - } - - private class HManagerStub extends HMangr { - public HManagerStub(Access access, Locator<URI> loc) throws LocatorException { super(access, loc); } - @Override public<RET> RET same(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) { - return null; - } - @Override public<RET> RET oneOf(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable, boolean notify, String host) { - return null; - } - } - + + @Mock Locator<URI> locMock; + @Mock SecuritySetter<HttpURLConnection> ssMock; + @Mock Retryable<Void> retryableMock; + @Mock Retryable<Integer> goodRetry; + @Mock Locator.Item itemMock; + @Mock Rcli<Object> clientMock; + + private PropAccess access; + private URI uri; + private final static String uriString = "http://example.com"; + + @Before + public void setup() throws URISyntaxException { + MockitoAnnotations.initMocks(this); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + uri = new URI(uriString); + } + + @Test + public void sameTest() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + //coverage... + when(retryableMock.lastClient()).thenReturn(clientMock); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + CadiException cadiException; + + ConnectException connectException = new ConnectException(); + cadiException = new CadiException(connectException); + doThrow(cadiException).when(retryableMock).code(clientMock); + when(locMock.hasItems()).thenReturn(true).thenReturn(false); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + SocketException socketException = new SocketException(); + cadiException = new CadiException(socketException); + doThrow(cadiException).when(retryableMock).code(clientMock); + when(locMock.hasItems()).thenReturn(true).thenReturn(false); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + doThrow(connectException).when(retryableMock).code(clientMock); + assertThat(hman.same(ssMock, retryableMock), is(nullValue())); + + } + + @Test(expected = LocatorException.class) + public void throwsLocatorException1Test() throws LocatorException { + @SuppressWarnings("unused") + HMangr hman = new HMangr(access, null); + } + + @Test(expected = LocatorException.class) + public void throwsLocatorException2Test() throws LocatorException, APIException, CadiException { + HMangr hman = new HMangr(access, locMock); + hman.same(ssMock, retryableMock); + } + + @Test(expected = LocatorException.class) + public void throwsLocatorException3Test() throws LocatorException, APIException, CadiException { + HMangr hman = new HMangr(access, locMock); + when(locMock.best()).thenReturn(itemMock); + when(locMock.hasItems()).thenReturn(true).thenReturn(false); + hman.same(ssMock, retryableMock); + } + + @SuppressWarnings("unchecked") + @Test(expected = CadiException.class) + public void throwsCadiException1Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + when(retryableMock.code(clientMock)).thenThrow(CadiException.class); + hman.same(ssMock, retryableMock); + } + + @Test(expected = CadiException.class) + public void throwsCadiException2Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + + ConnectException connectException = new ConnectException(); + CadiException cadiException = new CadiException(connectException); + doThrow(cadiException).when(retryableMock).code(clientMock); + hman.same(ssMock, retryableMock); + } + + @Test(expected = CadiException.class) + public void throwsCadiException3Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + + SocketException socketException = new SocketException(); + CadiException cadiException = new CadiException(socketException); + doThrow(cadiException).when(retryableMock).code(clientMock); + hman.same(ssMock, retryableMock); + } + + @Test(expected = CadiException.class) + public void throwsCadiException4Test() throws LocatorException, APIException, CadiException, ConnectException { + HMangr hman = new HMangr(access, locMock); + when(retryableMock.item()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + when(retryableMock.lastClient()).thenReturn(clientMock); + + Exception e = new Exception(); + CadiException cadiException = new CadiException(e); + doThrow(cadiException).when(retryableMock).code(clientMock); + hman.same(ssMock, retryableMock); + } + + @Test + public void allTest() throws LocatorException, CadiException, APIException { + HManagerStub hman = new HManagerStub(access, locMock); + assertThat(hman.best(ssMock, retryableMock), is(nullValue())); + assertThat(hman.all(ssMock, retryableMock), is(nullValue())); + assertThat(hman.all(ssMock, retryableMock, true), is(nullValue())); + } + + @Test + public void oneOfTest() throws LocatorException, CadiException, APIException, ConnectException { + HMangr hman = new HMangr(access, locMock); + assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); + + try { + hman.oneOf(ssMock, retryableMock, true, "host"); + fail("Should've thrown an exception"); + } catch (LocatorException e) { + } + + when(locMock.first()).thenReturn(itemMock); + when(locMock.get(itemMock)).thenReturn(uri); + + // Branching coverage... + assertThat(hman.oneOf(ssMock, retryableMock, false, null), is(nullValue())); + assertThat(hman.oneOf(ssMock, retryableMock, false, "host"), is(nullValue())); + + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + CadiException cadiException; + + cadiException = new CadiException(new ConnectException()); + doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + cadiException = new CadiException(new SSLHandshakeException(null)); + doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + cadiException = new CadiException(new SocketException()); + doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); + try { + hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); + fail("Should've thrown an exception"); + } catch (CadiException e) { + } + + cadiException = new CadiException(new SocketException("java.net.SocketException: Connection reset")); + doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); + try { + hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); + fail("Should've thrown an exception"); + } catch (CadiException e) { + } + + cadiException = new CadiException(); + doThrow(cadiException).when(retryableMock).code((Rcli<?>) any()); + try { + hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)); + fail("Should've thrown an exception"); + } catch (CadiException e) { + } + + doThrow(new ConnectException()).when(retryableMock).code((Rcli<?>) any()); + assertThat(hman.oneOf(ssMock, retryableMock, false, uriString.substring(7)), is(nullValue())); + + when(goodRetry.code((Rcli<?>) any())).thenReturn(5); + assertThat(hman.oneOf(ssMock, goodRetry, false, uriString.substring(7)), is(5)); + } + + @Test + public void coverageTest() throws LocatorException { + HMangr hman = new HMangr(access, locMock); + hman.readTimeout(5); + assertThat(hman.readTimeout(), is(5)); + hman.connectionTimeout(5); + assertThat(hman.connectionTimeout(), is(5)); + hman.apiVersion("v1.0"); + assertThat(hman.apiVersion(), is("v1.0")); + hman.close(); + + } + + private class HManagerStub extends HMangr { + public HManagerStub(Access access, Locator<URI> loc) throws LocatorException { super(access, loc); } + @Override public<RET> RET same(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable) { + return null; + } + @Override public<RET> RET oneOf(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable, boolean notify, String host) { + return null; + } + } + }
\ No newline at end of file diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java index 9179aa36..923dd1a0 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HNoAuthSS.java @@ -33,28 +33,28 @@ import org.onap.aaf.cadi.config.SecurityInfoC; import org.onap.aaf.cadi.http.HNoAuthSS; public class JU_HNoAuthSS { - - @Mock - SecurityInfoC<HttpURLConnection> siMock; - - @Mock - HttpURLConnection httpMock; + + @Mock + SecurityInfoC<HttpURLConnection> siMock; + + @Mock + HttpURLConnection httpMock; - @Mock - HttpsURLConnection httpsMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws IOException, CadiException { - HNoAuthSS noAuth = new HNoAuthSS(null); - noAuth.setSecurity(httpMock); - noAuth = new HNoAuthSS(siMock); - noAuth.setSecurity(httpMock); - noAuth.setSecurity(httpsMock); - } + @Mock + HttpsURLConnection httpsMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws IOException, CadiException { + HNoAuthSS noAuth = new HNoAuthSS(null); + noAuth.setSecurity(httpMock); + noAuth = new HNoAuthSS(siMock); + noAuth.setSecurity(httpMock); + noAuth.setSecurity(httpsMock); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java index 06055ad6..ab6a39c0 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HRcli.java @@ -44,78 +44,78 @@ import org.onap.aaf.cadi.http.HMangr; import org.onap.aaf.cadi.http.HRcli; public class JU_HRcli { - - @Mock - SecuritySetter<HttpURLConnection> ssMock; - - @Mock - Locator<URI> locMock; - - @Mock - Locator.Item itemMock; - - private HMangr hman; - private PropAccess access; - private static URI uri; - - private static final String uriString = "example.com"; - - @Before - public void setup() throws LocatorException, URISyntaxException { - MockitoAnnotations.initMocks(this); + + @Mock + SecuritySetter<HttpURLConnection> ssMock; + + @Mock + Locator<URI> locMock; + + @Mock + Locator.Item itemMock; + + private HMangr hman; + private PropAccess access; + private static URI uri; + + private static final String uriString = "example.com"; + + @Before + public void setup() throws LocatorException, URISyntaxException { + MockitoAnnotations.initMocks(this); - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - hman = new HMangr(access, locMock); - uri = new URI(uriString); + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + hman = new HMangr(access, locMock); + uri = new URI(uriString); - when(locMock.get(itemMock)).thenReturn(uri); - } + when(locMock.get(itemMock)).thenReturn(uri); + } - @Test(expected = CadiException.class) - public void publicInterfaceTest() throws URISyntaxException, LocatorException, CadiException { - HRcli hrcli = new HRcli(hman, itemMock, ssMock); - assertThat(hrcli.setManager(hman), is(hrcli)); - assertThat(hrcli.toString(), is(uriString)); + @Test(expected = CadiException.class) + public void publicInterfaceTest() throws URISyntaxException, LocatorException, CadiException { + HRcli hrcli = new HRcli(hman, itemMock, ssMock); + assertThat(hrcli.setManager(hman), is(hrcli)); + assertThat(hrcli.toString(), is(uriString)); - hrcli.setSecuritySetter(ssMock); - assertThat(hrcli.getSecuritySetter(), is(ssMock)); - - // No throw - hrcli.invalidate(); - // Throw - doThrow(CadiException.class).when(locMock).invalidate(itemMock); - hrcli.invalidate(); - } - - @Test(expected = CadiException.class) - public void protectedInterfaceTest() throws CadiException, LocatorException { - HRcliStub hrcli = new HRcliStub(hman, uri, itemMock, ssMock); - HRcli clone = hrcli.clone(uri, ssMock); - assertThat(clone.toString(), is(hrcli.toString())); - - EClient<HttpURLConnection> eclient = hrcli.client(); - assertThat(eclient, is(not(nullValue()))); + hrcli.setSecuritySetter(ssMock); + assertThat(hrcli.getSecuritySetter(), is(ssMock)); + + // No throw + hrcli.invalidate(); + // Throw + doThrow(CadiException.class).when(locMock).invalidate(itemMock); + hrcli.invalidate(); + } + + @Test(expected = CadiException.class) + public void protectedInterfaceTest() throws CadiException, LocatorException { + HRcliStub hrcli = new HRcliStub(hman, uri, itemMock, ssMock); + HRcli clone = hrcli.clone(uri, ssMock); + assertThat(clone.toString(), is(hrcli.toString())); + + EClient<HttpURLConnection> eclient = hrcli.client(); + assertThat(eclient, is(not(nullValue()))); - hrcli = new HRcliStub(hman, null, itemMock, ssMock); - when(locMock.best()).thenReturn(itemMock); - eclient = hrcli.client(); - assertThat(eclient, is(not(nullValue()))); + hrcli = new HRcliStub(hman, null, itemMock, ssMock); + when(locMock.best()).thenReturn(itemMock); + eclient = hrcli.client(); + assertThat(eclient, is(not(nullValue()))); - hrcli = new HRcliStub(hman, null, itemMock, ssMock); - when(locMock.best()).thenReturn(null); - eclient = hrcli.client(); - } - - private class HRcliStub extends HRcli { - public HRcliStub(HMangr hman, URI uri, Item locItem, SecuritySetter<HttpURLConnection> secSet) { - super(hman, uri, locItem, secSet); - } - public HRcli clone(URI uri, SecuritySetter<HttpURLConnection> ss) { - return super.clone(uri, ss); - } - public EClient<HttpURLConnection> client() throws CadiException { - return super.client(); - } - } + hrcli = new HRcliStub(hman, null, itemMock, ssMock); + when(locMock.best()).thenReturn(null); + eclient = hrcli.client(); + } + + private class HRcliStub extends HRcli { + public HRcliStub(HMangr hman, URI uri, Item locItem, SecuritySetter<HttpURLConnection> secSet) { + super(hman, uri, locItem, secSet); + } + public HRcli clone(URI uri, SecuritySetter<HttpURLConnection> ss) { + return super.clone(uri, ss); + } + public EClient<HttpURLConnection> client() throws CadiException { + return super.client(); + } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java index 0fb695ec..9f2c9a71 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTokenSS.java @@ -34,18 +34,18 @@ import org.onap.aaf.cadi.http.HTokenSS; public class JU_HTokenSS { - @Mock - SecurityInfoC<HttpURLConnection> siMock; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test() throws IOException { - HTokenSS token = new HTokenSS(siMock, "string1", "string2"); - assertThat(token, is(not(nullValue()))); - } + @Mock + SecurityInfoC<HttpURLConnection> siMock; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test() throws IOException { + HTokenSS token = new HTokenSS(siMock, "string1", "string2"); + assertThat(token, is(not(nullValue()))); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java index fcb25d4e..77fac567 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HTransferSS.java @@ -41,52 +41,52 @@ import org.onap.aaf.cadi.http.HTransferSS; import org.onap.aaf.cadi.principal.TaggedPrincipal; public class JU_HTransferSS { - - @Mock - TaggedPrincipal princMock; - - @Mock - HttpURLConnection hucMock; + + @Mock + TaggedPrincipal princMock; + + @Mock + HttpURLConnection hucMock; - @Mock - HttpsURLConnection hucsMock; + @Mock + HttpsURLConnection hucsMock; - @Mock - SecurityInfoC<HttpURLConnection> siMock; - - @Mock - SecurityInfoC<HttpURLConnection> siMockNoDefSS; + @Mock + SecurityInfoC<HttpURLConnection> siMock; + + @Mock + SecurityInfoC<HttpURLConnection> siMockNoDefSS; - @Mock - SecuritySetter<HttpURLConnection> ssMock; - - private static final String princName = "name"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - when(princMock.getName()).thenReturn(princName); - siMock.defSS = ssMock; - } + @Mock + SecuritySetter<HttpURLConnection> ssMock; + + private static final String princName = "name"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + when(princMock.getName()).thenReturn(princName); + siMock.defSS = ssMock; + } - @Test - public void test() throws IOException, CadiException { - HTransferSS transfer = new HTransferSS(princMock, "string1"); - assertThat(transfer.setLastResponse(0), is(0)); - - transfer = new HTransferSS(princMock, "string1", siMock); - transfer.setSecurity(hucsMock); - assertThat(transfer.getID(), is(princName)); + @Test + public void test() throws IOException, CadiException { + HTransferSS transfer = new HTransferSS(princMock, "string1"); + assertThat(transfer.setLastResponse(0), is(0)); + + transfer = new HTransferSS(princMock, "string1", siMock); + transfer.setSecurity(hucsMock); + assertThat(transfer.getID(), is(princName)); - transfer = new HTransferSS(null, "string1", siMock); - transfer.setSecurity(hucsMock); - assertThat(transfer.getID(), is("")); - } + transfer = new HTransferSS(null, "string1", siMock); + transfer.setSecurity(hucsMock); + assertThat(transfer.getID(), is("")); + } - @Test(expected = CadiException.class) - public void testThrows() throws CadiException { - HTransferSS transfer = new HTransferSS(princMock, "string1", siMockNoDefSS); - transfer.setSecurity(hucMock); - } + @Test(expected = CadiException.class) + public void testThrows() throws CadiException { + HTransferSS transfer = new HTransferSS(princMock, "string1", siMockNoDefSS); + transfer.setSecurity(hucMock); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java index b57f29e0..fd102a95 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HX509SS.java @@ -48,70 +48,70 @@ import org.onap.aaf.cadi.http.HX509SS; import org.onap.aaf.misc.env.APIException; public class JU_HX509SS { - - @Mock X509Certificate x509Mock; - @Mock X509KeyManager keyManagerMock; - @Mock PrivateKey privateKeyMock; - @Mock SecurityInfoC<HttpURLConnection> siMock; - @Mock HttpURLConnection hucMock; - @Mock HttpsURLConnection hucsMock; - - private final static String alias = "Some alias"; - private final static String algName = "Some algName"; - private final static byte[] publicKeyBytes = "a public key".getBytes(); - - private PropAccess access; - private SecurityInfoC<HttpURLConnection> si; - - @Before - public void setup() throws IOException, CadiException, CertificateEncodingException { - MockitoAnnotations.initMocks(this); - - when(x509Mock.getSigAlgName()).thenReturn(algName); - when(x509Mock.getEncoded()).thenReturn(publicKeyBytes); - - when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[] {x509Mock}); - when(keyManagerMock.getPrivateKey(alias)).thenReturn(privateKeyMock); + + @Mock X509Certificate x509Mock; + @Mock X509KeyManager keyManagerMock; + @Mock PrivateKey privateKeyMock; + @Mock SecurityInfoC<HttpURLConnection> siMock; + @Mock HttpURLConnection hucMock; + @Mock HttpsURLConnection hucsMock; + + private final static String alias = "Some alias"; + private final static String algName = "Some algName"; + private final static byte[] publicKeyBytes = "a public key".getBytes(); + + private PropAccess access; + private SecurityInfoC<HttpURLConnection> si; + + @Before + public void setup() throws IOException, CadiException, CertificateEncodingException { + MockitoAnnotations.initMocks(this); + + when(x509Mock.getSigAlgName()).thenReturn(algName); + when(x509Mock.getEncoded()).thenReturn(publicKeyBytes); + + when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[] {x509Mock}); + when(keyManagerMock.getPrivateKey(alias)).thenReturn(privateKeyMock); - when(siMock.getKeyManagers()).thenReturn(new X509KeyManager[] {keyManagerMock}); - - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - access.setProperty(Config.CADI_ALIAS, alias); - // si = SecurityInfoC.instance(access, HttpURLConnectionStub.class); - } + when(siMock.getKeyManagers()).thenReturn(new X509KeyManager[] {keyManagerMock}); + + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + access.setProperty(Config.CADI_ALIAS, alias); + // si = SecurityInfoC.instance(access, HttpURLConnectionStub.class); + } - @Test - public void test() throws APIException, CadiException { - HX509SS x509 = new HX509SS(alias, siMock); - assertThat(x509.getID(), is(alias)); - assertThat(x509.setLastResponse(0), is(0)); - assertThat(x509.setLastResponse(1), is(0)); - assertThat(x509.setLastResponse(2), is(0)); - - // coverage... - x509.setSecurity(hucMock); - x509.setSecurity(hucsMock); - } - - // TODO: Test the setSecurity method - Ian - // @Test - // public void test2() throws APIException, CadiException { - // HX509SS x509 = new HX509SS(si, false); - // x509.setSecurity(hucMock); - // x509.setSecurity(hucsMock); - // } - - @Test(expected = APIException.class) - public void throws1Test() throws APIException, CadiException { - @SuppressWarnings("unused") - HX509SS x509 = new HX509SS(siMock); - } + @Test + public void test() throws APIException, CadiException { + HX509SS x509 = new HX509SS(alias, siMock); + assertThat(x509.getID(), is(alias)); + assertThat(x509.setLastResponse(0), is(0)); + assertThat(x509.setLastResponse(1), is(0)); + assertThat(x509.setLastResponse(2), is(0)); + + // coverage... + x509.setSecurity(hucMock); + x509.setSecurity(hucsMock); + } + + // TODO: Test the setSecurity method - Ian + // @Test + // public void test2() throws APIException, CadiException { + // HX509SS x509 = new HX509SS(si, false); + // x509.setSecurity(hucMock); + // x509.setSecurity(hucsMock); + // } + + @Test(expected = APIException.class) + public void throws1Test() throws APIException, CadiException { + @SuppressWarnings("unused") + HX509SS x509 = new HX509SS(siMock); + } - @Test(expected = APIException.class) - public void throws3Test() throws APIException, CadiException { - when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[0]); - @SuppressWarnings("unused") - HX509SS x509 = new HX509SS(alias, siMock); - } - + @Test(expected = APIException.class) + public void throws3Test() throws APIException, CadiException { + when(keyManagerMock.getCertificateChain(alias)).thenReturn(new X509Certificate[0]); + @SuppressWarnings("unused") + HX509SS x509 = new HX509SS(alias, siMock); + } + } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java index a80e52f7..9b5bbafe 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_DNSLocator.java @@ -35,91 +35,91 @@ import org.onap.aaf.cadi.Locator.Item; import org.onap.aaf.cadi.locator.DNSLocator; public class JU_DNSLocator { - - private PropAccess access; - - @Before - public void setup() { - access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); - } - - @Test - public void test() throws LocatorException { - DNSLocator dl; - Item item; - URI uri; - - dl = new DNSLocator(access, "https", "localhost", "8100-8101"); - - item = dl.best(); - uri = dl.get(item); - assertThat(uri.toString(), is("https://127.0.0.1:8100")); - item = dl.best(); - assertThat(uri.toString(), is("https://127.0.0.1:8100")); - - assertThat(dl.hasItems(), is(true)); - for (item = dl.first(); item != null; item = dl.next(item)) { - dl.invalidate(item); - } - assertThat(dl.hasItems(), is(false)); - - // This doesn't actually do anything besides increase coverage - dl.destroy(); - } - - @Test - public void constructorTest() throws LocatorException { - // For coverage - new DNSLocator(access, "https", "localhost", "8100"); - new DNSLocator(access, "https", "localhost", "8100-8101"); - - new DNSLocator(access, "http:localhost"); - new DNSLocator(access, "https:localhost"); - new DNSLocator(access, "https:localhost:8100"); - new DNSLocator(access, "https:localhost:[8100]"); - new DNSLocator(access, "https:localhost:[8100-8101]"); - new DNSLocator(access, "https:localhost:8000/"); - } - - @Test - public void refreshTest() throws LocatorException { - DNSLocator dl = new DNSLocator(access, "https", "bogushost", "8100-8101"); - assertThat(dl.refresh(), is(false)); - } - - @Test(expected = LocatorException.class) - public void throws1Test() throws LocatorException { - new DNSLocator(access, null); - } - - @Test(expected = LocatorException.class) - public void throws2Test() throws LocatorException { - new DNSLocator(access, "ftp:invalid"); - } - - @Test(expected = LocatorException.class) - public void throws3Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[8100"); - } - - @Test(expected = LocatorException.class) - public void throws4Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[]"); - } - - @Test(expected = LocatorException.class) - public void throws5Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[8100-]"); - } - - @Test(expected = LocatorException.class) - public void throws6Test() throws LocatorException { - new DNSLocator(access, "https:localhost:[-8101]"); - } - - @Test(expected = LocatorException.class) - public void throws7Test() throws LocatorException { - new DNSLocator(access, "https:localhost:/"); - } + + private PropAccess access; + + @Before + public void setup() { + access = new PropAccess(new PrintStream(new ByteArrayOutputStream()), new String[0]); + } + + @Test + public void test() throws LocatorException { + DNSLocator dl; + Item item; + URI uri; + + dl = new DNSLocator(access, "https", "localhost", "8100-8101"); + + item = dl.best(); + uri = dl.get(item); + assertThat(uri.toString(), is("https://127.0.0.1:8100")); + item = dl.best(); + assertThat(uri.toString(), is("https://127.0.0.1:8100")); + + assertThat(dl.hasItems(), is(true)); + for (item = dl.first(); item != null; item = dl.next(item)) { + dl.invalidate(item); + } + assertThat(dl.hasItems(), is(false)); + + // This doesn't actually do anything besides increase coverage + dl.destroy(); + } + + @Test + public void constructorTest() throws LocatorException { + // For coverage + new DNSLocator(access, "https", "localhost", "8100"); + new DNSLocator(access, "https", "localhost", "8100-8101"); + + new DNSLocator(access, "http:localhost"); + new DNSLocator(access, "https:localhost"); + new DNSLocator(access, "https:localhost:8100"); + new DNSLocator(access, "https:localhost:[8100]"); + new DNSLocator(access, "https:localhost:[8100-8101]"); + new DNSLocator(access, "https:localhost:8000/"); + } + + @Test + public void refreshTest() throws LocatorException { + DNSLocator dl = new DNSLocator(access, "https", "bogushost", "8100-8101"); + assertThat(dl.refresh(), is(false)); + } + + @Test(expected = LocatorException.class) + public void throws1Test() throws LocatorException { + new DNSLocator(access, null); + } + + @Test(expected = LocatorException.class) + public void throws2Test() throws LocatorException { + new DNSLocator(access, "ftp:invalid"); + } + + @Test(expected = LocatorException.class) + public void throws3Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[8100"); + } + + @Test(expected = LocatorException.class) + public void throws4Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[]"); + } + + @Test(expected = LocatorException.class) + public void throws5Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[8100-]"); + } + + @Test(expected = LocatorException.class) + public void throws6Test() throws LocatorException { + new DNSLocator(access, "https:localhost:[-8101]"); + } + + @Test(expected = LocatorException.class) + public void throws7Test() throws LocatorException { + new DNSLocator(access, "https:localhost:/"); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java index 81140d23..e40ecb6e 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_HClientHotPeerLocator.java @@ -39,112 +39,112 @@ import org.onap.aaf.cadi.locator.HClientHotPeerLocator; public class JU_HClientHotPeerLocator { - @Mock private HX509SS ssMock; - - private PropAccess access; - private ByteArrayOutputStream outStream; - - // Note: - The IP and port are irrelevant for these tests - private static final String goodURL1 = "fakeIP1:fakePort1/38/-90"; // Approx St Louis - private static final String goodURL2 = "fakeIP2:fakePort2/33/-96"; // Approx Dallas - private static final String badURL = "~%$!@#$//"; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - - outStream = new ByteArrayOutputStream(); - access = new PropAccess(new PrintStream(outStream), new String[0]); - } - - @Test - public void test() throws LocatorException { - HClientHotPeerLocator loc; - String urlStr = goodURL1 + ',' + goodURL2; - loc = new HClientHotPeerLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); - assertThat(loc.hasItems(), is(true)); - - String[] messages = outStream.toString().split(System.lineSeparator()); - String preffered = messages[0].split(" ", 4)[3]; - String alternate = messages[1].split(" ", 4)[3]; - assertThat(preffered, is("Preferred Client is " + goodURL1)); - assertThat(alternate, is("Alternate Client is " + goodURL2)); - - HClient firstClient = loc.get(loc.first()); - HClient bestClient = loc.bestClient(); - assertThat(bestClient, is(firstClient)); - - Locator.Item item = loc.first(); - assertThat(loc.info(item), is(goodURL1)); - - item = loc.next(item); - assertThat(loc.info(item), is(goodURL2)); - - item = loc.next(item); - assertThat(item, is(nullValue())); - assertThat(loc.info(item), is("Invalid Item")); - - item = loc.first(); - loc.invalidate(item); - - loc.invalidate(loc.bestClient()); - loc.invalidate(loc.get(loc.next(item))); - loc.destroy(); - } - - @Test(expected = LocatorException.class) - public void failuresTest() throws LocatorException { - HClientHotPeerLocator loc; - String urlStr = goodURL1 + ',' + goodURL2 + ',' + badURL; - loc = new HClientHotPeerLocator(access, urlStr, 1000000, "38.627", "-90.199", ssMock); - String[] messages = outStream.toString().split(System.lineSeparator()); - String preffered = messages[0].split(" ", 4)[3]; - String alternate1 = messages[1].split(" ", 4)[3]; - String alternate2 = messages[2].split(" ", 4)[3]; - assertThat(preffered, is("Preferred Client is " + badURL)); - assertThat(alternate1, is("Alternate Client is " + goodURL1)); - assertThat(alternate2, is("Alternate Client is " + goodURL2)); - - outStream.reset(); - - loc.invalidate(loc.first()); - - loc.destroy(); - loc.best(); - } - - @Test - public void hasNoItemTest() throws LocatorException { - HClientHotPeerLocator loc; - loc = new HClientHotPeerLocator(access, badURL, 0, "38.627", "-90.199", ssMock); - assertThat(loc.hasItems(), is(false)); - loc.invalidate(loc.first()); - } - - @Test(expected = LocatorException.class) - public void invalidClientTest() throws LocatorException { - @SuppressWarnings("unused") - HClientHotPeerLocator loc = new HClientHotPeerLocator(access, "InvalidClient", 0, "38.627", "-90.199", ssMock); - } - - @Test(expected = LocatorException.class) - public void coverageTest() throws LocatorException { - CoverageLocator loc; - String urlStr = goodURL1 + ',' + goodURL2; - loc = new CoverageLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); - assertThat(loc._invalidate(null), is(nullValue())); - loc._destroy(null); - - loc._newClient("bad string"); - } - - private class CoverageLocator extends HClientHotPeerLocator { - public CoverageLocator(Access access, String urlstr, long invalidateTime, String localLatitude, - String localLongitude, HX509SS ss) throws LocatorException { - super(access, urlstr, invalidateTime, localLatitude, localLongitude, ss); - } - public HClient _newClient(String clientInfo) throws LocatorException { return super._newClient(clientInfo); } - public HClient _invalidate(HClient client) { return super._invalidate(client); } - public void _destroy(HClient client) { super._destroy(client); } - } + @Mock private HX509SS ssMock; + + private PropAccess access; + private ByteArrayOutputStream outStream; + + // Note: - The IP and port are irrelevant for these tests + private static final String goodURL1 = "fakeIP1:fakePort1/38/-90"; // Approx St Louis + private static final String goodURL2 = "fakeIP2:fakePort2/33/-96"; // Approx Dallas + private static final String badURL = "~%$!@#$//"; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + + outStream = new ByteArrayOutputStream(); + access = new PropAccess(new PrintStream(outStream), new String[0]); + } + + @Test + public void test() throws LocatorException { + HClientHotPeerLocator loc; + String urlStr = goodURL1 + ',' + goodURL2; + loc = new HClientHotPeerLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); + assertThat(loc.hasItems(), is(true)); + + String[] messages = outStream.toString().split(System.lineSeparator()); + String preffered = messages[0].split(" ", 4)[3]; + String alternate = messages[1].split(" ", 4)[3]; + assertThat(preffered, is("Preferred Client is " + goodURL1)); + assertThat(alternate, is("Alternate Client is " + goodURL2)); + + HClient firstClient = loc.get(loc.first()); + HClient bestClient = loc.bestClient(); + assertThat(bestClient, is(firstClient)); + + Locator.Item item = loc.first(); + assertThat(loc.info(item), is(goodURL1)); + + item = loc.next(item); + assertThat(loc.info(item), is(goodURL2)); + + item = loc.next(item); + assertThat(item, is(nullValue())); + assertThat(loc.info(item), is("Invalid Item")); + + item = loc.first(); + loc.invalidate(item); + + loc.invalidate(loc.bestClient()); + loc.invalidate(loc.get(loc.next(item))); + loc.destroy(); + } + + @Test(expected = LocatorException.class) + public void failuresTest() throws LocatorException { + HClientHotPeerLocator loc; + String urlStr = goodURL1 + ',' + goodURL2 + ',' + badURL; + loc = new HClientHotPeerLocator(access, urlStr, 1000000, "38.627", "-90.199", ssMock); + String[] messages = outStream.toString().split(System.lineSeparator()); + String preffered = messages[0].split(" ", 4)[3]; + String alternate1 = messages[1].split(" ", 4)[3]; + String alternate2 = messages[2].split(" ", 4)[3]; + assertThat(preffered, is("Preferred Client is " + badURL)); + assertThat(alternate1, is("Alternate Client is " + goodURL1)); + assertThat(alternate2, is("Alternate Client is " + goodURL2)); + + outStream.reset(); + + loc.invalidate(loc.first()); + + loc.destroy(); + loc.best(); + } + + @Test + public void hasNoItemTest() throws LocatorException { + HClientHotPeerLocator loc; + loc = new HClientHotPeerLocator(access, badURL, 0, "38.627", "-90.199", ssMock); + assertThat(loc.hasItems(), is(false)); + loc.invalidate(loc.first()); + } + + @Test(expected = LocatorException.class) + public void invalidClientTest() throws LocatorException { + @SuppressWarnings("unused") + HClientHotPeerLocator loc = new HClientHotPeerLocator(access, "InvalidClient", 0, "38.627", "-90.199", ssMock); + } + + @Test(expected = LocatorException.class) + public void coverageTest() throws LocatorException { + CoverageLocator loc; + String urlStr = goodURL1 + ',' + goodURL2; + loc = new CoverageLocator(access, urlStr, 0, "38.627", "-90.199", ssMock); + assertThat(loc._invalidate(null), is(nullValue())); + loc._destroy(null); + + loc._newClient("bad string"); + } + + private class CoverageLocator extends HClientHotPeerLocator { + public CoverageLocator(Access access, String urlstr, long invalidateTime, String localLatitude, + String localLongitude, HX509SS ss) throws LocatorException { + super(access, urlstr, invalidateTime, localLatitude, localLongitude, ss); + } + public HClient _newClient(String clientInfo) throws LocatorException { return super._newClient(clientInfo); } + public HClient _invalidate(HClient client) { return super._invalidate(client); } + public void _destroy(HClient client) { super._destroy(client); } + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java index 024deff7..7b61e398 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/locator/test/JU_PropertyLocator.java @@ -36,81 +36,81 @@ import org.onap.aaf.cadi.locator.PropertyLocator; public class JU_PropertyLocator { - @Mock - Socket socketMock; + @Mock + Socket socketMock; - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + @Before + public void setup() { + MockitoAnnotations.initMocks(this); - when(socketMock.isConnected()).thenReturn(true); - when(socketMock.isClosed()).thenReturn(true).thenReturn(false); - } + when(socketMock.isConnected()).thenReturn(true); + when(socketMock.isClosed()).thenReturn(true).thenReturn(false); + } - @Test - public void test() throws Exception { - String uris = "https://fred.wilma.com:26444,https://tom.jerry.com:[534-535]"; - PropertyLocator pl = new PropertyLocator(uris, 0L, 1000*60*20L) { - @Override protected Socket createSocket() { return socketMock; } - }; - String str = pl.toString(); - assertThat(str.contains("https://fred.wilma.com:26444"), is(true)); - assertThat(str.contains("https://tom.jerry.com:534"), is(true)); - assertThat(str.contains("https://tom.jerry.com:535"), is(true)); + @Test + public void test() throws Exception { + String uris = "https://fred.wilma.com:26444,https://tom.jerry.com:[534-535]"; + PropertyLocator pl = new PropertyLocator(uris, 0L, 1000*60*20L) { + @Override protected Socket createSocket() { return socketMock; } + }; + String str = pl.toString(); + assertThat(str.contains("https://fred.wilma.com:26444"), is(true)); + assertThat(str.contains("https://tom.jerry.com:534"), is(true)); + assertThat(str.contains("https://tom.jerry.com:535"), is(true)); - Item item = pl.first(); - assertThat(item.toString(), is("Item: 0 order: 0")); + Item item = pl.first(); + assertThat(item.toString(), is("Item: 0 order: 0")); - URI uri = pl.get(item); - assertThat(uri.toString(), is("https://fred.wilma.com:26444")); + URI uri = pl.get(item); + assertThat(uri.toString(), is("https://fred.wilma.com:26444")); - assertThat(pl.get(null), is(nullValue())); + assertThat(pl.get(null), is(nullValue())); - assertThat(pl.hasItems(), is(true)); + assertThat(pl.hasItems(), is(true)); - assertThat(countItems(pl), is(3)); - pl.invalidate(pl.best()); + assertThat(countItems(pl), is(3)); + pl.invalidate(pl.best()); - assertThat(countItems(pl), is(2)); - pl.invalidate(pl.best()); + assertThat(countItems(pl), is(2)); + pl.invalidate(pl.best()); - assertThat(countItems(pl), is(1)); + assertThat(countItems(pl), is(1)); - pl.invalidate(pl.best()); + pl.invalidate(pl.best()); - assertThat(pl.hasItems(), is(false)); - assertThat(countItems(pl), is(0)); + assertThat(pl.hasItems(), is(false)); + assertThat(countItems(pl), is(0)); - Thread.sleep(20L); // PL checks same milli... - pl.refresh(); + Thread.sleep(20L); // PL checks same milli... + pl.refresh(); - assertThat(pl.hasItems(), is(true)); - - assertThat(pl.next(null), is(nullValue())); + assertThat(pl.hasItems(), is(true)); + + assertThat(pl.next(null), is(nullValue())); - // coverage... - pl.invalidate(null); - pl.invalidate(null); - pl.invalidate(null); - pl.invalidate(null); + // coverage... + pl.invalidate(null); + pl.invalidate(null); + pl.invalidate(null); + pl.invalidate(null); - pl.destroy(); + pl.destroy(); - pl = new PropertyLocator(uris); - - } + pl = new PropertyLocator(uris); + + } - @Test(expected=LocatorException.class) - public void exceptionTest() throws LocatorException { - new PropertyLocator(null); - } + @Test(expected=LocatorException.class) + public void exceptionTest() throws LocatorException { + new PropertyLocator(null); + } - private int countItems(PropertyLocator pl) throws LocatorException { - int count = 0; - for(Item i = pl.first(); i != null; i = pl.next(i)) { - ++count; - } - return count; - } + private int countItems(PropertyLocator pl) throws LocatorException { + int count = 0; + for(Item i = pl.first(); i != null; i = pl.next(i)) { + ++count; + } + return count; + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java b/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java index f492d4a2..31fda501 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/routing/test/JU_GreatCircle.java @@ -28,52 +28,52 @@ import org.onap.aaf.cadi.routing.GreatCircle; public class JU_GreatCircle { - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void calc1Test() { - assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); - assertEquals(0.0, GreatCircle.calc(38.627345, -90.193774, 38.627345, -90.193774), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(35.252234, -81.384929, 38.627345, -90.193774), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(-38.627345, 90.193774, -35.252234, 81.384929), 0.000000001); - assertEquals(105.71060033936052, GreatCircle.calc(-38.627345, 90.193774, -35.252234, -81.384929), 0.000000001); - assertEquals(105.71060033936052, GreatCircle.calc(38.627345, -90.193774, 35.252234, 81.384929), 0.000000001); - assertEquals(74.32786874922931, GreatCircle.calc(-38.627345, 90.193774, 35.252234, 81.384929), 0.000000001); - } + @Test + public void calc1Test() { + assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); + assertEquals(0.0, GreatCircle.calc(38.627345, -90.193774, 38.627345, -90.193774), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(35.252234, -81.384929, 38.627345, -90.193774), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(38.627345, -90.193774, 35.252234, -81.384929), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(-38.627345, 90.193774, -35.252234, 81.384929), 0.000000001); + assertEquals(105.71060033936052, GreatCircle.calc(-38.627345, 90.193774, -35.252234, -81.384929), 0.000000001); + assertEquals(105.71060033936052, GreatCircle.calc(38.627345, -90.193774, 35.252234, 81.384929), 0.000000001); + assertEquals(74.32786874922931, GreatCircle.calc(-38.627345, 90.193774, 35.252234, 81.384929), 0.000000001); + } - @Test - public void calc2Test() { - assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345", "-90.193774", "35.252234", "-81.384929"}), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234,-81.384929"}), 0.000000001); - assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774,35.252234,-81.384929"}), 0.000000001); + @Test + public void calc2Test() { + assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345", "-90.193774", "35.252234", "-81.384929"}), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234,-81.384929"}), 0.000000001); + assertEquals(7.803062505568182, GreatCircle.calc(new String[] {"38.627345,-90.193774,35.252234,-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[0]), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"38.627345;-90.193774", "35.252234,-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234;-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774;35.252234,-81.384929"}), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[0]), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[] {"38.627345;-90.193774", "35.252234,-81.384929"}), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774", "35.252234;-81.384929"}), 0.000000001); + assertEquals(-1, GreatCircle.calc(new String[] {"38.627345,-90.193774;35.252234,-81.384929"}), 0.000000001); - assertEquals(-1, GreatCircle.calc(new String[] {"Invalid input", "Invalid input", "Invalid input", "Invalid input"}), 0.000000001); - } + assertEquals(-1, GreatCircle.calc(new String[] {"Invalid input", "Invalid input", "Invalid input", "Invalid input"}), 0.000000001); + } - @Test - public void coverageTest() { - @SuppressWarnings("unused") - GreatCircle gc = new GreatCircle(); - } + @Test + public void coverageTest() { + @SuppressWarnings("unused") + GreatCircle gc = new GreatCircle(); + } } diff --git a/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java b/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java index b0ac5a0c..5b47faab 100644 --- a/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java +++ b/cadi/client/src/test/java/org/onap/aaf/client/test/JU_ResultTest.java @@ -30,79 +30,79 @@ import org.onap.aaf.cadi.client.Result; public class JU_ResultTest { - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @Test - public void testOk() { - Result<String> t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testOk() { + Result<String> t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr() { - Result<String> t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } - - @Test - public void testOk1() { - Result<String> t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testErr() { + Result<String> t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } + + @Test + public void testOk1() { + Result<String> t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr1() { - Result<String> t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } - - @Test - public void testOk2() { - Result<String> t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testErr1() { + Result<String> t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } + + @Test + public void testOk2() { + Result<String> t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr2() { - Result<String> t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } - - @Test - public void testOk3() { - Result<String> t = Result.ok(1, "Ok"); - assertNotNull(t); - assertThat(t.code, is(1)); - assertTrue(t.isOK()); - assertThat(t.toString(), is("Code: 1")); - } + @Test + public void testErr2() { + Result<String> t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } + + @Test + public void testOk3() { + Result<String> t = Result.ok(1, "Ok"); + assertNotNull(t); + assertThat(t.code, is(1)); + assertTrue(t.isOK()); + assertThat(t.toString(), is("Code: 1")); + } - @Test - public void testErr3() { - Result<String> t = Result.err(1, "Error Body"); - assertNotNull(t); - assertThat(t.error, is("Error Body")); - assertFalse(t.isOK()); - assertThat(t.toString(), is("Code: 1 = Error Body")); - } + @Test + public void testErr3() { + Result<String> t = Result.err(1, "Error Body"); + assertNotNull(t); + assertThat(t.error, is("Error Body")); + assertFalse(t.isOK()); + assertThat(t.toString(), is("Code: 1 = Error Body")); + } } |